diff options
| author | zhangjie <iamkadisi@163.com> | 2019-08-14 15:38:44 +0800 |
|---|---|---|
| committer | zhangjie <iamkadisi@163.com> | 2019-08-16 22:22:17 +0800 |
| commit | 66672260cafc80bb32b26312cbcd0dcb5342b6dd (patch) | |
| tree | 133666b6fbbd8e982e45febcfe0b89bc1d93ee74 | |
| parent | unifying test component logging library to klog (diff) | |
| download | kubeedge-66672260cafc80bb32b26312cbcd0dcb5342b6dd.tar.gz | |
unifying other component logging library to klog
Signed-off-by: zhangjie <iamkadisi@163.com>
98 files changed, 459 insertions, 2043 deletions
diff --git a/cloud/cmd/cloudcore/cloudcore.go b/cloud/cmd/cloudcore/cloudcore.go index 4327d3171..9854364c7 100644 --- a/cloud/cmd/cloudcore/cloudcore.go +++ b/cloud/cmd/cloudcore/cloudcore.go @@ -5,17 +5,15 @@ import ( "os" "github.com/spf13/pflag" - "k8s.io/klog" "github.com/kubeedge/kubeedge/cloud/cmd/cloudcore/app" ) -func init() { +func main() { klog.InitFlags(nil) pflag.CommandLine.AddGoFlagSet(flag.CommandLine) -} -func main() { + command := app.NewCloudCoreCommand() if err := command.Execute(); err != nil { diff --git a/cloud/pkg/cloudhub/cloudhub.go b/cloud/pkg/cloudhub/cloudhub.go index 4bb923c98..0686b4abd 100644 --- a/cloud/pkg/cloudhub/cloudhub.go +++ b/cloud/pkg/cloudhub/cloudhub.go @@ -9,7 +9,6 @@ import ( "github.com/kubeedge/beehive/pkg/common/config" "github.com/kubeedge/beehive/pkg/core" "github.com/kubeedge/beehive/pkg/core/context" - "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/channelq" "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/common/util" chconfig "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/config" diff --git a/cloud/pkg/cloudhub/handler/eventhandler.go b/cloud/pkg/cloudhub/handler/eventhandler.go index be2463d0b..d552ed761 100644 --- a/cloud/pkg/cloudhub/handler/eventhandler.go +++ b/cloud/pkg/cloudhub/handler/eventhandler.go @@ -11,13 +11,12 @@ import ( "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/viaduct/pkg/conn" - "github.com/kubeedge/viaduct/pkg/mux" - "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/channelq" hubio "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/common/io" emodel "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/common/model" "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/common/util" + "github.com/kubeedge/viaduct/pkg/conn" + "github.com/kubeedge/viaduct/pkg/mux" ) // ExitCode exit code diff --git a/cloud/pkg/cloudhub/servers/quicserver/server.go b/cloud/pkg/cloudhub/servers/quicserver/server.go index 91186b2be..d57099061 100644 --- a/cloud/pkg/cloudhub/servers/quicserver/server.go +++ b/cloud/pkg/cloudhub/servers/quicserver/server.go @@ -8,12 +8,11 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/context" - "github.com/kubeedge/viaduct/pkg/api" - "github.com/kubeedge/viaduct/pkg/server" - "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/channelq" "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/common/util" "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/handler" + "github.com/kubeedge/viaduct/pkg/api" + "github.com/kubeedge/viaduct/pkg/server" ) // StartCloudHub starts the cloud hub service diff --git a/cloud/pkg/cloudhub/servers/wsserver/server.go b/cloud/pkg/cloudhub/servers/wsserver/server.go index c6ffc811a..6fd31b62c 100644 --- a/cloud/pkg/cloudhub/servers/wsserver/server.go +++ b/cloud/pkg/cloudhub/servers/wsserver/server.go @@ -8,13 +8,12 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/context" - "github.com/kubeedge/viaduct/pkg/api" - "github.com/kubeedge/viaduct/pkg/server" - "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/channelq" "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/common/model" "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/common/util" "github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/handler" + "github.com/kubeedge/viaduct/pkg/api" + "github.com/kubeedge/viaduct/pkg/server" ) // the api path diff --git a/cloud/pkg/devicecontroller/config/buffer.go b/cloud/pkg/devicecontroller/config/buffer.go index 9a9308603..4c849539f 100644 --- a/cloud/pkg/devicecontroller/config/buffer.go +++ b/cloud/pkg/devicecontroller/config/buffer.go @@ -4,7 +4,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/common/config" - "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" ) diff --git a/cloud/pkg/devicecontroller/config/context.go b/cloud/pkg/devicecontroller/config/context.go index 2f536e19c..e0c6f6718 100644 --- a/cloud/pkg/devicecontroller/config/context.go +++ b/cloud/pkg/devicecontroller/config/context.go @@ -5,7 +5,6 @@ import ( "github.com/kubeedge/beehive/pkg/common/config" "github.com/kubeedge/beehive/pkg/core/context" - "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" ) diff --git a/cloud/pkg/devicecontroller/config/kube.go b/cloud/pkg/devicecontroller/config/kube.go index f5604f081..b5cb6c57e 100644 --- a/cloud/pkg/devicecontroller/config/kube.go +++ b/cloud/pkg/devicecontroller/config/kube.go @@ -4,7 +4,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/common/config" - "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" ) diff --git a/cloud/pkg/devicecontroller/config/load.go b/cloud/pkg/devicecontroller/config/load.go index 595368fc2..7c1ad88b5 100644 --- a/cloud/pkg/devicecontroller/config/load.go +++ b/cloud/pkg/devicecontroller/config/load.go @@ -4,7 +4,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/common/config" - "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" ) diff --git a/cloud/pkg/devicecontroller/config/messagelayer.go b/cloud/pkg/devicecontroller/config/messagelayer.go index 2a9629091..a9e3d03cc 100644 --- a/cloud/pkg/devicecontroller/config/messagelayer.go +++ b/cloud/pkg/devicecontroller/config/messagelayer.go @@ -4,7 +4,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/common/config" - "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" ) diff --git a/cloud/pkg/devicecontroller/controller/downstream.go b/cloud/pkg/devicecontroller/controller/downstream.go index cf8c2507a..09dcd14e3 100644 --- a/cloud/pkg/devicecontroller/controller/downstream.go +++ b/cloud/pkg/devicecontroller/controller/downstream.go @@ -31,7 +31,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/cloud/pkg/apis/devices/v1alpha1" "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/manager" diff --git a/cloud/pkg/devicecontroller/controller/upstream.go b/cloud/pkg/devicecontroller/controller/upstream.go index 3a4bb851c..b8b263b84 100644 --- a/cloud/pkg/devicecontroller/controller/upstream.go +++ b/cloud/pkg/devicecontroller/controller/upstream.go @@ -24,7 +24,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/cloud/pkg/apis/devices/v1alpha1" "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/config" "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" diff --git a/cloud/pkg/devicecontroller/manager/device.go b/cloud/pkg/devicecontroller/manager/device.go index e2a0eab6f..431b63a68 100644 --- a/cloud/pkg/devicecontroller/manager/device.go +++ b/cloud/pkg/devicecontroller/manager/device.go @@ -3,14 +3,13 @@ package manager import ( "sync" - "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/config" - "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "github.com/kubeedge/kubeedge/cloud/pkg/apis/devices/v1alpha1" + "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/config" ) // DeviceManager is a manager watch device change event diff --git a/cloud/pkg/devicecontroller/manager/devicemodel.go b/cloud/pkg/devicecontroller/manager/devicemodel.go index ea80f74bc..ce9be46a2 100644 --- a/cloud/pkg/devicecontroller/manager/devicemodel.go +++ b/cloud/pkg/devicecontroller/manager/devicemodel.go @@ -3,14 +3,13 @@ package manager import ( "sync" - "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/config" - "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "github.com/kubeedge/kubeedge/cloud/pkg/apis/devices/v1alpha1" + "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/config" ) // DeviceModelManager is a manager watch DeviceModel change event diff --git a/cloud/pkg/devicecontroller/module.go b/cloud/pkg/devicecontroller/module.go index 7e0b1bb7d..3dd67c7da 100644 --- a/cloud/pkg/devicecontroller/module.go +++ b/cloud/pkg/devicecontroller/module.go @@ -8,7 +8,6 @@ import ( "github.com/kubeedge/beehive/pkg/core" bcontext "github.com/kubeedge/beehive/pkg/core/context" - "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/config" "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/constants" "github.com/kubeedge/kubeedge/cloud/pkg/devicecontroller/controller" diff --git a/cloud/pkg/edgecontroller/config/buffer.go b/cloud/pkg/edgecontroller/config/buffer.go index b414070d1..3520819f6 100644 --- a/cloud/pkg/edgecontroller/config/buffer.go +++ b/cloud/pkg/edgecontroller/config/buffer.go @@ -4,7 +4,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/common/config" - "github.com/kubeedge/kubeedge/common/constants" ) diff --git a/cloud/pkg/edgecontroller/config/context.go b/cloud/pkg/edgecontroller/config/context.go index c436a79f5..f14343f00 100644 --- a/cloud/pkg/edgecontroller/config/context.go +++ b/cloud/pkg/edgecontroller/config/context.go @@ -5,7 +5,6 @@ import ( "github.com/kubeedge/beehive/pkg/common/config" "github.com/kubeedge/beehive/pkg/core/context" - "github.com/kubeedge/kubeedge/common/constants" ) diff --git a/cloud/pkg/edgecontroller/config/load.go b/cloud/pkg/edgecontroller/config/load.go index 551f24d28..2a8811b83 100644 --- a/cloud/pkg/edgecontroller/config/load.go +++ b/cloud/pkg/edgecontroller/config/load.go @@ -4,7 +4,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/common/config" - "github.com/kubeedge/kubeedge/common/constants" ) diff --git a/cloud/pkg/edgecontroller/config/messagelayer.go b/cloud/pkg/edgecontroller/config/messagelayer.go index e9cf7f934..a85f06953 100644 --- a/cloud/pkg/edgecontroller/config/messagelayer.go +++ b/cloud/pkg/edgecontroller/config/messagelayer.go @@ -4,7 +4,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/common/config" - "github.com/kubeedge/kubeedge/common/constants" ) diff --git a/cloud/pkg/edgecontroller/controller.go b/cloud/pkg/edgecontroller/controller.go index 5b40e2047..635d362b1 100644 --- a/cloud/pkg/edgecontroller/controller.go +++ b/cloud/pkg/edgecontroller/controller.go @@ -6,7 +6,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core" - bcontext "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/config" "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/constants" diff --git a/cloud/pkg/edgecontroller/controller/downstream.go b/cloud/pkg/edgecontroller/controller/downstream.go index 444a67aaf..f3e0102f6 100644 --- a/cloud/pkg/edgecontroller/controller/downstream.go +++ b/cloud/pkg/edgecontroller/controller/downstream.go @@ -13,7 +13,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/config" "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/constants" "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/manager" diff --git a/cloud/pkg/edgecontroller/controller/upstream.go b/cloud/pkg/edgecontroller/controller/upstream.go index 799676dec..6040ec99d 100644 --- a/cloud/pkg/edgecontroller/controller/upstream.go +++ b/cloud/pkg/edgecontroller/controller/upstream.go @@ -36,7 +36,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/config" "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/constants" "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/messagelayer" diff --git a/cloud/pkg/edgecontroller/messagelayer/context.go b/cloud/pkg/edgecontroller/messagelayer/context.go index 1d710dd19..ab8f0473d 100644 --- a/cloud/pkg/edgecontroller/messagelayer/context.go +++ b/cloud/pkg/edgecontroller/messagelayer/context.go @@ -3,7 +3,6 @@ package messagelayer import ( "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/config" ) diff --git a/cloud/pkg/edgecontroller/messagelayer/layer.go b/cloud/pkg/edgecontroller/messagelayer/layer.go index 391153168..61b36a5ea 100644 --- a/cloud/pkg/edgecontroller/messagelayer/layer.go +++ b/cloud/pkg/edgecontroller/messagelayer/layer.go @@ -2,7 +2,6 @@ package messagelayer import ( "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/config" ) diff --git a/cloud/pkg/edgecontroller/messagelayer/util.go b/cloud/pkg/edgecontroller/messagelayer/util.go index 887fc31ce..ebaf53397 100644 --- a/cloud/pkg/edgecontroller/messagelayer/util.go +++ b/cloud/pkg/edgecontroller/messagelayer/util.go @@ -7,7 +7,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/config" controller "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/constants" "github.com/kubeedge/kubeedge/common/constants" diff --git a/edge/cmd/edgecore/edgecore.go b/edge/cmd/edgecore/edgecore.go index f17def5dd..77d944576 100644 --- a/edge/cmd/edgecore/edgecore.go +++ b/edge/cmd/edgecore/edgecore.go @@ -10,14 +10,11 @@ import ( "github.com/kubeedge/kubeedge/edge/cmd/edgecore/app" ) -func init() { +func main() { klog.InitFlags(nil) pflag.CommandLine.AddGoFlagSet(flag.CommandLine) -} -func main() { command := app.NewEdgeCoreCommand() - if err := command.Execute(); err != nil { os.Exit(1) } diff --git a/edge/mocks/beehive/fake_module.go b/edge/mocks/beehive/fake_module.go index 233f27716..5fa00359e 100644 --- a/edge/mocks/beehive/fake_module.go +++ b/edge/mocks/beehive/fake_module.go @@ -5,9 +5,11 @@ package beehive import ( + reflect "reflect" + gomock "github.com/golang/mock/gomock" + context "github.com/kubeedge/beehive/pkg/core/context" - reflect "reflect" ) // MockModule is a mock of Module interface diff --git a/edge/pkg/common/dbm/db.go b/edge/pkg/common/dbm/db.go index 628218e15..11ff0bf95 100644 --- a/edge/pkg/common/dbm/db.go +++ b/edge/pkg/common/dbm/db.go @@ -4,11 +4,11 @@ import ( "os" "strings" + "github.com/astaxie/beego/orm" //Blank import to run only the init function _ "github.com/mattn/go-sqlite3" "k8s.io/klog" - "github.com/astaxie/beego/orm" "github.com/kubeedge/beehive/pkg/common/config" ) diff --git a/edge/pkg/devicetwin/dtcontext/dtcontext.go b/edge/pkg/devicetwin/dtcontext/dtcontext.go index 96eb21d82..58f4a7798 100644 --- a/edge/pkg/devicetwin/dtcontext/dtcontext.go +++ b/edge/pkg/devicetwin/dtcontext/dtcontext.go @@ -11,7 +11,6 @@ import ( "github.com/kubeedge/beehive/pkg/common/config" "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/common/modules" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" diff --git a/edge/pkg/devicetwin/dtmanager/communicate.go b/edge/pkg/devicetwin/dtmanager/communicate.go index 00a0801ff..4a2ff739c 100644 --- a/edge/pkg/devicetwin/dtmanager/communicate.go +++ b/edge/pkg/devicetwin/dtmanager/communicate.go @@ -9,7 +9,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" - connect "github.com/kubeedge/kubeedge/edge/pkg/common/cloudconnection" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcontext" diff --git a/edge/pkg/devicetwin/dtmanager/device.go b/edge/pkg/devicetwin/dtmanager/device.go index 6781334d0..40de8e697 100644 --- a/edge/pkg/devicetwin/dtmanager/device.go +++ b/edge/pkg/devicetwin/dtmanager/device.go @@ -9,7 +9,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/common/modules" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtclient" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" diff --git a/edge/pkg/devicetwin/dtmanager/device_test.go b/edge/pkg/devicetwin/dtmanager/device_test.go index 68ba7b583..a3244cc58 100644 --- a/edge/pkg/devicetwin/dtmanager/device_test.go +++ b/edge/pkg/devicetwin/dtmanager/device_test.go @@ -28,7 +28,6 @@ import ( "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtclient" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcontext" diff --git a/edge/pkg/devicetwin/dtmanager/membership.go b/edge/pkg/devicetwin/dtmanager/membership.go index ae0f9372c..22a223566 100644 --- a/edge/pkg/devicetwin/dtmanager/membership.go +++ b/edge/pkg/devicetwin/dtmanager/membership.go @@ -10,7 +10,6 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/common/modules" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtclient" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" diff --git a/edge/pkg/devicetwin/dttype/types.go b/edge/pkg/devicetwin/dttype/types.go index dfb1810f6..e34faca91 100644 --- a/edge/pkg/devicetwin/dttype/types.go +++ b/edge/pkg/devicetwin/dttype/types.go @@ -6,10 +6,10 @@ import ( "strings" "time" + "github.com/satori/go.uuid" + "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtclient" "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" - - "github.com/satori/go.uuid" ) //Device the struct of device diff --git a/edge/pkg/edged/containers/container_manager.go b/edge/pkg/edged/containers/container_manager.go index 8f44a67d1..ad97bee50 100644 --- a/edge/pkg/edged/containers/container_manager.go +++ b/edge/pkg/edged/containers/container_manager.go @@ -41,8 +41,6 @@ import ( dockercontainer "github.com/docker/docker/api/types/container" dockerstrslice "github.com/docker/docker/api/types/strslice" "github.com/docker/go-connections/nat" - "github.com/kubeedge/kubeedge/edge/pkg/edged/apis" - "github.com/kubeedge/kubeedge/edge/pkg/edged/securitycontext" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -58,6 +56,9 @@ import ( schedulercache "k8s.io/kubernetes/pkg/scheduler/nodeinfo" hashutil "k8s.io/kubernetes/pkg/util/hash" "k8s.io/kubernetes/pkg/util/selinux" + + "github.com/kubeedge/kubeedge/edge/pkg/edged/apis" + "github.com/kubeedge/kubeedge/edge/pkg/edged/securitycontext" ) //Pod details constants diff --git a/edge/pkg/edged/edged_status.go b/edge/pkg/edged/edged_status.go index 0efed6ced..47b339377 100644 --- a/edge/pkg/edged/edged_status.go +++ b/edge/pkg/edged/edged_status.go @@ -31,15 +31,15 @@ import ( "strings" "time" - edgeapi "github.com/kubeedge/kubeedge/common/types" - "github.com/kubeedge/kubeedge/edge/pkg/edged/apis" - "github.com/kubeedge/kubeedge/edge/pkg/edged/util" - v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/klog" + + edgeapi "github.com/kubeedge/kubeedge/common/types" + "github.com/kubeedge/kubeedge/edge/pkg/edged/apis" + "github.com/kubeedge/kubeedge/edge/pkg/edged/util" ) //GPUInfoQueryTool sets information monitoring tool location for GPU diff --git a/edge/pkg/edged/images/image_gc_manager.go b/edge/pkg/edged/images/image_gc_manager.go index 397097f5b..faeec2be1 100644 --- a/edge/pkg/edged/images/image_gc_manager.go +++ b/edge/pkg/edged/images/image_gc_manager.go @@ -3,10 +3,10 @@ package images import ( "syscall" - "github.com/kubeedge/kubeedge/edge/pkg/edged/util" - statsapi "k8s.io/kubernetes/pkg/kubelet/apis/stats/v1alpha1" "k8s.io/kubernetes/pkg/kubelet/images" + + "github.com/kubeedge/kubeedge/edge/pkg/edged/util" ) type imageGCManager struct { diff --git a/edge/pkg/edged/volume_host.go b/edge/pkg/edged/volume_host.go index 51f834ea8..22dc416da 100644 --- a/edge/pkg/edged/volume_host.go +++ b/edge/pkg/edged/volume_host.go @@ -28,17 +28,15 @@ import ( "fmt" "net" + authenticationv1 "k8s.io/api/authentication/v1" api "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" + recordtools "k8s.io/client-go/tools/record" cloudprovider "k8s.io/cloud-provider" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/volume" - - "k8s.io/apimachinery/pkg/types" - - authenticationv1 "k8s.io/api/authentication/v1" - recordtools "k8s.io/client-go/tools/record" "k8s.io/kubernetes/pkg/volume/util/subpath" ) diff --git a/edge/pkg/edgehub/clients/wsclient/websocket_test.go b/edge/pkg/edgehub/clients/wsclient/websocket_test.go index b2cd72e44..0c16b2050 100644 --- a/edge/pkg/edgehub/clients/wsclient/websocket_test.go +++ b/edge/pkg/edgehub/clients/wsclient/websocket_test.go @@ -27,12 +27,11 @@ import ( "k8s.io/klog" "github.com/kubeedge/beehive/pkg/core/model" + "github.com/kubeedge/kubeedge/edge/pkg/common/util" "github.com/kubeedge/viaduct/pkg/api" "github.com/kubeedge/viaduct/pkg/conn" "github.com/kubeedge/viaduct/pkg/mux" "github.com/kubeedge/viaduct/pkg/server" - - "github.com/kubeedge/kubeedge/edge/pkg/common/util" ) //init() starts the test server and generates test certificates for testing diff --git a/edge/pkg/edgehub/controller.go b/edge/pkg/edgehub/controller.go index 39c87527f..a9bc87b5c 100644 --- a/edge/pkg/edgehub/controller.go +++ b/edge/pkg/edgehub/controller.go @@ -10,7 +10,6 @@ import ( bhconfig "github.com/kubeedge/beehive/pkg/common/config" "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - connect "github.com/kubeedge/kubeedge/edge/pkg/common/cloudconnection" "github.com/kubeedge/kubeedge/edge/pkg/common/message" "github.com/kubeedge/kubeedge/edge/pkg/common/modules" diff --git a/edge/pkg/edgehub/module_test.go b/edge/pkg/edgehub/module_test.go index 1e4727a1f..3b5148836 100644 --- a/edge/pkg/edgehub/module_test.go +++ b/edge/pkg/edgehub/module_test.go @@ -1,12 +1,13 @@ package edgehub import ( + "testing" + "time" + "github.com/kubeedge/beehive/pkg/core" "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" commodule "github.com/kubeedge/kubeedge/edge/pkg/common/modules" - "testing" - "time" ) // coreContext is beehive context used for communication between modules diff --git a/edge/pkg/eventbus/mqtt/client.go b/edge/pkg/eventbus/mqtt/client.go index 6f1604e3e..4aef7fd18 100644 --- a/edge/pkg/eventbus/mqtt/client.go +++ b/edge/pkg/eventbus/mqtt/client.go @@ -12,7 +12,6 @@ import ( "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/common/modules" "github.com/kubeedge/kubeedge/edge/pkg/eventbus/common/util" ) diff --git a/edge/pkg/metamanager/client/configmap.go b/edge/pkg/metamanager/client/configmap.go index 979e0cbe1..fbbc1438c 100644 --- a/edge/pkg/metamanager/client/configmap.go +++ b/edge/pkg/metamanager/client/configmap.go @@ -8,7 +8,6 @@ import ( "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/common/message" "github.com/kubeedge/kubeedge/edge/pkg/common/modules" ) diff --git a/edge/pkg/metamanager/module.go b/edge/pkg/metamanager/module.go index 6f5b2942e..a40bee65e 100644 --- a/edge/pkg/metamanager/module.go +++ b/edge/pkg/metamanager/module.go @@ -7,7 +7,6 @@ import ( "github.com/kubeedge/beehive/pkg/core" "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/common/dbm" "github.com/kubeedge/kubeedge/edge/pkg/common/modules" "github.com/kubeedge/kubeedge/edge/pkg/metamanager/dao" diff --git a/edge/pkg/metamanager/msg_processor.go b/edge/pkg/metamanager/msg_processor.go index fbf3cce9c..aaf3124d9 100644 --- a/edge/pkg/metamanager/msg_processor.go +++ b/edge/pkg/metamanager/msg_processor.go @@ -13,7 +13,6 @@ import ( "github.com/kubeedge/beehive/pkg/common/util" "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/common/constants" connect "github.com/kubeedge/kubeedge/edge/pkg/common/cloudconnection" messagepkg "github.com/kubeedge/kubeedge/edge/pkg/common/message" diff --git a/edge/pkg/servicebus/servicebus.go b/edge/pkg/servicebus/servicebus.go index 77d89ba25..37caf6e1d 100644 --- a/edge/pkg/servicebus/servicebus.go +++ b/edge/pkg/servicebus/servicebus.go @@ -13,7 +13,6 @@ import ( "github.com/kubeedge/beehive/pkg/core" "github.com/kubeedge/beehive/pkg/core/context" "github.com/kubeedge/beehive/pkg/core/model" - "github.com/kubeedge/kubeedge/edge/pkg/common/modules" "github.com/kubeedge/kubeedge/edge/pkg/servicebus/util" ) diff --git a/edge/test/integration/appdeployment/application_suite_test.go b/edge/test/integration/appdeployment/application_suite_test.go index c614bb2ef..464ddbdd0 100644 --- a/edge/test/integration/appdeployment/application_suite_test.go +++ b/edge/test/integration/appdeployment/application_suite_test.go @@ -19,11 +19,11 @@ package application_test import ( "testing" - "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" - "github.com/kubeedge/kubeedge/edge/test/integration/utils/edge" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + + "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" + "github.com/kubeedge/kubeedge/edge/test/integration/utils/edge" ) //context to load config and access across the package @@ -37,7 +37,7 @@ func TestEdgecoreAppDeployment(t *testing.T) { RegisterFailHandler(Fail) //var UID string var _ = BeforeSuite(func() { - common.InfoV6("Before Suite Execution") + common.Infof("Before Suite Execution") cfg = edge.LoadConfig() ctx = edge.NewTestContext(cfg) }) diff --git a/edge/test/integration/appdeployment/application_test.go b/edge/test/integration/appdeployment/application_test.go index f72b816fa..72cb2913d 100755 --- a/edge/test/integration/appdeployment/application_test.go +++ b/edge/test/integration/appdeployment/application_test.go @@ -20,15 +20,15 @@ import ( "net/http" "time" - "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" - "github.com/kubeedge/kubeedge/edge/test/integration/utils/edge" - . "github.com/kubeedge/kubeedge/edge/test/integration/utils/helpers" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/util/intstr" + + "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" + "github.com/kubeedge/kubeedge/edge/test/integration/utils/edge" + . "github.com/kubeedge/kubeedge/edge/test/integration/utils/helpers" ) const ( @@ -67,10 +67,10 @@ var _ = Describe("Application deployment in edgecore Testing", func() { CheckPodRunningState(ctx.Cfg.EdgedEndpoint+AppHandler, UID) pods, err := GetPods(ctx.Cfg.EdgedEndpoint + AppHandler) Expect(err).To(BeNil()) - common.Info("Get pods from Edged is Successful !!") + common.Infof("Get pods from Edged is Successful !!") for index := range pods.Items { pod := &pods.Items[index] - common.InfoV2("PodName: %s PodStatus: %s", pod.Name, pod.Status.Phase) + common.Infof("PodName: %s PodStatus: %s", pod.Name, pod.Status.Phase) } }) @@ -178,7 +178,7 @@ var _ = Describe("Application deployment in edgecore Testing", func() { UID = "deployment-app-" + edge.GetRandomString(10) memory, err2 := resource.ParseQuantity("1024Mi") if err2 != nil { - common.InfoV2("memory error") + common.Infof("memory error") } limit := v1.ResourceList{v1.ResourceMemory: memory} r := v1.ResourceRequirements{Limits: limit} @@ -197,7 +197,7 @@ var _ = Describe("Application deployment in edgecore Testing", func() { UID = "deployment-app-" + edge.GetRandomString(10) cpu, err := resource.ParseQuantity("0.75") if err != nil { - common.InfoV2("cpu resource parsing error") + common.Infof("cpu resource parsing error") } limit := v1.ResourceList{v1.ResourceCPU: cpu} r := v1.ResourceRequirements{Limits: limit} @@ -216,11 +216,11 @@ var _ = Describe("Application deployment in edgecore Testing", func() { UID = "deployment-app-" + edge.GetRandomString(10) cpu, err := resource.ParseQuantity("0.25") if err != nil { - common.InfoV2("cpu error") + common.Infof("cpu error") } memory, err := resource.ParseQuantity("256M") if err != nil { - common.InfoV2("memory error") + common.Infof("memory error") } cpuReq, err := resource.ParseQuantity("0.50") memoReq, err := resource.ParseQuantity("512Mi") @@ -242,11 +242,11 @@ var _ = Describe("Application deployment in edgecore Testing", func() { UID = "deployment-app-" + edge.GetRandomString(10) cpu, err := resource.ParseQuantity("0.75") if err != nil { - common.InfoV2("cpu error") + common.Infof("cpu error") } memory, err2 := resource.ParseQuantity("1024Mi") if err2 != nil { - common.InfoV2("memory error") + common.Infof("memory error") } cpuReq, err := resource.ParseQuantity("0.25") memoReq, err := resource.ParseQuantity("512Mi") diff --git a/edge/test/integration/device/device_suite_test.go b/edge/test/integration/device/device_suite_test.go index 553762aac..b10c29ace 100755 --- a/edge/test/integration/device/device_suite_test.go +++ b/edge/test/integration/device/device_suite_test.go @@ -21,13 +21,13 @@ import ( "testing" "time" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" + "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" "github.com/kubeedge/kubeedge/edge/test/integration/utils/edge" "github.com/kubeedge/kubeedge/edge/test/integration/utils/helpers" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" ) //context to load config and access across the package @@ -64,11 +64,12 @@ var ( //Function to run the Ginkgo Test func TestEdgecoreEventBus(t *testing.T) { + RegisterFailHandler(Fail) var _ = BeforeSuite(func() { MemDeviceUpdate = &MembershipUpdate{} - common.InfoV6("Before Suite execution") + common.Infof("Before Suite execution") cfg = edge.LoadConfig() ctx = edge.NewTestContext(cfg) @@ -76,16 +77,19 @@ func TestEdgecoreEventBus(t *testing.T) { }) AfterSuite(func() { By("After Suite Executing....!") - common.InfoV2("Remove Mock devices from edgenode !!") + common.Infof("Remove Mock devices from edgenode !!") //Deleting all the devices created for testing purposes. - IsDeviceDeleted := helpers.HandleAddAndDeleteDevice(http.MethodDelete, ctx.Cfg.TestManager+Devicehandler, DeviceN) + IsDeviceDeleted := helpers.HandleAddAndDeleteDevice(http.MethodDelete, + ctx.Cfg.TestManager+Devicehandler, DeviceN) Expect(IsDeviceDeleted).Should(BeTrue()) - IsDeviceDeleted = helpers.HandleAddAndDeleteDevice(http.MethodDelete, ctx.Cfg.TestManager+Devicehandler, DeviceATT) + IsDeviceDeleted = helpers.HandleAddAndDeleteDevice(http.MethodDelete, + ctx.Cfg.TestManager+Devicehandler, DeviceATT) Expect(IsDeviceDeleted).Should(BeTrue()) - IsDeviceDeleted = helpers.HandleAddAndDeleteDevice(http.MethodDelete, ctx.Cfg.TestManager+Devicehandler, DeviceTW) + IsDeviceDeleted = helpers.HandleAddAndDeleteDevice(http.MethodDelete, + ctx.Cfg.TestManager+Devicehandler, DeviceTW) Expect(IsDeviceDeleted).Should(BeTrue()) }) diff --git a/edge/test/integration/device/device_test.go b/edge/test/integration/device/device_test.go index 1510c4dc4..8ab003094 100755 --- a/edge/test/integration/device/device_test.go +++ b/edge/test/integration/device/device_test.go @@ -21,15 +21,15 @@ import ( "net/http" "strings" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" - "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" - . "github.com/kubeedge/kubeedge/edge/test/integration/utils/helpers" - MQTT "github.com/eclipse/paho.mqtt.golang" _ "github.com/mattn/go-sqlite3" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + + "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dtcommon" + "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" + "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" + . "github.com/kubeedge/kubeedge/edge/test/integration/utils/helpers" ) //Devicestate from subscribed MQTT topic @@ -73,7 +73,7 @@ func SubMessageReceived(client MQTT.Client, message MQTT.Message) { devicePayload := (message.Payload()) err := json.Unmarshal(devicePayload, &deviceState) if err != nil { - common.Failf("Unmarshall failed %s", err) + common.Fatalf("Unmarshall failed %s", err) } } DeviceState = deviceState.State @@ -84,7 +84,7 @@ func DeviceSubscribed(client MQTT.Client, message MQTT.Message) { devicePayload := (message.Payload()) err := json.Unmarshal(devicePayload, MemDeviceUpdate) if err != nil { - common.Failf("Unmarshall failed %s", err) + common.Fatalf("Unmarshall failed %s", err) } } } @@ -104,7 +104,7 @@ var _ = Describe("Event Bus Testing", func() { ClientOpts = HubClientInit(ctx.Cfg.MqttEndpoint, ClientID, "", "") Client = MQTT.NewClient(ClientOpts) if TokenClient = Client.Connect(); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Connect() Error is %s", TokenClient.Error()) + common.Fatalf("client.Connect() Error is %s", TokenClient.Error()) } }) AfterEach(func() { @@ -115,12 +115,12 @@ var _ = Describe("Event Bus Testing", func() { var data = "messagetoUpload_record_to_cloud" body, err := json.Marshal(data) if err != nil { - common.Failf("Marshal failed %v", err) + common.Fatalf("Marshal failed %v", err) } if TokenClient = Client.Publish(UploadRecordToCloud, 0, false, body); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Publish() Error is %s", TokenClient.Error()) + common.Fatalf("client.Publish() Error is %s", TokenClient.Error()) } else { - common.InfoV6("client.Publish Success !!") + common.Infof("client.Publish Success !!") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) @@ -130,12 +130,12 @@ var _ = Describe("Event Bus Testing", func() { var data = "messagetoDevice_status_update" body, err := json.Marshal(data) if err != nil { - common.Failf("Marshal failed %v", err) + common.Fatalf("Marshal failed %v", err) } if TokenClient = Client.Publish(DevicestatusUpdate, 0, false, body); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Publish() Error is %s", TokenClient.Error()) + common.Fatalf("client.Publish() Error is %s", TokenClient.Error()) } else { - common.InfoV6("client.Publish Success !!") + common.Infof("client.Publish Success !!") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) //Client.Disconnect(1) @@ -145,12 +145,12 @@ var _ = Describe("Event Bus Testing", func() { var data = "messagetoDevice_Twin_update" body, err := json.Marshal(data) if err != nil { - common.Failf("Marshal failed %v", err) + common.Fatalf("Marshal failed %v", err) } if TokenClient = Client.Publish(DeviceTwinUpdate, 0, false, body); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Publish() Error is %s", TokenClient.Error()) + common.Fatalf("client.Publish() Error is %s", TokenClient.Error()) } else { - common.InfoV6("client.Publish Success !!") + common.Infof("client.Publish Success !!") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) }) @@ -159,12 +159,12 @@ var _ = Describe("Event Bus Testing", func() { var data = "messagetoDevice_Membership_update" body, err := json.Marshal(data) if err != nil { - common.Failf("Marshal failed %v", err) + common.Fatalf("Marshal failed %v", err) } if TokenClient = Client.Publish(DeviceMembershipUpdate, 0, false, body); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Publish() Error is %s", TokenClient.Error()) + common.Fatalf("client.Publish() Error is %s", TokenClient.Error()) } else { - common.InfoV6("client.Publish Success !!") + common.Infof("client.Publish Success !!") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) }) @@ -173,12 +173,12 @@ var _ = Describe("Event Bus Testing", func() { var data = "messagetoDevice_upload" body, err := json.Marshal(data) if err != nil { - common.Failf("Marshal failed %v", err) + common.Fatalf("Marshal failed %v", err) } if TokenClient = Client.Publish(DeviceUpload, 0, false, body); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Publish() Error is %s", TokenClient.Error()) + common.Fatalf("client.Publish() Error is %s", TokenClient.Error()) } else { - common.InfoV6("client.Publish Success !!") + common.Infof("client.Publish Success !!") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) }) @@ -186,7 +186,7 @@ var _ = Describe("Event Bus Testing", func() { Context("Publish on eventbus topics throgh MQTT internal broker", func() { BeforeEach(func() { - common.InfoV2("Adding Mock device to edgenode !!") + common.Infof("Adding Mock device to edgenode !!") DeviceIDN = GenerateDeviceID("kubeedge-device-") DeviceN = CreateDevice(DeviceIDN, "edgedevice", "unknown") @@ -194,19 +194,19 @@ var _ = Describe("Event Bus Testing", func() { ClientOpts = HubClientInit(ctx.Cfg.MqttEndpoint, ClientID, "", "") Client = MQTT.NewClient(ClientOpts) if TokenClient = Client.Connect(); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Connect() Error is %s", TokenClient.Error()) + common.Fatalf("client.Connect() Error is %s", TokenClient.Error()) } Expect(TokenClient.Error()).NotTo(HaveOccurred()) devicetopic := dtcommon.MemETPrefix + ctx.Cfg.NodeID + dtcommon.MemETUpdateSuffix topic := dtcommon.DeviceETPrefix + DeviceIDN + dtcommon.DeviceETStateUpdateSuffix + "/result" Token := Client.Subscribe(devicetopic, 0, DeviceSubscribed) if Token.Wait() && TokenClient.Error() != nil { - common.Failf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), topic) + common.Fatalf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), topic) } Token = Client.Subscribe(topic, 0, SubMessageReceived) if Token.Wait() && TokenClient.Error() != nil { - common.Failf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), devicetopic) + common.Fatalf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), devicetopic) } IsDeviceAdded := HandleAddAndDeleteDevice(http.MethodPut, ctx.Cfg.TestManager+Devicehandler, DeviceN) Expect(IsDeviceAdded).Should(BeTrue()) @@ -222,7 +222,7 @@ var _ = Describe("Event Bus Testing", func() { topic := dtcommon.DeviceETPrefix + DeviceIDN + dtcommon.DeviceETStateUpdateSuffix + "/result" body, err := json.Marshal(message) if err != nil { - common.Failf("Marshal failed %v", err) + common.Fatalf("Marshal failed %v", err) } Eventually(func() string { var ID string @@ -230,9 +230,9 @@ var _ = Describe("Event Bus Testing", func() { if deviceEvent.ID == DeviceIDN { ID = deviceEvent.ID if TokenClient = Client.Publish(dtcommon.DeviceETPrefix+DeviceIDN+dtcommon.DeviceETStateUpdateSuffix, 0, false, body); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Publish() Error is %s", TokenClient.Error()) + common.Fatalf("client.Publish() Error is %s", TokenClient.Error()) } else { - common.InfoV6("client.Publish Success !!") + common.Infof("client.Publish Success !!") } } } @@ -240,7 +240,7 @@ var _ = Describe("Event Bus Testing", func() { }, "10s", "2s").Should(Equal(DeviceIDN), "Device state is not online within specified time") Expect(TokenClient.Error()).NotTo(HaveOccurred()) Eventually(func() string { - common.InfoV2("subscribed to the topic %v", topic) + common.Infof("subscribed to the topic %v", topic) return DeviceState }, "10s", "2s").Should(Equal("online"), "Device state is not online within specified time") }) @@ -251,16 +251,16 @@ var _ = Describe("Event Bus Testing", func() { topic := dtcommon.DeviceETPrefix + DeviceIDN + dtcommon.DeviceETStateUpdateSuffix + "/result" body, err := json.Marshal(message) if err != nil { - common.Failf("Marshal failed %v", err) + common.Fatalf("Marshal failed %v", err) } Eventually(func() string { var deviceEvent Device for _, deviceEvent = range MemDeviceUpdate.AddDevices { if strings.Compare(deviceEvent.ID, DeviceIDN) == 0 { if TokenClient = Client.Publish(dtcommon.DeviceETPrefix+DeviceIDN+dtcommon.DeviceETStateUpdateSuffix, 0, false, body); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Publish() Error is %s", TokenClient.Error()) + common.Fatalf("client.Publish() Error is %s", TokenClient.Error()) } else { - common.InfoV6("client.Publish Success !!") + common.Infof("client.Publish Success !!") } } } @@ -268,7 +268,7 @@ var _ = Describe("Event Bus Testing", func() { }, "10s", "2s").Should(Equal(DeviceIDN), "Device state is not online within specified time") Expect(TokenClient.Error()).NotTo(HaveOccurred()) Eventually(func() string { - common.InfoV2("subscribed to the topic %v", topic) + common.Infof("subscribed to the topic %v", topic) return DeviceState }, "10s", "2s").Should(Equal("unknown"), "Device state is not unknown within specified time") }) @@ -279,16 +279,16 @@ var _ = Describe("Event Bus Testing", func() { topic := dtcommon.DeviceETPrefix + DeviceIDN + dtcommon.DeviceETStateUpdateSuffix + "/result" body, err := json.Marshal(message) if err != nil { - common.Failf("Marshal failed %v", err) + common.Fatalf("Marshal failed %v", err) } Eventually(func() string { var deviceEvent Device for _, deviceEvent = range MemDeviceUpdate.AddDevices { if strings.Compare(deviceEvent.ID, DeviceIDN) == 0 { if TokenClient = Client.Publish(dtcommon.DeviceETPrefix+DeviceIDN+dtcommon.DeviceETStateUpdateSuffix, 0, false, body); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Publish() Error is %s", TokenClient.Error()) + common.Fatalf("client.Publish() Error is %s", TokenClient.Error()) } else { - common.InfoV6("client.Publish Success !!") + common.Infof("client.Publish Success !!") } } } @@ -296,7 +296,7 @@ var _ = Describe("Event Bus Testing", func() { }, "10s", "2s").Should(Equal(DeviceIDN), "Device state is not online within specified time") Expect(TokenClient.Error()).NotTo(HaveOccurred()) Eventually(func() string { - common.InfoV2("subscribed to the topic %v", topic) + common.Infof("subscribed to the topic %v", topic) return DeviceState }, "10s", "2s").Should(Equal("offline"), "Device state is not offline within specified time") }) @@ -322,7 +322,7 @@ var _ = Describe("Event Bus Testing", func() { Eventually(func() string { attributeDB := GetDeviceAttributesFromDB(DeviceIDWithAttr, "Temperature") - common.InfoV2("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Value) + common.Infof("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Value) return attributeDB.Value }, "60s", "2s").Should(Equal("25.25"), "Device is not added within specified time") @@ -341,7 +341,7 @@ var _ = Describe("Event Bus Testing", func() { Eventually(func() string { attributeDB := GetTwinAttributesFromDB(DeviceIDWithTwin, "Temperature") - common.InfoV2("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Expected) + common.Infof("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Expected) return attributeDB.Expected }, "60s", "2s").Should(Equal("25.25"), "Device is not added within specified time") @@ -359,7 +359,7 @@ var _ = Describe("Event Bus Testing", func() { Eventually(func() string { attributeDB := GetDeviceAttributesFromDB(DeviceIDWithAttr, "Temperature") - common.InfoV2("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Value) + common.Infof("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Value) return attributeDB.Value }, "60s", "2s").Should(Equal("50.50"), "Device Attributes are not updated within specified time") @@ -377,7 +377,7 @@ var _ = Describe("Event Bus Testing", func() { Eventually(func() string { attributeDB := GetTwinAttributesFromDB(DeviceIDWithTwin, "Temperature") - common.InfoV2("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Expected) + common.Infof("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Expected) return attributeDB.Expected }, "60s", "2s").Should(Equal("50.50"), "Device Twin Attributes are not updated within specified time") @@ -392,7 +392,7 @@ var _ = Describe("Event Bus Testing", func() { Eventually(func() string { attributeDB := GetDeviceAttributesFromDB(DeviceIDWithAttr, "Humidity") - common.InfoV2("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Value) + common.Infof("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Value) return attributeDB.Value }, "60s", "2s").Should(Equal("30"), "Device Attributes are not Added within specified time") @@ -407,7 +407,7 @@ var _ = Describe("Event Bus Testing", func() { Eventually(func() string { attributeDB := GetTwinAttributesFromDB(DeviceIDWithTwin, "Humidity") - common.InfoV2("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Expected) + common.Infof("DeviceID= %s, Value= %s", attributeDB.DeviceID, attributeDB.Expected) return attributeDB.Expected }, "60s", "2s").Should(Equal("100.100"), "Device Twin Attributes are not Added within specified time") diff --git a/edge/test/integration/scripts/fast_test b/edge/test/integration/scripts/fast_test index ce3934ca2..a7d019a3d 100755 --- a/edge/test/integration/scripts/fast_test +++ b/edge/test/integration/scripts/fast_test @@ -18,7 +18,6 @@ cd `dirname $0` workdir=`pwd` cd $workdir -debugflag="-v 6 -alsologtostderr" compilemodule=$1 runtest=$2 @@ -39,9 +38,9 @@ END if [ $# -eq 0 ] then #run testcase - ./appdeployment/appdeployment.test $debugflag 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log - ./device/device.test $debugflag 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log + ./appdeployment/appdeployment.test 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log + ./device/device.test 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log else - ./$compilemodule/$compilemodule.test $debugflag $runtest 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log + ./$compilemodule/$compilemodule.test $runtest 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log fi diff --git a/edge/test/integration/utils/common/log.go b/edge/test/integration/utils/common/log.go index 30bdbc80a..5a93357e7 100755 --- a/edge/test/integration/utils/common/log.go +++ b/edge/test/integration/utils/common/log.go @@ -21,7 +21,6 @@ import ( "time" "github.com/onsi/ginkgo" - "k8s.io/klog" ) //Function to get time in millisec @@ -35,25 +34,16 @@ func logf(level string, format string, args ...interface{}) { } //Funciton to log Filure logs -func Failf(format string, args ...interface{}) { +func Fatalf(format string, args ...interface{}) { msg := fmt.Sprintf(format, args...) logf("FAIL", msg) ginkgo.Fail(nowStamp()+": "+msg, 1) } //function for log level -func Info(format string, args ...interface{}) { - klog.V(4).Infof(format, args...) -} - -//function for log level -func InfoV2(format string, args ...interface{}) { - klog.V(2).Infof(format, args...) -} - -//function for log level -func InfoV6(format string, args ...interface{}) { - klog.V(5).Infof(format, args...) +func Infof(format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + logf("INFO", msg) } //Function to print the test case name and status of execution @@ -66,5 +56,5 @@ func PrintTestcaseNameandStatus() { } else { Status = "PASSED" } - InfoV6("TestCase:%40s Status=%s", testdesc.TestText, Status) + Infof("TestCase:%40s Status=%s", testdesc.TestText, Status) } diff --git a/edge/test/integration/utils/edge/config.go b/edge/test/integration/utils/edge/config.go index 8cb931da3..1a8e6fbd6 100755 --- a/edge/test/integration/utils/edge/config.go +++ b/edge/test/integration/utils/edge/config.go @@ -51,7 +51,7 @@ func loadConfigJSONFromPath() *Config { path := getConfigPath() _, err := filepath.Abs(filepath.Dir(path)) if err != nil { - common.InfoV6("Failed to get Abs path: %v", err) + common.Infof("Failed to get Abs path: %v", err) panic(err) } config := &Config{} diff --git a/edge/test/integration/utils/helpers/helpers.go b/edge/test/integration/utils/helpers/helpers.go index 1c1c9431b..b371c9647 100644 --- a/edge/test/integration/utils/helpers/helpers.go +++ b/edge/test/integration/utils/helpers/helpers.go @@ -28,15 +28,15 @@ import ( "path/filepath" "time" - "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" - "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" - "github.com/kubeedge/kubeedge/edge/test/integration/utils/edge" - MQTT "github.com/eclipse/paho.mqtt.golang" "github.com/onsi/gomega" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" + + "github.com/kubeedge/kubeedge/edge/pkg/devicetwin/dttype" + "github.com/kubeedge/kubeedge/edge/test/integration/utils/common" + "github.com/kubeedge/kubeedge/edge/test/integration/utils/edge" ) //DeviceUpdate device update @@ -133,24 +133,24 @@ func GetDeviceStateFromDB(deviceID string) string { pwd, err := os.Getwd() if err != nil { - common.Failf("Failed to get PWD: %v", err) + common.Fatalf("Failed to get PWD: %v", err) os.Exit(1) } destpath := filepath.Join(pwd, "../../edge.db") db, err := sql.Open("sqlite3", destpath) if err != nil { - common.Failf("Open Sqlite DB failed : %v", err) + common.Fatalf("Open Sqlite DB failed : %v", err) } defer db.Close() row, err := db.Query("SELECT * FROM device") if err != nil { - common.Failf("Query Sqlite DB failed: %v", err) + common.Fatalf("Query Sqlite DB failed: %v", err) } defer row.Close() for row.Next() { err = row.Scan(&device.ID, &device.Name, &device.Description, &device.State, &device.LastOnline) if err != nil { - common.Failf("Failed to scan DB rows: %v", err) + common.Fatalf("Failed to scan DB rows: %v", err) } if string(device.ID) == deviceID { break @@ -163,13 +163,13 @@ func GetTwinAttributesFromDB(deviceID string, Name string) TwinAttribute { var twinAttribute TwinAttribute pwd, err := os.Getwd() if err != nil { - common.Failf("Failed to get PWD: %v", err) + common.Fatalf("Failed to get PWD: %v", err) os.Exit(1) } destpath := filepath.Join(pwd, "../../edge.db") db, err := sql.Open("sqlite3", destpath) if err != nil { - common.Failf("Open Sqlite DB failed : %v", err) + common.Fatalf("Open Sqlite DB failed : %v", err) } defer db.Close() row, err := db.Query("SELECT * FROM device_twin") @@ -191,7 +191,7 @@ func GetTwinAttributesFromDB(deviceID string, Name string) TwinAttribute { &twinAttribute.MetaData) if err != nil { - common.Failf("Failed to scan DB rows: %v", err) + common.Fatalf("Failed to scan DB rows: %v", err) } if string(twinAttribute.DeviceID) == deviceID && twinAttribute.Name == Name { break @@ -205,13 +205,13 @@ func GetDeviceAttributesFromDB(deviceID string, Name string) Attribute { pwd, err := os.Getwd() if err != nil { - common.Failf("Failed to get PWD: %v", err) + common.Fatalf("Failed to get PWD: %v", err) os.Exit(1) } destPath := filepath.Join(pwd, "../../edge.db") db, err := sql.Open("sqlite3", destPath) if err != nil { - common.Failf("Open Sqlite DB failed : %v", err) + common.Fatalf("Open Sqlite DB failed : %v", err) } defer db.Close() row, err := db.Query("SELECT * FROM device_attr") @@ -220,7 +220,7 @@ func GetDeviceAttributesFromDB(deviceID string, Name string) Attribute { for row.Next() { err = row.Scan(&attribute.ID, &attribute.DeviceID, &attribute.Name, &attribute.Description, &attribute.Value, &attribute.Optional, &attribute.Type, &attribute.MetaData) if err != nil { - common.Failf("Failed to scan DB rows: %v", err) + common.Fatalf("Failed to scan DB rows: %v", err) } if string(attribute.DeviceID) == deviceID && attribute.Name == Name { break @@ -259,20 +259,20 @@ func HandleAddAndDeleteDevice(operation, testMgrEndPoint string, device dttype.D device, }} default: - common.Failf("operation %q is invalid", operation) + common.Fatalf("operation %q is invalid", operation) return false } respbytes, err := json.Marshal(payload) if err != nil { - common.Failf("Payload marshalling failed: %v", err) + common.Fatalf("Payload marshalling failed: %v", err) return false } req, err := http.NewRequest(httpMethod, testMgrEndPoint, bytes.NewBuffer(respbytes)) if err != nil { // handle error - common.Failf("Frame HTTP request failed: %v", err) + common.Fatalf("Frame HTTP request failed: %v", err) return false } @@ -283,10 +283,10 @@ func HandleAddAndDeleteDevice(operation, testMgrEndPoint string, device dttype.D if err != nil { // handle error - common.Failf("HTTP request is failed :%v", err) + common.Fatalf("HTTP request is failed :%v", err) return false } - common.InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + common.Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) return true } @@ -299,7 +299,7 @@ func HandleAddAndDeletePods(operation string, edgedpoint string, UID string, con case "DELETE": httpMethod = http.MethodDelete default: - common.Failf("operation %q is invalid", operation) + common.Fatalf("operation %q is invalid", operation) return false } @@ -310,24 +310,24 @@ func HandleAddAndDeletePods(operation string, edgedpoint string, UID string, con } respbytes, err := json.Marshal(payload) if err != nil { - common.Failf("Payload marshalling failed: %v", err) + common.Fatalf("Payload marshalling failed: %v", err) return false } req, err := http.NewRequest(httpMethod, edgedpoint, bytes.NewBuffer(respbytes)) if err != nil { // handle error - common.Failf("Frame HTTP request failed: %v", err) + common.Fatalf("Frame HTTP request failed: %v", err) return false } req.Header.Set("Content-Type", "application/json; charset=utf-8") t := time.Now() client := &http.Client{} resp, err := client.Do(req) - common.InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + common.Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) if err != nil { // handle error - common.Failf("HTTP request is failed :%v", err) + common.Fatalf("HTTP request is failed :%v", err) return false } return true @@ -342,24 +342,24 @@ func GetPods(EdgedEndpoint string) (v1.PodList, error) { req, err := http.NewRequest(http.MethodGet, EdgedEndpoint, bytes) req.Header.Set("Content-Type", "application/json; charset=utf-8") if err != nil { - common.Failf("Frame HTTP request failed: %v", err) + common.Fatalf("Frame HTTP request failed: %v", err) return pods, nil } resp, err := client.Do(req) if err != nil { - common.Failf("Sending HTTP request failed: %v", err) + common.Fatalf("Sending HTTP request failed: %v", err) return pods, nil } - common.InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + common.Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { - common.Failf("HTTP Response reading has failed: %v", err) + common.Fatalf("HTTP Response reading has failed: %v", err) return pods, nil } err = json.Unmarshal(contents, &pods) if err != nil { - common.Failf("Unmarshal HTTP Response has failed: %v", err) + common.Fatalf("Unmarshal HTTP Response has failed: %v", err) return pods, nil } return pods, nil @@ -374,7 +374,7 @@ func CheckPodRunningState(EdgedEndPoint, podname string) { pod := &pods.Items[index] if podname == pod.Name { status = string(pod.Status.Phase) - common.InfoV2("PodName: %s PodStatus: %s", pod.Name, pod.Status.Phase) + common.Infof("PodName: %s PodStatus: %s", pod.Name, pod.Status.Phase) } } return status @@ -389,7 +389,7 @@ func CheckPodDeletion(EdgedEndPoint, UID string) { if len(pods.Items) > 0 { for index := range pods.Items { pod := &pods.Items[index] - common.InfoV2("PodName: %s PodStatus: %s", pod.Name, pod.Status.Phase) + common.Infof("PodName: %s PodStatus: %s", pod.Name, pod.Status.Phase) if pod.Name == UID { IsExist = true } diff --git a/edgesite/cmd/edgesite.go b/edgesite/cmd/edgesite.go index c3beadd73..faf841082 100644 --- a/edgesite/cmd/edgesite.go +++ b/edgesite/cmd/edgesite.go @@ -10,14 +10,11 @@ import ( "github.com/kubeedge/kubeedge/edgesite/cmd/app" ) -func init() { +func main() { klog.InitFlags(nil) pflag.CommandLine.AddGoFlagSet(flag.CommandLine) -} -func main() { command := app.NewEdgeSiteCommand() - if err := command.Execute(); err != nil { os.Exit(1) } @@ -30,7 +30,6 @@ require ( github.com/go-mesh/openlogging v1.0.0 github.com/godbus/dbus v0.0.0-20181101234600-2ff6f7ffd60f // indirect github.com/gogo/protobuf v1.2.1 // indirect - github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 // indirect github.com/golang/mock v1.3.1 github.com/google/cadvisor v0.33.2-0.20190411163913-9db8c7dee20a @@ -86,7 +85,7 @@ require ( k8s.io/client-go v0.0.0 k8s.io/cloud-provider v0.0.0 k8s.io/cri-api v0.0.0 - k8s.io/klog v0.3.3 + k8s.io/klog v0.4.0 k8s.io/kube-openapi v0.0.0-20190718094010-3cf2ea392886 // indirect k8s.io/kubernetes v1.15.1 k8s.io/utils v0.0.0-20190712204705-3dccf664f023 diff --git a/keadm/app/cmd/common/config.go b/keadm/app/cmd/common/config.go index c3e0824e6..e1b259a6a 100644 --- a/keadm/app/cmd/common/config.go +++ b/keadm/app/cmd/common/config.go @@ -22,8 +22,9 @@ import ( "strings" "time" - "github.com/kubeedge/kubeedge/common/constants" "gopkg.in/yaml.v2" + + "github.com/kubeedge/kubeedge/common/constants" ) //Write2File writes data into a file in path diff --git a/keadm/app/keadm.go b/keadm/app/keadm.go index 0ef399fa3..04d789f42 100644 --- a/keadm/app/keadm.go +++ b/keadm/app/keadm.go @@ -28,7 +28,6 @@ import ( //Run executes the keadm command func Run() error { pflag.CommandLine.AddGoFlagSet(flag.CommandLine) - pflag.Set("logtostderr", "true") cmd := cmd.NewKubeedgeCommand(os.Stdin, os.Stdout, os.Stderr) diff --git a/mappers/bluetooth_mapper/configuration/config.go b/mappers/bluetooth_mapper/configuration/config.go index eb216ccae..0a8e0f258 100644 --- a/mappers/bluetooth_mapper/configuration/config.go +++ b/mappers/bluetooth_mapper/configuration/config.go @@ -23,12 +23,12 @@ import ( "reflect" "strings" + "gopkg.in/yaml.v2" + "github.com/kubeedge/kubeedge/mappers/bluetooth_mapper/action_manager" "github.com/kubeedge/kubeedge/mappers/bluetooth_mapper/data_converter" "github.com/kubeedge/kubeedge/mappers/bluetooth_mapper/scheduler" "github.com/kubeedge/kubeedge/mappers/bluetooth_mapper/watcher" - - "gopkg.in/yaml.v2" ) //ConfigFilePath contains the location of the configuration file diff --git a/mappers/bluetooth_mapper/helper/helper.go b/mappers/bluetooth_mapper/helper/helper.go index 6dfc84399..cbcf494c6 100644 --- a/mappers/bluetooth_mapper/helper/helper.go +++ b/mappers/bluetooth_mapper/helper/helper.go @@ -22,9 +22,8 @@ import ( "sync" "time" - "k8s.io/klog" - MQTT "github.com/eclipse/paho.mqtt.golang" + "k8s.io/klog" ) var ( diff --git a/mappers/bluetooth_mapper/main.go b/mappers/bluetooth_mapper/main.go index faeacf746..2f7883119 100644 --- a/mappers/bluetooth_mapper/main.go +++ b/mappers/bluetooth_mapper/main.go @@ -27,24 +27,12 @@ import ( "github.com/kubeedge/kubeedge/mappers/bluetooth_mapper/controller" ) -//usage is responsible for setting up the default settings of all defined command-line flags for log. -func usage() { - flag.PrintDefaults() - os.Exit(2) -} - -//init for getting command line arguments for log -func init() { +// main function +func main() { klog.InitFlags(nil) - flag.Usage = usage - // NOTE: This next line is key you have to call flag.Parse() for the command line - // options or "flags" that are defined in the log module to be picked up. - flag.Parse() pflag.CommandLine.AddGoFlagSet(flag.CommandLine) -} + pflag.Parse() -// main function -func main() { BleConfig := configuration.BLEConfig{} // load config err := BleConfig.Load() diff --git a/tests/e2e/deployment/deployment_suite_test.go b/tests/e2e/deployment/deployment_suite_test.go index 2661a4e0d..051253fe3 100644 --- a/tests/e2e/deployment/deployment_suite_test.go +++ b/tests/e2e/deployment/deployment_suite_test.go @@ -36,10 +36,9 @@ var ( //Function to run the Ginkgo Test func TestEdgecoreAppDeployment(t *testing.T) { - RegisterFailHandler(Fail) var _ = BeforeSuite(func() { - utils.InfoV6("Before Suite Execution") + utils.Infof("Before Suite Execution") //cfg = utils.LoadConfig() ctx = utils.NewTestContext(utils.LoadConfig()) nodeName = "integration-node-" + utils.GetRandomString(10) @@ -58,7 +57,7 @@ func TestEdgecoreAppDeployment(t *testing.T) { //Check node successfully registered or not Eventually(func() string { status := utils.CheckNodeReadyStatus(ctx.Cfg.K8SMasterForKubeEdge+constants.NodeHandler, nodeName) - utils.Info("Node Name: %v, Node Status: %v", nodeName, status) + utils.Infof("Node Name: %v, Node Status: %v", nodeName, status) return status }, "60s", "4s").Should(Equal("Running"), "Node register to the k8s master is unsuccessfull !!") @@ -69,14 +68,14 @@ func TestEdgecoreAppDeployment(t *testing.T) { Expect(utils.DeRegisterNodeFromMaster(ctx.Cfg.K8SMasterForKubeEdge+constants.NodeHandler, nodeName)).Should(BeNil()) Eventually(func() int { statuscode := utils.CheckNodeDeleteStatus(ctx.Cfg.K8SMasterForKubeEdge+constants.NodeHandler, nodeName) - utils.Info("Node Name: %v, Node Statuscode: %v", nodeName, statuscode) + utils.Infof("Node Name: %v, Node Statuscode: %v", nodeName, statuscode) return statuscode }, "60s", "4s").Should(Equal(http.StatusNotFound), "Node register to the k8s master is unsuccessfull !!") //Run the Cleanup steps to kill edgecore and cloudcore binaries Expect(utils.CleanUp("deployment")).Should(BeNil()) //time.Sleep(2 * time.Second) - utils.Info("Cleanup is Successfull !!") + utils.Infof("Cleanup is Successfull !!") }) RunSpecs(t, "kubeedge App Deploymet Suite") diff --git a/tests/e2e/device_crd/device_crd_suit_test.go b/tests/e2e/device_crd/device_crd_suit_test.go index 360a237c3..507a77ff5 100644 --- a/tests/e2e/device_crd/device_crd_suit_test.go +++ b/tests/e2e/device_crd/device_crd_suit_test.go @@ -18,8 +18,6 @@ package device_crd import ( "bytes" - "github.com/kubeedge/kubeedge/tests/e2e/constants" - "github.com/kubeedge/kubeedge/tests/e2e/utils" "io/ioutil" "net/http" "path" @@ -29,6 +27,9 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + + "github.com/kubeedge/kubeedge/tests/e2e/constants" + "github.com/kubeedge/kubeedge/tests/e2e/utils" ) //context to load config and access across the package @@ -47,10 +48,11 @@ var ( //Function to run the Ginkgo Test func TestEdgecoreAppDeployment(t *testing.T) { + RegisterFailHandler(Fail) var _ = BeforeSuite(func() { client := &http.Client{} - utils.InfoV6("Before Suite Execution") + utils.Infof("Before Suite Execution") ctx = utils.NewTestContext(utils.LoadConfig()) NodeName = "integration-node-" + utils.GetRandomString(10) nodeSelector = "node-" + utils.GetRandomString(3) @@ -68,7 +70,7 @@ func TestEdgecoreAppDeployment(t *testing.T) { //Check node successfully registered or not Eventually(func() string { status := utils.CheckNodeReadyStatus(ctx.Cfg.K8SMasterForKubeEdge+constants.NodeHandler, NodeName) - utils.Info("Node Name: %v, Node Status: %v", NodeName, status) + utils.Infof("Node Name: %v, Node Status: %v", NodeName, status) return status }, "60s", "4s").Should(Equal("Running"), "Node register to the k8s master is unsuccessfull !!") //Apply the CRDs @@ -101,7 +103,7 @@ func TestEdgecoreAppDeployment(t *testing.T) { Expect(utils.DeRegisterNodeFromMaster(ctx.Cfg.K8SMasterForKubeEdge+constants.NodeHandler, NodeName)).Should(BeNil()) Eventually(func() int { statuscode := utils.CheckNodeDeleteStatus(ctx.Cfg.K8SMasterForKubeEdge+constants.NodeHandler, NodeName) - utils.Info("Node Name: %v, Node Statuscode: %v", NodeName, statuscode) + utils.Infof("Node Name: %v, Node Statuscode: %v", NodeName, statuscode) return statuscode }, "60s", "4s").Should(Equal(http.StatusNotFound), "Node register to the k8s master is unsuccessfull !!") client := &http.Client{} @@ -120,7 +122,7 @@ func TestEdgecoreAppDeployment(t *testing.T) { //Run the Cleanup steps to kill edgecore and cloudcore binaries Expect(utils.CleanUp("device_crd")).Should(BeNil()) - utils.Info("Cleanup is Successfull !!") + utils.Infof("Cleanup is Successfull !!") }) RunSpecs(t, "kubeedge Device Managemnet Suite") } diff --git a/tests/e2e/device_crd/device_crd_test.go b/tests/e2e/device_crd/device_crd_test.go index e8c2aefda..fe45b9640 100644 --- a/tests/e2e/device_crd/device_crd_test.go +++ b/tests/e2e/device_crd/device_crd_test.go @@ -18,12 +18,12 @@ package device_crd import ( "encoding/json" - v1 "k8s.io/api/core/v1" "net/http" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + v1 "k8s.io/api/core/v1" "github.com/kubeedge/kubeedge/cloud/pkg/apis/devices/v1alpha1" "github.com/kubeedge/kubeedge/tests/e2e/utils" diff --git a/tests/e2e/edgesite/edgesite_suite_test.go b/tests/e2e/edgesite/edgesite_suite_test.go index bfd0e81b9..8834b8433 100644 --- a/tests/e2e/edgesite/edgesite_suite_test.go +++ b/tests/e2e/edgesite/edgesite_suite_test.go @@ -36,10 +36,9 @@ var ( //Function to run the Ginkgo Test func TestEdgecoreAppDeployment(t *testing.T) { - RegisterFailHandler(Fail) var _ = BeforeSuite(func() { - utils.InfoV6("Before Suite Execution") + utils.Infof("Before Suite Execution") //cfg = utils.LoadConfig() ctx = utils.NewTestContext(utils.LoadConfig()) //Expect(utils.CleanUp("edgesite")).Should(BeNil()) @@ -53,7 +52,7 @@ func TestEdgecoreAppDeployment(t *testing.T) { //Check node successfully registered or not Eventually(func() string { status := utils.CheckNodeReadyStatus(ctx.Cfg.K8SMasterForKubeEdge+constants.NodeHandler, nodeName) - utils.Info("Node Name: %v, Node Status: %v", nodeName, status) + utils.Infof("Node Name: %v, Node Status: %v", nodeName, status) return status }, "60s", "4s").Should(Equal("Running"), "Node register to the k8s master is unsuccessfull !!") @@ -66,14 +65,14 @@ func TestEdgecoreAppDeployment(t *testing.T) { Eventually(func() int { statuscode := utils.CheckNodeDeleteStatus(ctx.Cfg.K8SMasterForKubeEdge+constants.NodeHandler, nodeName) - utils.Info("Node Name: %v, Node Statuscode: %v", nodeName, statuscode) + utils.Infof("Node Name: %v, Node Statuscode: %v", nodeName, statuscode) return statuscode }, "60s", "4s").Should(Equal(http.StatusNotFound), "Node register to the k8s master is unsuccessfull !!") //Run the Cleanup steps to kill edgecore and cloudcore binaries Expect(utils.CleanUp("edgesite")).Should(BeNil()) //time.Sleep(2 * time.Second) - utils.Info("Cleanup is Successfull !!") + utils.Infof("Cleanup is Successfull !!") }) RunSpecs(t, "kubeedge App Deploymet Suite with EdgeSite") diff --git a/tests/e2e/mapper/bluetooth/bluetooth_suite_test.go b/tests/e2e/mapper/bluetooth/bluetooth_suite_test.go index 291fbaeae..79ce69d7a 100644 --- a/tests/e2e/mapper/bluetooth/bluetooth_suite_test.go +++ b/tests/e2e/mapper/bluetooth/bluetooth_suite_test.go @@ -74,7 +74,7 @@ type Token interface { func TestMapperCharacteristics(t *testing.T) { RegisterFailHandler(Fail) var _ = BeforeSuite(func() { - utils.InfoV6("Before Suite Execution") + utils.Infof("Before Suite Execution") cfg = utils.LoadConfig() ctx = utils.NewTestContext(cfg) t := time.Now() @@ -98,7 +98,7 @@ func TestMapperCharacteristics(t *testing.T) { req.Header.Set("Content-Type", "application/yaml") resp, err := client.Do(req) Expect(err).To(BeNil()) - utils.InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + utils.Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) Expect(resp.StatusCode).Should(Equal(http.StatusCreated)) //Apply CRD for deviceinstance @@ -113,7 +113,7 @@ func TestMapperCharacteristics(t *testing.T) { req.Header.Set("Content-Type", "application/yaml") resp, err = client.Do(req) Expect(err).To(BeNil()) - utils.InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + utils.Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) Expect(resp.StatusCode).Should(Equal(http.StatusCreated)) //Run ./edgecontroller binary @@ -129,7 +129,7 @@ func TestMapperCharacteristics(t *testing.T) { //Check node successfully registered or not Eventually(func() string { status := utils.CheckNodeReadyStatus(ctx.Cfg.K8SMasterForKubeEdge+nodeHandler, nodeName) - utils.Info("Node Name: %v, Node Status: %v", nodeName, status) + utils.Infof("Node Name: %v, Node Status: %v", nodeName, status) return status }, "60s", "4s").Should(Equal("Running"), "Node register to the k8s master is unsuccessfull !!") @@ -182,7 +182,7 @@ func TestMapperCharacteristics(t *testing.T) { resp, err = client.Do(req) Expect(err).To(BeNil()) Expect(resp.StatusCode).Should(Equal(http.StatusCreated)) - utils.InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + utils.Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) //apply CRD for mock deviceinstance curPath = getpwd() @@ -197,7 +197,7 @@ func TestMapperCharacteristics(t *testing.T) { resp, err = client.Do(req) Expect(err).To(BeNil()) Expect(resp.StatusCode).Should(Equal(http.StatusCreated)) - utils.InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + utils.Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) //updating deployment file with edgenode name and dockerhubusername curPath = getpwd() @@ -267,14 +267,14 @@ func TestMapperCharacteristics(t *testing.T) { Expect(err).Should(BeNil()) Eventually(func() int { statuscode := utils.CheckNodeDeleteStatus(ctx.Cfg.K8SMasterForKubeEdge+nodeHandler, nodeName) - utils.Info("Node Name: %v, Node Statuscode: %v", nodeName, statuscode) + utils.Infof("Node Name: %v, Node Statuscode: %v", nodeName, statuscode) return statuscode }, "60s", "4s").Should(Equal(http.StatusNotFound), "Node register to the k8s master is unsuccessfull !!") Expect(utils.CleanUp("deployment")).Should(BeNil()) time.Sleep(2 * time.Second) - utils.Info("Cleanup is Successfull !!") + utils.Infof("Cleanup is Successfull !!") }) RunSpecs(t, "Kubeedge Mapper Test Suite") } diff --git a/tests/e2e/mapper/bluetooth/bluetooth_test.go b/tests/e2e/mapper/bluetooth/bluetooth_test.go index 9b5cea350..3e0b390d8 100644 --- a/tests/e2e/mapper/bluetooth/bluetooth_test.go +++ b/tests/e2e/mapper/bluetooth/bluetooth_test.go @@ -62,7 +62,7 @@ func DataConversion(client MQTT.Client, message MQTT.Message) { devicePayload := message.Payload() err := json.Unmarshal(devicePayload, &scheduleResult) if err != nil { - common.Failf("Unmarshall failed %s", err) + utils.Fatalf("Unmarshall failed %s", err) } else { if reflect.DeepEqual(scheduleResult.EventResult, expectedTemp) { dataConverted = true @@ -80,7 +80,7 @@ func WriteDataReceived(client MQTT.Client, message MQTT.Message) { err := json.Unmarshal(devicePayload, &scheduleResult) data := []byte{1} if err != nil { - common.Failf("Unmarshall failed %s", err) + utils.Fatalf("Unmarshall failed %s", err) } else { if reflect.DeepEqual(string(data), scheduleResult.EventResult) { readWrittenData = true @@ -97,7 +97,7 @@ func ScheduleExecute(client MQTT.Client, message MQTT.Message) { devicePayload := message.Payload() err := json.Unmarshal(devicePayload, &scheduleResult) if err != nil { - common.Failf("Unmarshall failed %s", err) + utils.Fatalf("Unmarshall failed %s", err) } else { if reflect.DeepEqual(scheduleResult.EventResult, expectedTemp) { timesExecuted++ @@ -114,15 +114,15 @@ var _ = Describe("Application deployment test in E2E scenario", func() { ClientOpts = helpers.HubClientInit(ctx.Cfg.MqttEndpoint, "bluetoothmapper", "", "") Client = MQTT.NewClient(ClientOpts) if TokenClient = Client.Connect(); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Connect() Error is %s", TokenClient.Error()) + utils.Fatalf("client.Connect() Error is %s", TokenClient.Error()) } else { - common.Info("Connection successful") + utils.Infof("Connection successful") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) scheduletopic := "$ke/device/bluetooth-mapper/mock-temp-sensor-instance/scheduler/result" Token := Client.Subscribe(scheduletopic, 0, WriteDataReceived) if Token.Wait() && TokenClient.Error() != nil { - common.Failf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), scheduletopic) + utils.Fatalf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), scheduletopic) } Expect(TokenClient.Error()).NotTo(HaveOccurred()) }) @@ -159,15 +159,15 @@ var _ = Describe("Application deployment test in E2E scenario", func() { ClientOpts = helpers.HubClientInit(ctx.Cfg.MqttEndpoint, "bluetoothmapper", "", "") Client = MQTT.NewClient(ClientOpts) if TokenClient = Client.Connect(); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Connect() Error is %s", TokenClient.Error()) + utils.Fatalf("client.Connect() Error is %s", TokenClient.Error()) } else { - common.Info("Subscribe Connection Successful") + utils.Infof("Subscribe Connection Successful") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) scheduletopic := "$ke/device/bluetooth-mapper/mock-temp-sensor-instance/scheduler/result" Token := Client.Subscribe(scheduletopic, 0, DataConversion) if Token.Wait() && TokenClient.Error() != nil { - common.Failf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), scheduletopic) + utils.Fatalf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), scheduletopic) } Expect(TokenClient.Error()).NotTo(HaveOccurred()) var expectedSchedule []scheduler.Schedule @@ -177,11 +177,11 @@ var _ = Describe("Application deployment test in E2E scenario", func() { scheduleCreateTopic := "$ke/device/bluetooth-mapper/mock-temp-sensor-instance/scheduler/create" scheduleCreate, err := json.Marshal(expectedSchedule) if err != nil { - common.Failf("Error in marshalling: %s", err) + utils.Fatalf("Error in marshalling: %s", err) } TokenClient = Client.Publish(scheduleCreateTopic, 0, false, scheduleCreate) if TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("Publish to Topic Failed %s, %s", TokenClient.Error(), scheduleCreateTopic) + utils.Fatalf("Publish to Topic Failed %s, %s", TokenClient.Error(), scheduleCreateTopic) } Expect(TokenClient.Error()).NotTo(HaveOccurred()) }) @@ -203,15 +203,15 @@ var _ = Describe("Application deployment test in E2E scenario", func() { ClientOpts = helpers.HubClientInit(ctx.Cfg.MqttEndpoint, "bluetoothmapper", "", "") Client = MQTT.NewClient(ClientOpts) if TokenClient = Client.Connect(); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Connect() Error is %s", TokenClient.Error()) + utils.Fatalf("client.Connect() Error is %s", TokenClient.Error()) } else { - common.Info("Subscribe Connection successful") + utils.Infof("Subscribe Connection successful") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) scheduletopic := "$ke/device/bluetooth-mapper/mock-temp-sensor-instance/scheduler/result" Token := Client.Subscribe(scheduletopic, 0, ScheduleExecute) if Token.Wait() && TokenClient.Error() != nil { - common.Failf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), scheduletopic) + utils.Fatalf("Subscribe to Topic Failed %s, %s", TokenClient.Error(), scheduletopic) } Expect(TokenClient.Error()).NotTo(HaveOccurred()) var expectedSchedule []scheduler.Schedule @@ -221,11 +221,11 @@ var _ = Describe("Application deployment test in E2E scenario", func() { scheduleCreateTopic := "$ke/device/bluetooth-mapper/mock-temp-sensor-instance/scheduler/create" scheduleCreate, err := json.Marshal(expectedSchedule) if err != nil { - common.Failf("Error in marshalling: %s", err) + utils.Fatalf("Error in marshalling: %s", err) } TokenClient = Client.Publish(scheduleCreateTopic, 0, false, scheduleCreate) if TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("Publish to Topic Failed %s, %s", TokenClient.Error(), scheduleCreateTopic) + utils.Fatalf("Publish to Topic Failed %s, %s", TokenClient.Error(), scheduleCreateTopic) } Expect(TokenClient.Error()).NotTo(HaveOccurred()) }) @@ -252,19 +252,19 @@ var _ = Describe("Application deployment test in E2E scenario", func() { ClientOpts = helpers.HubClientInit(ctx.Cfg.MqttEndpoint, "bluetoothmapper", "", "") Client = MQTT.NewClient(ClientOpts) if TokenClient = Client.Connect(); TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("client.Connect() Error is %s", TokenClient.Error()) + utils.Fatalf("client.Connect() Error is %s", TokenClient.Error()) } else { - common.Info("Publish Connection successful") + utils.Infof("Publish Connection successful") } Expect(TokenClient.Error()).NotTo(HaveOccurred()) watcherCreateTopic := "$ke/device/bluetooth-mapper/mock-temp-sensor-instance/watcher/create" scheduleCreate, err := json.Marshal(expectedWatchAttribute) if err != nil { - common.Failf("Error in marshalling: %s", err) + utils.Fatalf("Error in marshalling: %s", err) } TokenClient = Client.Publish(watcherCreateTopic, 0, false, scheduleCreate) if TokenClient.Wait() && TokenClient.Error() != nil { - common.Failf("Publish to Topic Failed %s, %s", TokenClient.Error(), watcherCreateTopic) + utils.Fatalf("Publish to Topic Failed %s, %s", TokenClient.Error(), watcherCreateTopic) } Expect(TokenClient.Error()).NotTo(HaveOccurred()) }) diff --git a/tests/e2e/scripts/cleanup.sh b/tests/e2e/scripts/cleanup.sh index afe33b5d6..4a5ba59e3 100755 --- a/tests/e2e/scripts/cleanup.sh +++ b/tests/e2e/scripts/cleanup.sh @@ -30,7 +30,7 @@ kill_edgecore() { } kill_cloudcore() { - sudo pkill edge + sudo pkill cloudcore #kill the cloudcore process if it exists. sleep 5s if pgrep cloudcore >/dev/null diff --git a/tests/e2e/scripts/fast_test.sh b/tests/e2e/scripts/fast_test.sh index 9971b25a7..391699e2e 100755 --- a/tests/e2e/scripts/fast_test.sh +++ b/tests/e2e/scripts/fast_test.sh @@ -18,8 +18,6 @@ cd `dirname $0` workdir=`pwd` cd $workdir -debugflag="-v 6 -alsologtostderr" - compilemodule=$1 runtest=$2 @@ -41,13 +39,13 @@ END if [ $# -eq 0 ] then #run testcase - ./deployment/deployment.test $debugflag 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log - ./edgesite/edgesite.test $debugflag 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log + ./deployment/deployment.test 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log + ./edgesite/edgesite.test 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log else if compilemodule=="bluetooth" then - ./mapper/bluetooth/bluetooth.test $debugflag $runtest 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log + ./mapper/bluetooth/bluetooth.test $runtest 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log else - ./$compilemodule/$compilemodule.test $debugflag $runtest 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log + ./$compilemodule/$compilemodule.test $runtest 2>&1 | tee /tmp/fast_test.log && cat /tmp/fast_test.log >> /tmp/testcase.log && :> /tmp/fast_test.log fi fi diff --git a/tests/e2e/testsuite/testsuite.go b/tests/e2e/testsuite/testsuite.go index b976097c2..9c0b7c233 100644 --- a/tests/e2e/testsuite/testsuite.go +++ b/tests/e2e/testsuite/testsuite.go @@ -20,12 +20,12 @@ import ( "net/http" "time" - "github.com/kubeedge/kubeedge/tests/e2e/constants" - "github.com/kubeedge/kubeedge/tests/e2e/utils" - . "github.com/onsi/gomega" v1 "k8s.io/api/apps/v1" metav1 "k8s.io/api/core/v1" + + "github.com/kubeedge/kubeedge/tests/e2e/constants" + "github.com/kubeedge/kubeedge/tests/e2e/utils" ) func CreateDeploymentTest(replica int, deplName, nodeName, nodeSelector string, ctx *utils.TestContext) metav1.PodList { diff --git a/tests/e2e/utils/common.go b/tests/e2e/utils/common.go index 577e34b54..65f4db291 100644 --- a/tests/e2e/utils/common.go +++ b/tests/e2e/utils/common.go @@ -28,9 +28,6 @@ import ( "strings" "time" - "github.com/kubeedge/kubeedge/cloud/pkg/apis/devices/v1alpha1" - "github.com/kubeedge/viaduct/pkg/api" - MQTT "github.com/eclipse/paho.mqtt.golang" "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -40,6 +37,9 @@ import ( "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" + + "github.com/kubeedge/kubeedge/cloud/pkg/apis/devices/v1alpha1" + "github.com/kubeedge/viaduct/pkg/api" ) const ( @@ -296,12 +296,12 @@ func GetDeployments(list *apps.DeploymentList, getDeploymentApi string) error { defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) return err } err = json.Unmarshal(contents, &list) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) return err } return nil @@ -310,7 +310,7 @@ func GetDeployments(list *apps.DeploymentList, getDeploymentApi string) error { func VerifyDeleteDeployment(getDeploymentApi string) int { err, resp := SendHttpRequest(http.MethodGet, getDeploymentApi) if err != nil { - Failf("SendHttpRequest is failed: %v", err) + Fatalf("SendHttpRequest is failed: %v", err) } defer resp.Body.Close() return resp.StatusCode @@ -328,7 +328,7 @@ func HandlePod(operation string, apiserver string, UID string, ImageUrl, nodesel body := newPodObj(UID, ImageUrl, nodeselector) respBytes, err := json.Marshal(body) if err != nil { - Failf("Marshalling body failed: %v", err) + Fatalf("Marshalling body failed: %v", err) } req, err = http.NewRequest(http.MethodPost, apiserver, bytes.NewBuffer(respBytes)) case "DELETE": @@ -336,7 +336,7 @@ func HandlePod(operation string, apiserver string, UID string, ImageUrl, nodesel } if err != nil { // handle error - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) return false } req.Header.Set("Content-Type", "application/json") @@ -344,10 +344,10 @@ func HandlePod(operation string, apiserver string, UID string, ImageUrl, nodesel resp, err := client.Do(req) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return false } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) return true } @@ -363,11 +363,11 @@ func HandleDeployment(IsCloudCore, IsEdgeCore bool, operation, apiserver, UID, I case "POST": depObj := newDeployment(IsCloudCore, IsEdgeCore, UID, ImageUrl, nodeselector, configmapname, replica) if err != nil { - Failf("GenerateDeploymentBody marshalling failed: %v", err) + Fatalf("GenerateDeploymentBody marshalling failed: %v", err) } respBytes, err := json.Marshal(depObj) if err != nil { - Failf("Marshalling body failed: %v", err) + Fatalf("Marshalling body failed: %v", err) } req, err = http.NewRequest(http.MethodPost, apiserver, bytes.NewBuffer(respBytes)) case "DELETE": @@ -375,7 +375,7 @@ func HandleDeployment(IsCloudCore, IsEdgeCore bool, operation, apiserver, UID, I } if err != nil { // handle error - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) return false } req.Header.Set("Content-Type", "application/json") @@ -383,10 +383,10 @@ func HandleDeployment(IsCloudCore, IsEdgeCore bool, operation, apiserver, UID, I resp, err := client.Do(req) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return false } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) return true } @@ -395,7 +395,7 @@ func DeleteDeployment(DeploymentApi, deploymentname string) int { err, resp := SendHttpRequest(http.MethodDelete, DeploymentApi+"/"+deploymentname) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return -1 } @@ -406,14 +406,14 @@ func DeleteDeployment(DeploymentApi, deploymentname string) int { // PrintCombinedOutput to show the os command injuction in combined format func PrintCombinedOutput(cmd *exec.Cmd) error { - Info("===========> Executing: %s\n", strings.Join(cmd.Args, " ")) + Infof("===========> Executing: %s\n", strings.Join(cmd.Args, " ")) output, err := cmd.CombinedOutput() if err != nil { - Failf("CombinedOutput failed", err) + Fatalf("CombinedOutput failed %v", err) return err } if len(output) > 0 { - Info("=====> Output: %s\n", string(output)) + Infof("=====> Output: %s\n", string(output)) } return nil } @@ -423,12 +423,12 @@ func ExposeCloudService(name, serviceHandler string) error { ServiceObj := CreateServiceObject(name) respBytes, err := json.Marshal(ServiceObj) if err != nil { - Failf("Marshalling body failed: %v", err) + Fatalf("Marshalling body failed: %v", err) } req, err := http.NewRequest(http.MethodPost, serviceHandler, bytes.NewBuffer(respBytes)) if err != nil { // handle error - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) return err } client := &http.Client{} @@ -437,10 +437,10 @@ func ExposeCloudService(name, serviceHandler string) error { resp, err := client.Do(req) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return err } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) Expect(resp.StatusCode).Should(Equal(http.StatusCreated)) return nil } @@ -477,19 +477,19 @@ func GetServicePort(cloudName, serviceHandler string) (int32, int32) { err, resp := SendHttpRequest(http.MethodGet, serviceHandler) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return -1, -1 } contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) return -1, -1 } err = json.Unmarshal(contents, &svc) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) return -1, -1 } defer resp.Body.Close() @@ -515,7 +515,7 @@ func DeleteSvc(svcname string) int { err, resp := SendHttpRequest(http.MethodDelete, svcname) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return -1 } @@ -536,7 +536,7 @@ func HandleDeviceModel(operation string, apiserver string, UID string, protocolT body := newDeviceModelObject(protocolType, false) respBytes, err := json.Marshal(body) if err != nil { - Failf("Marshalling body failed: %v", err) + Fatalf("Marshalling body failed: %v", err) } req, err = http.NewRequest(http.MethodPost, apiserver, bytes.NewBuffer(respBytes)) req.Header.Set("Content-Type", "application/json") @@ -544,7 +544,7 @@ func HandleDeviceModel(operation string, apiserver string, UID string, protocolT body := newDeviceModelObject(protocolType, true) respBytes, err := json.Marshal(body) if err != nil { - Failf("Marshalling body failed: %v", err) + Fatalf("Marshalling body failed: %v", err) } req, err = http.NewRequest(http.MethodPatch, apiserver+UID, bytes.NewBuffer(respBytes)) req.Header.Set("Content-Type", "application/merge-patch+json") @@ -554,17 +554,17 @@ func HandleDeviceModel(operation string, apiserver string, UID string, protocolT } if err != nil { // handle error - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) return false, 0 } t := time.Now() resp, err := client.Do(req) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return false, 0 } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) return true, resp.StatusCode } @@ -580,7 +580,7 @@ func HandleDeviceInstance(operation string, apiserver string, nodeSelector strin body := newDeviceInstanceObject(nodeSelector, protocolType, false) respBytes, err := json.Marshal(body) if err != nil { - Failf("Marshalling body failed: %v", err) + Fatalf("Marshalling body failed: %v", err) } req, err = http.NewRequest(http.MethodPost, apiserver, bytes.NewBuffer(respBytes)) req.Header.Set("Content-Type", "application/json") @@ -588,7 +588,7 @@ func HandleDeviceInstance(operation string, apiserver string, nodeSelector strin body := newDeviceInstanceObject(nodeSelector, protocolType, true) respBytes, err := json.Marshal(body) if err != nil { - Failf("Marshalling body failed: %v", err) + Fatalf("Marshalling body failed: %v", err) } req, err = http.NewRequest(http.MethodPatch, apiserver+UID, bytes.NewBuffer(respBytes)) req.Header.Set("Content-Type", "application/merge-patch+json") @@ -598,17 +598,17 @@ func HandleDeviceInstance(operation string, apiserver string, nodeSelector strin } if err != nil { // handle error - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) return false, 0 } t := time.Now() resp, err := client.Do(req) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return false, 0 } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) return true, resp.StatusCode } @@ -676,12 +676,12 @@ func GetDeviceModel(list *v1alpha1.DeviceModelList, getDeviceModelApi string, ex defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) return nil, err } err = json.Unmarshal(contents, &list) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) return nil, err } if expectedDeviceModel != nil { @@ -707,12 +707,12 @@ func GetDevice(list *v1alpha1.DeviceList, getDeviceApi string, expectedDevice *v defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) return nil, err } err = json.Unmarshal(contents, &list) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) return nil, err } if expectedDevice != nil { @@ -804,13 +804,13 @@ func TwinSubscribe(deviceID string) { getTwinResult := DeviceETPrefix + deviceID + TwinETGetResultSuffix TokenClient = Client.Subscribe(getTwinResult, 0, OnTwinMessageReceived) if TokenClient.Wait() && TokenClient.Error() != nil { - Err("subscribe() Error in device twin result get is " + TokenClient.Error().Error()) + Errorf("subscribe() Error in device twin result get is %v", TokenClient.Error().Error()) } for { twin := DeviceTwinUpdate{} err := GetTwin(twin, deviceID) if err != nil { - Err("Error in getting device twin: " + err.Error()) + Errorf("Error in getting device twin: %v", err.Error()) } time.Sleep(1 * time.Second) if TwinResult.Twin != nil { @@ -823,7 +823,7 @@ func TwinSubscribe(deviceID string) { func OnTwinMessageReceived(client MQTT.Client, message MQTT.Message) { err := json.Unmarshal(message.Payload(), &TwinResult) if err != nil { - Err("Error in unmarshalling: " + err.Error()) + Errorf("Error in unmarshalling: %v", err.Error()) } } diff --git a/tests/e2e/utils/config.go b/tests/e2e/utils/config.go index b18ff9f7e..1765669f5 100644 --- a/tests/e2e/utils/config.go +++ b/tests/e2e/utils/config.go @@ -65,7 +65,7 @@ func loadConfigJsonFromPath() *Config { path := getConfigPath() _, err := filepath.Abs(filepath.Dir(path)) if err != nil { - InfoV6("Failed to get Abs path: %v", err) + Infof("Failed to get Abs path: %v", err) panic(err) } var config *Config = &Config{} diff --git a/tests/e2e/utils/context.go b/tests/e2e/utils/context.go index 5ba1c6028..44b45788f 100644 --- a/tests/e2e/utils/context.go +++ b/tests/e2e/utils/context.go @@ -45,7 +45,7 @@ func SendHttpRequest(method, reqApi string) (error, *http.Response) { req, err := http.NewRequest(method, reqApi, body) if err != nil { // handle error - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) return err, resp } req.Header.Set("Content-Type", "application/json") @@ -53,10 +53,10 @@ func SendHttpRequest(method, reqApi string) (error, *http.Response) { resp, err = client.Do(req) if err != nil { // handle error - Failf("HTTP request is failed :%v", err) + Fatalf("HTTP request is failed :%v", err) return err, resp } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) return nil, resp } diff --git a/tests/e2e/utils/device.go b/tests/e2e/utils/device.go index 57f5b22ae..84aa5645d 100644 --- a/tests/e2e/utils/device.go +++ b/tests/e2e/utils/device.go @@ -2,6 +2,7 @@ package utils import ( "encoding/json" + v12 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -988,7 +989,7 @@ func NewConfigMapLED(nodeSelector string) v12.ConfigMap { bytes, err := json.Marshal(deviceProfile) if err != nil { - Err("Failed to marshal deviceprofile: %v", deviceProfile) + Errorf("Failed to marshal deviceprofile: %v", deviceProfile) } configMap.Data["deviceProfile.json"] = string(bytes) @@ -1180,7 +1181,7 @@ func NewConfigMapBluetooth(nodeSelector string) v12.ConfigMap { bytes, err := json.Marshal(deviceProfile) if err != nil { - Err("Failed to marshal deviceprofile: %v", deviceProfile) + Errorf("Failed to marshal deviceprofile: %v", deviceProfile) } configMap.Data["deviceProfile.json"] = string(bytes) @@ -1270,7 +1271,7 @@ func NewConfigMapModbus(nodeSelector string) v12.ConfigMap { bytes, err := json.Marshal(deviceProfile) if err != nil { - Err("Failed to marshal deviceprofile: %v", deviceProfile) + Errorf("Failed to marshal deviceprofile: %v", deviceProfile) } configMap.Data["deviceProfile.json"] = string(bytes) diff --git a/tests/e2e/utils/log.go b/tests/e2e/utils/log.go index 480ab2147..92ed9b888 100644 --- a/tests/e2e/utils/log.go +++ b/tests/e2e/utils/log.go @@ -19,9 +19,7 @@ import ( "fmt" "time" - "k8s.io/klog" - - . "github.com/onsi/ginkgo" + "github.com/onsi/ginkgo" ) //Function to get time in millisec @@ -31,45 +29,37 @@ func nowStamp() string { //functiont to log the Ginkgo framework logs func logf(level string, format string, args ...interface{}) { - fmt.Fprintf(GinkgoWriter, nowStamp()+": "+level+": "+format+"\n", args...) + fmt.Fprintf(ginkgo.GinkgoWriter, nowStamp()+": "+level+": "+format+"\n", args...) } //Funciton to log Filure logs -func Failf(format string, args ...interface{}) { +func Fatalf(format string, args ...interface{}) { msg := fmt.Sprintf(format, args...) - logf("FAIL", msg) - Fail(nowStamp()+": "+msg, 1) + logf("Fatal", msg) + ginkgo.Fail(nowStamp()+": "+msg, 1) } //function for Error log -func Err(format string, args ...interface{}) { - klog.Errorf(format, args...) -} - -//function for log level -func Info(format string, args ...interface{}) { - klog.V(4).Infof(format, args...) -} - -//function for log level -func InfoV2(format string, args ...interface{}) { - klog.V(2).Infof(format, args...) +func Errorf(format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + logf("Error", msg) } //function for log level -func InfoV6(format string, args ...interface{}) { - klog.V(5).Infof(format, args...) +func Infof(format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + logf("Info", msg) } //Function to print the test case name and status of execution func PrintTestcaseNameandStatus() { - var testdesc GinkgoTestDescription + var testdesc ginkgo.GinkgoTestDescription var Status string - testdesc = CurrentGinkgoTestDescription() + testdesc = ginkgo.CurrentGinkgoTestDescription() if testdesc.Failed == true { Status = "FAILED" } else { Status = "PASSED" } - InfoV6("TestCase:%40s Status=%s", testdesc.TestText, Status) + Infof("TestCase:%40s Status=%s", testdesc.TestText, Status) } diff --git a/tests/e2e/utils/node.go b/tests/e2e/utils/node.go index 86bd013cc..242cc5176 100644 --- a/tests/e2e/utils/node.go +++ b/tests/e2e/utils/node.go @@ -30,14 +30,13 @@ import ( "github.com/ghodss/yaml" . "github.com/onsi/gomega" "k8s.io/api/core/v1" - "k8s.io/klog" ) func getpwd() string { _, file, _, _ := runtime.Caller(0) dir, err := filepath.Abs(filepath.Dir(file)) if err != nil { - klog.Errorf("get current dir fail %+v", err) + Errorf("get current dir fail %+v", err) return " " } return dir @@ -47,7 +46,7 @@ func getpwd() string { func DeRegisterNodeFromMaster(nodehandler, nodename string) error { err, resp := SendHttpRequest(http.MethodDelete, nodehandler+"/"+nodename) if err != nil { - Failf("Sending SenHttpRequest failed: %v", err) + Fatalf("Sending SenHttpRequest failed: %v", err) return err } defer resp.Body.Close() @@ -63,7 +62,7 @@ func GenerateNodeReqBody(nodeid, nodeselector string) (error, map[string]interfa body := fmt.Sprintf(`{"kind": "Node","apiVersion": "v1","metadata": {"name": "%s","labels": {"name": "edgenode", "disktype":"%s", "node-role.kubernetes.io/edge": ""}}}`, nodeid, nodeselector) err := json.Unmarshal([]byte(body), &temp) if err != nil { - Failf("Unmarshal body failed: %v", err) + Fatalf("Unmarshal body failed: %v", err) return err, temp } @@ -74,7 +73,7 @@ func GenerateNodeReqBody(nodeid, nodeselector string) (error, map[string]interfa func RegisterNodeToMaster(UID, nodehandler, nodeselector string) error { err, body := GenerateNodeReqBody(UID, nodeselector) if err != nil { - Failf("Unmarshal body failed: %v", err) + Fatalf("Unmarshal body failed: %v", err) return err } @@ -82,22 +81,22 @@ func RegisterNodeToMaster(UID, nodehandler, nodeselector string) error { t := time.Now() nodebody, err := json.Marshal(body) if err != nil { - Failf("Marshal body failed: %v", err) + Fatalf("Marshal body failed: %v", err) return err } BodyBuf := bytes.NewReader(nodebody) req, err := http.NewRequest(http.MethodPost, nodehandler, BodyBuf) req.Header.Set("Content-Type", "application/json") if err != nil { - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) return err } resp, err := client.Do(req) if err != nil { - Failf("Sending HTTP request failed: %v", err) + Fatalf("Sending HTTP request failed: %v", err) return err } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) defer resp.Body.Close() Expect(resp.StatusCode).Should(Equal(http.StatusCreated)) @@ -110,19 +109,19 @@ func CheckNodeReadyStatus(nodehandler, nodename string) string { var nodeStatus = "unknown" err, resp := SendHttpRequest(http.MethodGet, nodehandler+"/"+nodename) if err != nil { - Failf("Sending SenHttpRequest failed: %v", err) + Fatalf("Sending SenHttpRequest failed: %v", err) return nodeStatus } defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) return nodeStatus } err = json.Unmarshal(contents, &node) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) return nodeStatus } @@ -133,7 +132,7 @@ func CheckNodeReadyStatus(nodehandler, nodename string) string { func CheckNodeDeleteStatus(nodehandler, nodename string) int { err, resp := SendHttpRequest(http.MethodGet, nodehandler+"/"+nodename) if err != nil { - Failf("Sending SenHttpRequest failed: %v", err) + Fatalf("Sending SenHttpRequest failed: %v", err) return -1 } defer resp.Body.Close() @@ -176,13 +175,13 @@ func HandleConfigmap(configName chan error, operation, confighandler string, IsE } if err != nil { - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) } resp, err := client.Do(req) if err != nil { - Failf("Sending HTTP request failed: %v", err) + Fatalf("Sending HTTP request failed: %v", err) } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) defer resp.Body.Close() if operation == http.MethodPost { Expect(resp.StatusCode).Should(Equal(http.StatusCreated)) @@ -200,7 +199,7 @@ func HandleConfigmap(configName chan error, operation, confighandler string, IsE func GetConfigmap(apiConfigMap string) (int, []byte) { err, resp := SendHttpRequest(http.MethodGet, apiConfigMap) if err != nil { - Failf("Sending SenHttpRequest failed: %v", err) + Fatalf("Sending SenHttpRequest failed: %v", err) return -1, nil } body, _ := ioutil.ReadAll(resp.Body) @@ -213,7 +212,7 @@ func GetConfigmap(apiConfigMap string) (int, []byte) { func DeleteConfigmap(apiConfigMap string) int { err, resp := SendHttpRequest(http.MethodDelete, apiConfigMap) if err != nil { - Failf("Sending SenHttpRequest failed: %v", err) + Fatalf("Sending SenHttpRequest failed: %v", err) return -1 } defer resp.Body.Close() @@ -230,12 +229,12 @@ func TaintEdgeDeployedNode(toTaint bool, taintHandler string) error { } err := json.Unmarshal([]byte(body), &temp) if err != nil { - Failf("Unmarshal body failed: %v", err) + Fatalf("Unmarshal body failed: %v", err) return nil } nodebody, err := json.Marshal(temp) if err != nil { - Failf("Marshal body failed: %v", err) + Fatalf("Marshal body failed: %v", err) return err } BodyBuf := bytes.NewReader(nodebody) @@ -246,10 +245,10 @@ func TaintEdgeDeployedNode(toTaint bool, taintHandler string) error { req.Header.Set("Content-Type", "application/strategic-merge-patch+json") resp, err := client.Do(req) if err != nil { - Failf("Sending HTTP request failed: %v", err) + Fatalf("Sending HTTP request failed: %v", err) return err } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) defer resp.Body.Close() Expect(resp.StatusCode).Should(Equal(http.StatusOK)) return nil @@ -260,17 +259,17 @@ func GetNodes(api string) v1.NodeList { var nodes v1.NodeList err, resp := SendHttpRequest(http.MethodGet, api) if err != nil { - Failf("Sending SenHttpRequest failed: %v", err) + Fatalf("Sending SenHttpRequest failed: %v", err) } defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) } err = json.Unmarshal(contents, &nodes) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) } return nodes @@ -282,12 +281,12 @@ func ApplyLabelToNode(apiserver, key, val string) error { body = fmt.Sprintf(`{"metadata":{"labels":{"%s":"%s"}}}`, key, val) err := json.Unmarshal([]byte(body), &temp) if err != nil { - Failf("Unmarshal body failed: %v", err) + Fatalf("Unmarshal body failed: %v", err) return nil } nodebody, err := json.Marshal(temp) if err != nil { - Failf("Marshal body failed: %v", err) + Fatalf("Marshal body failed: %v", err) return err } BodyBuf := bytes.NewReader(nodebody) @@ -298,10 +297,10 @@ func ApplyLabelToNode(apiserver, key, val string) error { req.Header.Set("Content-Type", "application/strategic-merge-patch+json") resp, err := client.Do(req) if err != nil { - Failf("Sending HTTP request failed: %v", err) + Fatalf("Sending HTTP request failed: %v", err) return err } - InfoV6("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) defer resp.Body.Close() Expect(resp.StatusCode).Should(Equal(http.StatusOK)) return nil diff --git a/tests/e2e/utils/pod.go b/tests/e2e/utils/pod.go index 6e7981e0b..795f573cd 100644 --- a/tests/e2e/utils/pod.go +++ b/tests/e2e/utils/pod.go @@ -20,16 +20,15 @@ import ( "encoding/json" "io/ioutil" "net/http" + "strings" "time" + . "github.com/onsi/gomega" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" - - . "github.com/onsi/gomega" - "strings" ) const ( @@ -48,18 +47,18 @@ func GetPods(apiserver, label string) (v1.PodList, error) { err, resp = SendHttpRequest(http.MethodGet, apiserver) } if err != nil { - Failf("Frame HTTP request failed: %v", err) + Fatalf("Frame HTTP request failed: %v", err) return pods, nil } defer resp.Body.Close() contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) return pods, nil } err = json.Unmarshal(contents, &pods) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) return pods, nil } return pods, nil @@ -71,18 +70,18 @@ func GetPodState(apiserver string) (string, int) { err, resp := SendHttpRequest(http.MethodGet, apiserver) if err != nil { - Failf("GetPodState :SenHttpRequest failed: %v", err) + Fatalf("GetPodState :SenHttpRequest failed: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusNotFound { contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) } err = json.Unmarshal(contents, &pod) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) } return string(pod.Status.Phase), resp.StatusCode } @@ -95,18 +94,18 @@ func DeletePods(apiserver string) (string, int) { var pod v1.Pod err, resp := SendHttpRequest(http.MethodDelete, apiserver) if err != nil { - Failf("GetPodState :SenHttpRequest failed: %v", err) + Fatalf("GetPodState :SenHttpRequest failed: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusNotFound { contents, err := ioutil.ReadAll(resp.Body) if err != nil { - Failf("HTTP Response reading has failed: %v", err) + Fatalf("HTTP Response reading has failed: %v", err) } err = json.Unmarshal(contents, &pod) if err != nil { - Failf("Unmarshal HTTP Response has failed: %v", err) + Fatalf("Unmarshal HTTP Response has failed: %v", err) } return string(pod.Status.Phase), resp.StatusCode } @@ -120,7 +119,7 @@ func CheckPodRunningState(apiserver string, podlist v1.PodList) { var count int for _, pod := range podlist.Items { state, _ := GetPodState(apiserver + "/" + pod.Name) - InfoV2("PodName: %s PodStatus: %s", pod.Name, state) + Infof("PodName: %s PodStatus: %s", pod.Name, state) if state == "Running" { count++ } @@ -144,7 +143,7 @@ func CheckPodDeleteState(apiserver string, podlist v1.PodList) { var count int for _, pod := range podlist.Items { status, statusCode := GetPodState(apiserver + "/" + pod.Name) - InfoV2("PodName: %s status: %s StatusCode: %d", pod.Name, status, statusCode) + Infof("PodName: %s status: %s StatusCode: %d", pod.Name, status, statusCode) if statusCode == 404 { count++ } @@ -168,7 +167,7 @@ func CheckDeploymentPodDeleteState(apiserver string, podlist v1.PodList) { var count int for _, pod := range podlist.Items { status, statusCode := GetPodState(apiserver + "/" + pod.Name) - InfoV2("PodName: %s status: %s StatusCode: %d", pod.Name, status, statusCode) + Infof("PodName: %s status: %s StatusCode: %d", pod.Name, status, statusCode) if statusCode == 404 { count++ } @@ -182,7 +181,7 @@ func CheckDeploymentPodDeleteState(apiserver string, podlist v1.PodList) { func NewKubeClient(apiserver string) *kubernetes.Clientset { kubeConfig, err := clientcmd.BuildConfigFromFlags(apiserver, "") if err != nil { - Failf("Get kube config failed with error: %v", err) + Fatalf("Get kube config failed with error: %v", err) return nil } kubeConfig.QPS = 5 @@ -190,7 +189,7 @@ func NewKubeClient(apiserver string) *kubernetes.Clientset { kubeConfig.ContentType = "application/vnd.kubernetes.protobuf" kubeClient, err := kubernetes.NewForConfig(kubeConfig) if err != nil { - Failf("Get kube client failed with error: %v", err) + Fatalf("Get kube client failed with error: %v", err) return nil } return kubeClient @@ -219,14 +218,14 @@ func WaitforPodsRunning(apiserver string, podlist v1.PodList, timout time.Durati // check update obj p, ok := newObj.(*v1.Pod) if !ok { - Failf("Failed to cast observed object to pod") + Fatalf("Failed to cast observed object to pod") } // calculate the pods in running status count := 0 for i := range podlist.Items { // update pod status in podlist if podlist.Items[i].Name == p.Name { - InfoV2("PodName: %s PodStatus: %s", p.Name, p.Status.Phase) + Infof("PodName: %s PodStatus: %s", p.Name, p.Status.Phase) podlist.Items[i].Status = p.Status } // check if the pod is in running status @@ -250,8 +249,8 @@ func WaitforPodsRunning(apiserver string, podlist v1.PodList, timout time.Durati // wait for a signal or timeout select { case <-signal: - InfoV2("All pods come into running status") + Infof("All pods come into running status") case <-time.After(timout): - Failf("Wait for pods come into running status timeout: %v", timout) + Fatalf("Wait for pods come into running status timeout: %v", timout) } } diff --git a/tests/e2e/utils/timer.go b/tests/e2e/utils/timer.go index 2681cae7c..a10f4af90 100644 --- a/tests/e2e/utils/timer.go +++ b/tests/e2e/utils/timer.go @@ -52,10 +52,10 @@ func (testTimer *TestTimer) Duration() time.Duration { // PrintResult prints the result of the test timer func (testTimer *TestTimer) PrintResult() { if testTimer.IsEnded() { - Info("Test case name: %s start time: %v duration: %v\n", + Infof("Test case name: %s start time: %v duration: %v\n", testTimer.Name, testTimer.StartTime, testTimer.Duration()) } else { - Info("Test case name: %s start time: %v duration: %v so far\n", + Infof("Test case name: %s start time: %v duration: %v so far\n", testTimer.Name, testTimer.StartTime, testTimer.Duration()) } } diff --git a/tests/performance/common/common.go b/tests/performance/common/common.go index 517d65e00..adb81a785 100644 --- a/tests/performance/common/common.go +++ b/tests/performance/common/common.go @@ -29,12 +29,12 @@ import ( "strings" "time" + . "github.com/onsi/gomega" + v1 "k8s.io/api/core/v1" + "github.com/kubeedge/kubeedge/tests/e2e/utils" "github.com/kubeedge/kubeedge/tests/stubs/common/constants" "github.com/kubeedge/kubeedge/tests/stubs/common/types" - - . "github.com/onsi/gomega" - v1 "k8s.io/api/core/v1" ) //K8s resource handlers @@ -111,7 +111,7 @@ func HandleEdgeCorePodDeployment(depHandler, imgURL, podHandler, nodeHandler str count := 0 for edgenodeName := range NodeInfo { status := utils.CheckNodeReadyStatus(nodeHandler, edgenodeName) - utils.Info("Node Name: %v, Node Status: %v", edgenodeName, status) + utils.Infof("Node Name: %v, Node Status: %v", edgenodeName, status) if status == "Running" { count++ } @@ -144,7 +144,7 @@ func DeleteEdgeDeployments(apiServerForRegisterNode, apiServerForDeployments str for edgenodeName := range NodeInfo { err := utils.DeRegisterNodeFromMaster(apiServerForRegisterNode+NodeHandler, edgenodeName) if err != nil { - utils.Failf("DeRegisterNodeFromMaster failed: %v", err) + utils.Fatalf("DeRegisterNodeFromMaster failed: %v", err) } } //Verify deployments, configmaps, nodes are deleted successfully @@ -174,7 +174,7 @@ func DeleteEdgeDeployments(apiServerForRegisterNode, apiServerForDeployments str count := 0 for edgenodeName := range NodeInfo { status := utils.CheckNodeDeleteStatus(apiServerForRegisterNode+NodeHandler, edgenodeName) - utils.Info("Node Name: %v, Node Status: %v", edgenodeName, status) + utils.Infof("Node Name: %v, Node Status: %v", edgenodeName, status) if status == 404 { count++ } @@ -220,14 +220,14 @@ func ApplyLabel(nodeHandler string) error { func AddFakePod(ControllerHubURL string, pod types.FakePod) { reqBody, err := json.Marshal(pod) if err != nil { - utils.Failf("Unmarshal HTTP Response has failed: %v", err) + utils.Fatalf("Unmarshal HTTP Response has failed: %v", err) } err, resp := SendHttpRequest(http.MethodPost, ControllerHubURL+constants.PodResource, bytes.NewBuffer(reqBody)) if err != nil { - utils.Failf("Frame HTTP request failed: %v", err) + utils.Fatalf("Frame HTTP request failed: %v", err) } if resp != nil { @@ -235,13 +235,13 @@ func AddFakePod(ControllerHubURL string, pod types.FakePod) { contents, err := ioutil.ReadAll(resp.Body) if err != nil { - utils.Failf("HTTP Response reading has failed: %v", err) + utils.Fatalf("HTTP Response reading has failed: %v", err) } if contents != nil { - utils.Info("AddPod response: %v", contents) + utils.Infof("AddPod response: %v", contents) } else { - utils.Info("AddPod response: nil") + utils.Infof("AddPod response: nil") } } } @@ -253,7 +253,7 @@ func DeleteFakePod(ControllerHubURL string, pod types.FakePod) { "?name="+pod.Name+"&namespace="+pod.Namespace+"&nodename="+pod.NodeName, nil) if err != nil { - utils.Failf("Frame HTTP request failed: %v", err) + utils.Fatalf("Frame HTTP request failed: %v", err) } if resp != nil { @@ -261,13 +261,13 @@ func DeleteFakePod(ControllerHubURL string, pod types.FakePod) { contents, err := ioutil.ReadAll(resp.Body) if err != nil { - utils.Failf("HTTP Response reading has failed: %v", err) + utils.Fatalf("HTTP Response reading has failed: %v", err) } if contents != nil { - utils.Info("DeletePod response: %v", contents) + utils.Infof("DeletePod response: %v", contents) } else { - utils.Info("DeletePod response: nil") + utils.Infof("DeletePod response: nil") } } } @@ -277,7 +277,7 @@ func ListFakePods(ControllerHubURL string) []types.FakePod { pods := []types.FakePod{} err, resp := SendHttpRequest(http.MethodGet, ControllerHubURL+constants.PodResource, nil) if err != nil { - utils.Failf("Frame HTTP request failed: %v", err) + utils.Fatalf("Frame HTTP request failed: %v", err) } if resp != nil { @@ -285,16 +285,16 @@ func ListFakePods(ControllerHubURL string) []types.FakePod { contents, err := ioutil.ReadAll(resp.Body) if err != nil { - utils.Failf("HTTP Response reading has failed: %v", err) + utils.Fatalf("HTTP Response reading has failed: %v", err) } err = json.Unmarshal(contents, &pods) if err != nil { - utils.Failf("Unmarshal message content with error: %s", err) + utils.Fatalf("Unmarshal message content with error: %s", err) } } - utils.Info("ListPods result: %d", len(pods)) + utils.Infof("ListPods result: %d", len(pods)) return pods } @@ -304,18 +304,18 @@ func SendHttpRequest(method, reqApi string, body io.Reader) (error, *http.Respon client := &http.Client{} req, err := http.NewRequest(method, reqApi, body) if err != nil { - utils.Failf("Frame HTTP request failed: %v", err) + utils.Fatalf("Frame HTTP request failed: %v", err) return err, resp } req.Header.Set("Content-Type", "application/json") t := time.Now() resp, err = client.Do(req) if err != nil { - utils.Failf("HTTP request is failed :%v", err) + utils.Fatalf("HTTP request is failed :%v", err) return err, resp } if resp != nil { - utils.Info("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) + utils.Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t)) } return nil, resp } diff --git a/tests/performance/hubtest/hubtest_suite_test.go b/tests/performance/hubtest/hubtest_suite_test.go index 4b2b84a90..47b3d7ab0 100644 --- a/tests/performance/hubtest/hubtest_suite_test.go +++ b/tests/performance/hubtest/hubtest_suite_test.go @@ -48,7 +48,7 @@ func TestKubeEdgeK8SDeployment(t *testing.T) { // Init suite var _ = BeforeSuite(func() { // Init config - utils.InfoV6("KubeEdge hub performance test begin!") + utils.Infof("KubeEdge hub performance test begin!") cfg = utils.LoadConfig() ctx = utils.NewTestContext(cfg) diff --git a/tests/performance/hubtest/hubtest_test.go b/tests/performance/hubtest/hubtest_test.go index 37822cfc3..769cc7bad 100644 --- a/tests/performance/hubtest/hubtest_test.go +++ b/tests/performance/hubtest/hubtest_test.go @@ -19,7 +19,6 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" metav1 "k8s.io/api/core/v1" - "k8s.io/klog" "github.com/kubeedge/kubeedge/tests/e2e/utils" . "github.com/kubeedge/kubeedge/tests/performance/common" @@ -48,10 +47,10 @@ var _ = Describe("KubeEdge hub performance test", func() { // Get latency if len(pods) > 0 { latency = GetLatency(pods) - klog.Infof("HubTest 50 percent latency: %s", latency.Percent50.String()) - klog.Infof("HubTest 90 percent latency: %s", latency.Percent90.String()) - klog.Infof("HubTest 99 percent latency: %s", latency.Percent99.String()) - klog.Infof("HubTest 100 percent latency: %s", latency.Percent100.String()) + utils.Infof("HubTest 50 percent latency: %s", latency.Percent50.String()) + utils.Infof("HubTest 90 percent latency: %s", latency.Percent90.String()) + utils.Infof("HubTest 99 percent latency: %s", latency.Percent99.String()) + utils.Infof("HubTest 100 percent latency: %s", latency.Percent100.String()) } // Delete Pods @@ -104,11 +103,11 @@ var _ = Describe("KubeEdge hub performance test", func() { count++ } } - klog.Infof("Current running pods count: %d", count) + utils.Infof("Current running pods count: %d", count) return count }, "240s", "100ms").Should(Equal(numOfEdgeNodes*numOfPodsPerEdgeNode), "Wait for Pods in running status timeout") }) - klog.Infof("HubTest runtime stats: %+v", hubTestRuntime) + utils.Infof("HubTest runtime stats: %+v", hubTestRuntime) }, 5) }) }) diff --git a/tests/performance/loadtest/loadtest_suite_test.go b/tests/performance/loadtest/loadtest_suite_test.go index e75cbdaf1..ac24928da 100644 --- a/tests/performance/loadtest/loadtest_suite_test.go +++ b/tests/performance/loadtest/loadtest_suite_test.go @@ -21,13 +21,13 @@ import ( "testing" "time" - "github.com/kubeedge/kubeedge/tests/e2e/utils" - . "github.com/kubeedge/kubeedge/tests/performance/common" - "github.com/kubeedge/viaduct/pkg/api" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" metav1 "k8s.io/api/core/v1" + + "github.com/kubeedge/kubeedge/tests/e2e/utils" + . "github.com/kubeedge/kubeedge/tests/performance/common" + "github.com/kubeedge/viaduct/pkg/api" ) //context to load config and access across the package @@ -47,7 +47,7 @@ func TestEdgecoreK8sDeployment(t *testing.T) { //var toTaint bool RegisterFailHandler(Fail) var _ = BeforeSuite(func() { - utils.InfoV6("Kubeedge deployment Load test Begin !!") + utils.Infof("Kubeedge deployment Load test Begin !!") cfg = utils.LoadConfig() ctx = utils.NewTestContext(cfg) //apply label to all cluster nodes, use the selector to deploy all edgenodes to cluster nodes diff --git a/tests/performance/loadtest/loadtest_test.go b/tests/performance/loadtest/loadtest_test.go index 9bf60885d..1c90ea1d8 100644 --- a/tests/performance/loadtest/loadtest_test.go +++ b/tests/performance/loadtest/loadtest_test.go @@ -25,7 +25,6 @@ import ( . "github.com/onsi/gomega" "k8s.io/api/apps/v1" metav1 "k8s.io/api/core/v1" - "k8s.io/klog" "github.com/kubeedge/kubeedge/tests/e2e/utils" . "github.com/kubeedge/kubeedge/tests/performance/common" @@ -66,7 +65,7 @@ func RestartEdgeNodePodsToUseQuicProtocol() error { var count int for i := range EdgeNodePods { status, statusCode := utils.GetPodState(ctx.Cfg.K8SMasterForProvisionEdgeNodes + AppHandler + "/" + EdgeNodePods[i]) - utils.InfoV2("PodName: %s status: %s StatusCode: %d", EdgeNodePods[i], status, statusCode) + utils.Infof("PodName: %s status: %s StatusCode: %d", EdgeNodePods[i], status, statusCode) if statusCode == 404 { count++ } @@ -81,7 +80,7 @@ func RestartEdgeNodePodsToUseQuicProtocol() error { var count int for _, pod := range newpods.Items { state, _ := utils.GetPodState(ctx.Cfg.K8SMasterForProvisionEdgeNodes + AppHandler + "/" + pod.Name) - utils.InfoV2("PodName: %s PodStatus: %s", pod.Name, state) + utils.Infof("PodName: %s PodStatus: %s", pod.Name, state) if state == "Running" { count++ } @@ -94,7 +93,7 @@ func RestartEdgeNodePodsToUseQuicProtocol() error { count := 0 for edgenodeName := range NodeInfo { status := utils.CheckNodeReadyStatus(ctx.Cfg.K8SMasterForKubeEdge+NodeHandler, edgenodeName) - utils.Info("Node Name: %v, Node Status: %v", edgenodeName, status) + utils.Infof("Node Name: %v, Node Status: %v", edgenodeName, status) if status == "Running" { count++ } @@ -191,7 +190,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) @@ -219,7 +218,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) @@ -247,7 +246,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) Measure("WSS_MEASURE_PERF_NODETEST_NODES_75: Create 75 KubeEdge Node Deployment, Measure time for application comes into Running state", func(b Benchmarker) { @@ -274,7 +273,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) Measure("WSS_MEASURE_PERF_NODETEST_NODES_100: Create 100 KubeEdge Node Deployment, Measure time for application comes into Running state", func(b Benchmarker) { @@ -301,7 +300,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) }) @@ -428,7 +427,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun } utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) Measure("QUIC_MEASURE_PERF_NODETEST_NODES_10: Create 10 KubeEdge Node Deployment, Measure time for application comes into Running state", func(b Benchmarker) { @@ -454,7 +453,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) @@ -481,7 +480,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) Measure("QUIC_MEASURE_PERF_NODETEST_NODES_75: Create 75 KubeEdge Node Deployment, Measure time for application comes into Running state", func(b Benchmarker) { @@ -506,7 +505,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun } utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) Measure("QUIC_MEASURE_PERF_NODETEST_NODES_100: Create 100 KubeEdge Node Deployment, Measure time for application comes into Running state", func(b Benchmarker) { @@ -531,7 +530,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun } utils.CheckPodRunningState(ctx.Cfg.K8SMasterForKubeEdge+AppHandler, podlist) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) }) }) diff --git a/tests/performance/nodedensity/nodedensity_suite_test.go b/tests/performance/nodedensity/nodedensity_suite_test.go index a660ea89c..f09f6e9d5 100644 --- a/tests/performance/nodedensity/nodedensity_suite_test.go +++ b/tests/performance/nodedensity/nodedensity_suite_test.go @@ -21,13 +21,13 @@ import ( "testing" "time" - "github.com/kubeedge/kubeedge/tests/e2e/utils" - . "github.com/kubeedge/kubeedge/tests/performance/common" - "github.com/kubeedge/viaduct/pkg/api" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" metav1 "k8s.io/api/core/v1" + + "github.com/kubeedge/kubeedge/tests/e2e/utils" + . "github.com/kubeedge/kubeedge/tests/performance/common" + "github.com/kubeedge/viaduct/pkg/api" ) //context to load config and access across the package @@ -45,7 +45,7 @@ func TestEdgecoreK8sDeployment(t *testing.T) { //var toTaint bool RegisterFailHandler(Fail) var _ = BeforeSuite(func() { - utils.InfoV6("Kubeedge deployment Load test Begin !!") + utils.Infof("Kubeedge deployment Load test Begin !!") cfg = utils.LoadConfig() ctx = utils.NewTestContext(cfg) //apply label to all cluster nodes, use the selector to deploy all edgenodes to cluster nodes diff --git a/tests/performance/nodedensity/nodedensity_test.go b/tests/performance/nodedensity/nodedensity_test.go index 8fd8a1969..c89b2b16c 100644 --- a/tests/performance/nodedensity/nodedensity_test.go +++ b/tests/performance/nodedensity/nodedensity_test.go @@ -18,7 +18,6 @@ package nodedensity import ( . "github.com/onsi/ginkgo" metav1 "k8s.io/api/core/v1" - "k8s.io/klog" "github.com/kubeedge/kubeedge/tests/e2e/utils" . "github.com/kubeedge/kubeedge/tests/performance/common" @@ -56,7 +55,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun ctx.Cfg.EdgeImageUrl, ctx.Cfg.K8SMasterForProvisionEdgeNodes+AppHandler, ctx.Cfg.K8SMasterForKubeEdge+NodeHandler, NoOfEdgeNodes) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) Measure("PERF_NODETEST_NODES_5: Create 5 KubeEdge Node Deployment, Measure Node Ready time", func(b Benchmarker) { podlist = metav1.PodList{} @@ -68,7 +67,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun ctx.Cfg.EdgeImageUrl, ctx.Cfg.K8SMasterForProvisionEdgeNodes+AppHandler, ctx.Cfg.K8SMasterForKubeEdge+NodeHandler, NoOfEdgeNodes) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) Measure("PERF_NODETEST_NODES_10: Create 10 KubeEdge Node Deployment, Measure Node Ready time", func(b Benchmarker) { @@ -81,7 +80,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun ctx.Cfg.EdgeImageUrl, ctx.Cfg.K8SMasterForProvisionEdgeNodes+AppHandler, ctx.Cfg.K8SMasterForKubeEdge+NodeHandler, NoOfEdgeNodes) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) Measure("PERF_NODETEST_NODES_20: Create 20 KubeEdge Node Deployment, Measure Node Ready time", func(b Benchmarker) { podlist = metav1.PodList{} @@ -93,7 +92,7 @@ var _ = Describe("Application deployment test in Perfronace test EdgeNodes", fun ctx.Cfg.EdgeImageUrl, ctx.Cfg.K8SMasterForProvisionEdgeNodes+AppHandler, ctx.Cfg.K8SMasterForKubeEdge+NodeHandler, NoOfEdgeNodes) }) - klog.Infof("Runtime stats: %+v", runtime) + utils.Infof("Runtime stats: %+v", runtime) }, 5) }) }) diff --git a/tests/stubs/devices/mockserver.go b/tests/stubs/devices/mockserver.go index a02e902c3..b889ac2f8 100644 --- a/tests/stubs/devices/mockserver.go +++ b/tests/stubs/devices/mockserver.go @@ -7,11 +7,10 @@ import ( "os" "time" - "k8s.io/klog" - "github.com/paypal/gatt" "github.com/paypal/gatt/examples/option" "github.com/paypal/gatt/examples/service" + "k8s.io/klog" "github.com/kubeedge/kubeedge/tests/stubs/devices/services" ) diff --git a/tests/stubs/devices/services/temperature.go b/tests/stubs/devices/services/temperature.go index 557f33b17..7157dd932 100644 --- a/tests/stubs/devices/services/temperature.go +++ b/tests/stubs/devices/services/temperature.go @@ -18,6 +18,7 @@ package services import ( "fmt" + "github.com/paypal/gatt" ) diff --git a/tests/stubs/example/main.go b/tests/stubs/example/main.go index aa6e3ae62..1814f3f2f 100644 --- a/tests/stubs/example/main.go +++ b/tests/stubs/example/main.go @@ -37,13 +37,13 @@ const ( ControllerHubURL = "http://127.0.0.1:54321" ) -func init() { +func main() { + var pod types.FakePod + klog.InitFlags(nil) pflag.CommandLine.AddGoFlagSet(flag.CommandLine) -} + pflag.Parse() -func main() { - var pod types.FakePod pod.Name = "TestPod" pod.Namespace = constants.NamespaceDefault pod.NodeName = "edgenode1" diff --git a/vendor/github.com/golang/glog/LICENSE b/vendor/github.com/golang/glog/LICENSE deleted file mode 100644 index 37ec93a14..000000000 --- a/vendor/github.com/golang/glog/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, "control" means (i) the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -"Object" form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -"submitted" means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -2. Grant of Copyright License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -3. Grant of Patent License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -5. Submission of Contributions. - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -6. Trademarks. - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -8. Limitation of Liability. - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same "printed page" as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/golang/glog/README b/vendor/github.com/golang/glog/README deleted file mode 100644 index 387b4eb68..000000000 --- a/vendor/github.com/golang/glog/README +++ /dev/null @@ -1,44 +0,0 @@ -glog -==== - -Leveled execution logs for Go. - -This is an efficient pure Go implementation of leveled logs in the -manner of the open source C++ package - https://github.com/google/glog - -By binding methods to booleans it is possible to use the log package -without paying the expense of evaluating the arguments to the log. -Through the -vmodule flag, the package also provides fine-grained -control over logging at the file level. - -The comment from glog.go introduces the ideas: - - Package glog implements logging analogous to the Google-internal - C++ INFO/ERROR/V setup. It provides functions Info, Warning, - Error, Fatal, plus formatting variants such as Infof. It - also provides V-style logging controlled by the -v and - -vmodule=file=2 flags. - - Basic examples: - - glog.Info("Prepare to repel boarders") - - glog.Fatalf("Initialization failed: %s", err) - - See the documentation for the V function for an explanation - of these examples: - - if glog.V(2) { - glog.Info("Starting transaction...") - } - - glog.V(2).Infoln("Processed", nItems, "elements") - - -The repository contains an open source version of the log package -used inside Google. The master copy of the source lives inside -Google, not here. The code in this repo is for export only and is not itself -under development. Feature requests will be ignored. - -Send bug reports to golang-nuts@googlegroups.com. diff --git a/vendor/github.com/golang/glog/glog.go b/vendor/github.com/golang/glog/glog.go deleted file mode 100644 index 54bd7afdc..000000000 --- a/vendor/github.com/golang/glog/glog.go +++ /dev/null @@ -1,1180 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. -// It provides functions Info, Warning, Error, Fatal, plus formatting variants such as -// Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. -// -// Basic examples: -// -// glog.Info("Prepare to repel boarders") -// -// glog.Fatalf("Initialization failed: %s", err) -// -// See the documentation for the V function for an explanation of these examples: -// -// if glog.V(2) { -// glog.Info("Starting transaction...") -// } -// -// glog.V(2).Infoln("Processed", nItems, "elements") -// -// Log output is buffered and written periodically using Flush. Programs -// should call Flush before exiting to guarantee all log output is written. -// -// By default, all log statements write to files in a temporary directory. -// This package provides several flags that modify this behavior. -// As a result, flag.Parse must be called before any logging is done. -// -// -logtostderr=false -// Logs are written to standard error instead of to files. -// -alsologtostderr=false -// Logs are written to standard error as well as to files. -// -stderrthreshold=ERROR -// Log events at or above this severity are logged to standard -// error as well as to files. -// -log_dir="" -// Log files will be written to this directory instead of the -// default temporary directory. -// -// Other flags provide aids to debugging. -// -// -log_backtrace_at="" -// When set to a file and line number holding a logging statement, -// such as -// -log_backtrace_at=gopherflakes.go:234 -// a stack trace will be written to the Info log whenever execution -// hits that statement. (Unlike with -vmodule, the ".go" must be -// present.) -// -v=0 -// Enable V-leveled logging at the specified level. -// -vmodule="" -// The syntax of the argument is a comma-separated list of pattern=N, -// where pattern is a literal file name (minus the ".go" suffix) or -// "glob" pattern and N is a V level. For instance, -// -vmodule=gopher*=3 -// sets the V level to 3 in all Go files whose names begin "gopher". -// -package glog - -import ( - "bufio" - "bytes" - "errors" - "flag" - "fmt" - "io" - stdLog "log" - "os" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -// severity identifies the sort of log: info, warning etc. It also implements -// the flag.Value interface. The -stderrthreshold flag is of type severity and -// should be modified only through the flag.Value interface. The values match -// the corresponding constants in C++. -type severity int32 // sync/atomic int32 - -// These constants identify the log levels in order of increasing severity. -// A message written to a high-severity log file is also written to each -// lower-severity log file. -const ( - infoLog severity = iota - warningLog - errorLog - fatalLog - numSeverity = 4 -) - -const severityChar = "IWEF" - -var severityName = []string{ - infoLog: "INFO", - warningLog: "WARNING", - errorLog: "ERROR", - fatalLog: "FATAL", -} - -// get returns the value of the severity. -func (s *severity) get() severity { - return severity(atomic.LoadInt32((*int32)(s))) -} - -// set sets the value of the severity. -func (s *severity) set(val severity) { - atomic.StoreInt32((*int32)(s), int32(val)) -} - -// String is part of the flag.Value interface. -func (s *severity) String() string { - return strconv.FormatInt(int64(*s), 10) -} - -// Get is part of the flag.Value interface. -func (s *severity) Get() interface{} { - return *s -} - -// Set is part of the flag.Value interface. -func (s *severity) Set(value string) error { - var threshold severity - // Is it a known name? - if v, ok := severityByName(value); ok { - threshold = v - } else { - v, err := strconv.Atoi(value) - if err != nil { - return err - } - threshold = severity(v) - } - logging.stderrThreshold.set(threshold) - return nil -} - -func severityByName(s string) (severity, bool) { - s = strings.ToUpper(s) - for i, name := range severityName { - if name == s { - return severity(i), true - } - } - return 0, false -} - -// OutputStats tracks the number of output lines and bytes written. -type OutputStats struct { - lines int64 - bytes int64 -} - -// Lines returns the number of lines written. -func (s *OutputStats) Lines() int64 { - return atomic.LoadInt64(&s.lines) -} - -// Bytes returns the number of bytes written. -func (s *OutputStats) Bytes() int64 { - return atomic.LoadInt64(&s.bytes) -} - -// Stats tracks the number of lines of output and number of bytes -// per severity level. Values must be read with atomic.LoadInt64. -var Stats struct { - Info, Warning, Error OutputStats -} - -var severityStats = [numSeverity]*OutputStats{ - infoLog: &Stats.Info, - warningLog: &Stats.Warning, - errorLog: &Stats.Error, -} - -// Level is exported because it appears in the arguments to V and is -// the type of the v flag, which can be set programmatically. -// It's a distinct type because we want to discriminate it from logType. -// Variables of type level are only changed under logging.mu. -// The -v flag is read only with atomic ops, so the state of the logging -// module is consistent. - -// Level is treated as a sync/atomic int32. - -// Level specifies a level of verbosity for V logs. *Level implements -// flag.Value; the -v flag is of type Level and should be modified -// only through the flag.Value interface. -type Level int32 - -// get returns the value of the Level. -func (l *Level) get() Level { - return Level(atomic.LoadInt32((*int32)(l))) -} - -// set sets the value of the Level. -func (l *Level) set(val Level) { - atomic.StoreInt32((*int32)(l), int32(val)) -} - -// String is part of the flag.Value interface. -func (l *Level) String() string { - return strconv.FormatInt(int64(*l), 10) -} - -// Get is part of the flag.Value interface. -func (l *Level) Get() interface{} { - return *l -} - -// Set is part of the flag.Value interface. -func (l *Level) Set(value string) error { - v, err := strconv.Atoi(value) - if err != nil { - return err - } - logging.mu.Lock() - defer logging.mu.Unlock() - logging.setVState(Level(v), logging.vmodule.filter, false) - return nil -} - -// moduleSpec represents the setting of the -vmodule flag. -type moduleSpec struct { - filter []modulePat -} - -// modulePat contains a filter for the -vmodule flag. -// It holds a verbosity level and a file pattern to match. -type modulePat struct { - pattern string - literal bool // The pattern is a literal string - level Level -} - -// match reports whether the file matches the pattern. It uses a string -// comparison if the pattern contains no metacharacters. -func (m *modulePat) match(file string) bool { - if m.literal { - return file == m.pattern - } - match, _ := filepath.Match(m.pattern, file) - return match -} - -func (m *moduleSpec) String() string { - // Lock because the type is not atomic. TODO: clean this up. - logging.mu.Lock() - defer logging.mu.Unlock() - var b bytes.Buffer - for i, f := range m.filter { - if i > 0 { - b.WriteRune(',') - } - fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) - } - return b.String() -} - -// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the -// struct is not exported. -func (m *moduleSpec) Get() interface{} { - return nil -} - -var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") - -// Syntax: -vmodule=recordio=2,file=1,gfs*=3 -func (m *moduleSpec) Set(value string) error { - var filter []modulePat - for _, pat := range strings.Split(value, ",") { - if len(pat) == 0 { - // Empty strings such as from a trailing comma can be ignored. - continue - } - patLev := strings.Split(pat, "=") - if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { - return errVmoduleSyntax - } - pattern := patLev[0] - v, err := strconv.Atoi(patLev[1]) - if err != nil { - return errors.New("syntax error: expect comma-separated list of filename=N") - } - if v < 0 { - return errors.New("negative value for vmodule level") - } - if v == 0 { - continue // Ignore. It's harmless but no point in paying the overhead. - } - // TODO: check syntax of filter? - filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)}) - } - logging.mu.Lock() - defer logging.mu.Unlock() - logging.setVState(logging.verbosity, filter, true) - return nil -} - -// isLiteral reports whether the pattern is a literal string, that is, has no metacharacters -// that require filepath.Match to be called to match the pattern. -func isLiteral(pattern string) bool { - return !strings.ContainsAny(pattern, `\*?[]`) -} - -// traceLocation represents the setting of the -log_backtrace_at flag. -type traceLocation struct { - file string - line int -} - -// isSet reports whether the trace location has been specified. -// logging.mu is held. -func (t *traceLocation) isSet() bool { - return t.line > 0 -} - -// match reports whether the specified file and line matches the trace location. -// The argument file name is the full path, not the basename specified in the flag. -// logging.mu is held. -func (t *traceLocation) match(file string, line int) bool { - if t.line != line { - return false - } - if i := strings.LastIndex(file, "/"); i >= 0 { - file = file[i+1:] - } - return t.file == file -} - -func (t *traceLocation) String() string { - // Lock because the type is not atomic. TODO: clean this up. - logging.mu.Lock() - defer logging.mu.Unlock() - return fmt.Sprintf("%s:%d", t.file, t.line) -} - -// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the -// struct is not exported -func (t *traceLocation) Get() interface{} { - return nil -} - -var errTraceSyntax = errors.New("syntax error: expect file.go:234") - -// Syntax: -log_backtrace_at=gopherflakes.go:234 -// Note that unlike vmodule the file extension is included here. -func (t *traceLocation) Set(value string) error { - if value == "" { - // Unset. - t.line = 0 - t.file = "" - } - fields := strings.Split(value, ":") - if len(fields) != 2 { - return errTraceSyntax - } - file, line := fields[0], fields[1] - if !strings.Contains(file, ".") { - return errTraceSyntax - } - v, err := strconv.Atoi(line) - if err != nil { - return errTraceSyntax - } - if v <= 0 { - return errors.New("negative or zero value for level") - } - logging.mu.Lock() - defer logging.mu.Unlock() - t.line = v - t.file = file - return nil -} - -// flushSyncWriter is the interface satisfied by logging destinations. -type flushSyncWriter interface { - Flush() error - Sync() error - io.Writer -} - -func init() { - flag.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files") - flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files") - flag.Var(&logging.verbosity, "v", "log level for V logs") - flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") - flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") - flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") - - // Default stderrThreshold is ERROR. - logging.stderrThreshold = errorLog - - logging.setVState(0, nil, false) - go logging.flushDaemon() -} - -// Flush flushes all pending log I/O. -func Flush() { - logging.lockAndFlushAll() -} - -// loggingT collects all the global state of the logging setup. -type loggingT struct { - // Boolean flags. Not handled atomically because the flag.Value interface - // does not let us avoid the =true, and that shorthand is necessary for - // compatibility. TODO: does this matter enough to fix? Seems unlikely. - toStderr bool // The -logtostderr flag. - alsoToStderr bool // The -alsologtostderr flag. - - // Level flag. Handled atomically. - stderrThreshold severity // The -stderrthreshold flag. - - // freeList is a list of byte buffers, maintained under freeListMu. - freeList *buffer - // freeListMu maintains the free list. It is separate from the main mutex - // so buffers can be grabbed and printed to without holding the main lock, - // for better parallelization. - freeListMu sync.Mutex - - // mu protects the remaining elements of this structure and is - // used to synchronize logging. - mu sync.Mutex - // file holds writer for each of the log types. - file [numSeverity]flushSyncWriter - // pcs is used in V to avoid an allocation when computing the caller's PC. - pcs [1]uintptr - // vmap is a cache of the V Level for each V() call site, identified by PC. - // It is wiped whenever the vmodule flag changes state. - vmap map[uintptr]Level - // filterLength stores the length of the vmodule filter chain. If greater - // than zero, it means vmodule is enabled. It may be read safely - // using sync.LoadInt32, but is only modified under mu. - filterLength int32 - // traceLocation is the state of the -log_backtrace_at flag. - traceLocation traceLocation - // These flags are modified only under lock, although verbosity may be fetched - // safely using atomic.LoadInt32. - vmodule moduleSpec // The state of the -vmodule flag. - verbosity Level // V logging level, the value of the -v flag/ -} - -// buffer holds a byte Buffer for reuse. The zero value is ready for use. -type buffer struct { - bytes.Buffer - tmp [64]byte // temporary byte array for creating headers. - next *buffer -} - -var logging loggingT - -// setVState sets a consistent state for V logging. -// l.mu is held. -func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) { - // Turn verbosity off so V will not fire while we are in transition. - logging.verbosity.set(0) - // Ditto for filter length. - atomic.StoreInt32(&logging.filterLength, 0) - - // Set the new filters and wipe the pc->Level map if the filter has changed. - if setFilter { - logging.vmodule.filter = filter - logging.vmap = make(map[uintptr]Level) - } - - // Things are consistent now, so enable filtering and verbosity. - // They are enabled in order opposite to that in V. - atomic.StoreInt32(&logging.filterLength, int32(len(filter))) - logging.verbosity.set(verbosity) -} - -// getBuffer returns a new, ready-to-use buffer. -func (l *loggingT) getBuffer() *buffer { - l.freeListMu.Lock() - b := l.freeList - if b != nil { - l.freeList = b.next - } - l.freeListMu.Unlock() - if b == nil { - b = new(buffer) - } else { - b.next = nil - b.Reset() - } - return b -} - -// putBuffer returns a buffer to the free list. -func (l *loggingT) putBuffer(b *buffer) { - if b.Len() >= 256 { - // Let big buffers die a natural death. - return - } - l.freeListMu.Lock() - b.next = l.freeList - l.freeList = b - l.freeListMu.Unlock() -} - -var timeNow = time.Now // Stubbed out for testing. - -/* -header formats a log header as defined by the C++ implementation. -It returns a buffer containing the formatted header and the user's file and line number. -The depth specifies how many stack frames above lives the source line to be identified in the log message. - -Log lines have this form: - Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... -where the fields are defined as follows: - L A single character, representing the log level (eg 'I' for INFO) - mm The month (zero padded; ie May is '05') - dd The day (zero padded) - hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds - threadid The space-padded thread ID as returned by GetTID() - file The file name - line The line number - msg The user-supplied message -*/ -func (l *loggingT) header(s severity, depth int) (*buffer, string, int) { - _, file, line, ok := runtime.Caller(3 + depth) - if !ok { - file = "???" - line = 1 - } else { - slash := strings.LastIndex(file, "/") - if slash >= 0 { - file = file[slash+1:] - } - } - return l.formatHeader(s, file, line), file, line -} - -// formatHeader formats a log header using the provided file name and line number. -func (l *loggingT) formatHeader(s severity, file string, line int) *buffer { - now := timeNow() - if line < 0 { - line = 0 // not a real line number, but acceptable to someDigits - } - if s > fatalLog { - s = infoLog // for safety. - } - buf := l.getBuffer() - - // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. - // It's worth about 3X. Fprintf is hard. - _, month, day := now.Date() - hour, minute, second := now.Clock() - // Lmmdd hh:mm:ss.uuuuuu threadid file:line] - buf.tmp[0] = severityChar[s] - buf.twoDigits(1, int(month)) - buf.twoDigits(3, day) - buf.tmp[5] = ' ' - buf.twoDigits(6, hour) - buf.tmp[8] = ':' - buf.twoDigits(9, minute) - buf.tmp[11] = ':' - buf.twoDigits(12, second) - buf.tmp[14] = '.' - buf.nDigits(6, 15, now.Nanosecond()/1000, '0') - buf.tmp[21] = ' ' - buf.nDigits(7, 22, pid, ' ') // TODO: should be TID - buf.tmp[29] = ' ' - buf.Write(buf.tmp[:30]) - buf.WriteString(file) - buf.tmp[0] = ':' - n := buf.someDigits(1, line) - buf.tmp[n+1] = ']' - buf.tmp[n+2] = ' ' - buf.Write(buf.tmp[:n+3]) - return buf -} - -// Some custom tiny helper functions to print the log header efficiently. - -const digits = "0123456789" - -// twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i]. -func (buf *buffer) twoDigits(i, d int) { - buf.tmp[i+1] = digits[d%10] - d /= 10 - buf.tmp[i] = digits[d%10] -} - -// nDigits formats an n-digit integer at buf.tmp[i], -// padding with pad on the left. -// It assumes d >= 0. -func (buf *buffer) nDigits(n, i, d int, pad byte) { - j := n - 1 - for ; j >= 0 && d > 0; j-- { - buf.tmp[i+j] = digits[d%10] - d /= 10 - } - for ; j >= 0; j-- { - buf.tmp[i+j] = pad - } -} - -// someDigits formats a zero-prefixed variable-width integer at buf.tmp[i]. -func (buf *buffer) someDigits(i, d int) int { - // Print into the top, then copy down. We know there's space for at least - // a 10-digit number. - j := len(buf.tmp) - for { - j-- - buf.tmp[j] = digits[d%10] - d /= 10 - if d == 0 { - break - } - } - return copy(buf.tmp[i:], buf.tmp[j:]) -} - -func (l *loggingT) println(s severity, args ...interface{}) { - buf, file, line := l.header(s, 0) - fmt.Fprintln(buf, args...) - l.output(s, buf, file, line, false) -} - -func (l *loggingT) print(s severity, args ...interface{}) { - l.printDepth(s, 1, args...) -} - -func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) { - buf, file, line := l.header(s, depth) - fmt.Fprint(buf, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, false) -} - -func (l *loggingT) printf(s severity, format string, args ...interface{}) { - buf, file, line := l.header(s, 0) - fmt.Fprintf(buf, format, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, false) -} - -// printWithFileLine behaves like print but uses the provided file and line number. If -// alsoLogToStderr is true, the log message always appears on standard error; it -// will also appear in the log file unless --logtostderr is set. -func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) { - buf := l.formatHeader(s, file, line) - fmt.Fprint(buf, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, alsoToStderr) -} - -// output writes the data to the log files and releases the buffer. -func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) { - l.mu.Lock() - if l.traceLocation.isSet() { - if l.traceLocation.match(file, line) { - buf.Write(stacks(false)) - } - } - data := buf.Bytes() - if !flag.Parsed() { - os.Stderr.Write([]byte("ERROR: logging before flag.Parse: ")) - os.Stderr.Write(data) - } else if l.toStderr { - os.Stderr.Write(data) - } else { - if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() { - os.Stderr.Write(data) - } - if l.file[s] == nil { - if err := l.createFiles(s); err != nil { - os.Stderr.Write(data) // Make sure the message appears somewhere. - l.exit(err) - } - } - switch s { - case fatalLog: - l.file[fatalLog].Write(data) - fallthrough - case errorLog: - l.file[errorLog].Write(data) - fallthrough - case warningLog: - l.file[warningLog].Write(data) - fallthrough - case infoLog: - l.file[infoLog].Write(data) - } - } - if s == fatalLog { - // If we got here via Exit rather than Fatal, print no stacks. - if atomic.LoadUint32(&fatalNoStacks) > 0 { - l.mu.Unlock() - timeoutFlush(10 * time.Second) - os.Exit(1) - } - // Dump all goroutine stacks before exiting. - // First, make sure we see the trace for the current goroutine on standard error. - // If -logtostderr has been specified, the loop below will do that anyway - // as the first stack in the full dump. - if !l.toStderr { - os.Stderr.Write(stacks(false)) - } - // Write the stack trace for all goroutines to the files. - trace := stacks(true) - logExitFunc = func(error) {} // If we get a write error, we'll still exit below. - for log := fatalLog; log >= infoLog; log-- { - if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set. - f.Write(trace) - } - } - l.mu.Unlock() - timeoutFlush(10 * time.Second) - os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway. - } - l.putBuffer(buf) - l.mu.Unlock() - if stats := severityStats[s]; stats != nil { - atomic.AddInt64(&stats.lines, 1) - atomic.AddInt64(&stats.bytes, int64(len(data))) - } -} - -// timeoutFlush calls Flush and returns when it completes or after timeout -// elapses, whichever happens first. This is needed because the hooks invoked -// by Flush may deadlock when glog.Fatal is called from a hook that holds -// a lock. -func timeoutFlush(timeout time.Duration) { - done := make(chan bool, 1) - go func() { - Flush() // calls logging.lockAndFlushAll() - done <- true - }() - select { - case <-done: - case <-time.After(timeout): - fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout) - } -} - -// stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines. -func stacks(all bool) []byte { - // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though. - n := 10000 - if all { - n = 100000 - } - var trace []byte - for i := 0; i < 5; i++ { - trace = make([]byte, n) - nbytes := runtime.Stack(trace, all) - if nbytes < len(trace) { - return trace[:nbytes] - } - n *= 2 - } - return trace -} - -// logExitFunc provides a simple mechanism to override the default behavior -// of exiting on error. Used in testing and to guarantee we reach a required exit -// for fatal logs. Instead, exit could be a function rather than a method but that -// would make its use clumsier. -var logExitFunc func(error) - -// exit is called if there is trouble creating or writing log files. -// It flushes the logs and exits the program; there's no point in hanging around. -// l.mu is held. -func (l *loggingT) exit(err error) { - fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err) - // If logExitFunc is set, we do that instead of exiting. - if logExitFunc != nil { - logExitFunc(err) - return - } - l.flushAll() - os.Exit(2) -} - -// syncBuffer joins a bufio.Writer to its underlying file, providing access to the -// file's Sync method and providing a wrapper for the Write method that provides log -// file rotation. There are conflicting methods, so the file cannot be embedded. -// l.mu is held for all its methods. -type syncBuffer struct { - logger *loggingT - *bufio.Writer - file *os.File - sev severity - nbytes uint64 // The number of bytes written to this file -} - -func (sb *syncBuffer) Sync() error { - return sb.file.Sync() -} - -func (sb *syncBuffer) Write(p []byte) (n int, err error) { - if sb.nbytes+uint64(len(p)) >= MaxSize { - if err := sb.rotateFile(time.Now()); err != nil { - sb.logger.exit(err) - } - } - n, err = sb.Writer.Write(p) - sb.nbytes += uint64(n) - if err != nil { - sb.logger.exit(err) - } - return -} - -// rotateFile closes the syncBuffer's file and starts a new one. -func (sb *syncBuffer) rotateFile(now time.Time) error { - if sb.file != nil { - sb.Flush() - sb.file.Close() - } - var err error - sb.file, _, err = create(severityName[sb.sev], now) - sb.nbytes = 0 - if err != nil { - return err - } - - sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) - - // Write header. - var buf bytes.Buffer - fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) - fmt.Fprintf(&buf, "Running on machine: %s\n", host) - fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) - fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") - n, err := sb.file.Write(buf.Bytes()) - sb.nbytes += uint64(n) - return err -} - -// bufferSize sizes the buffer associated with each log file. It's large -// so that log records can accumulate without the logging thread blocking -// on disk I/O. The flushDaemon will block instead. -const bufferSize = 256 * 1024 - -// createFiles creates all the log files for severity from sev down to infoLog. -// l.mu is held. -func (l *loggingT) createFiles(sev severity) error { - now := time.Now() - // Files are created in decreasing severity order, so as soon as we find one - // has already been created, we can stop. - for s := sev; s >= infoLog && l.file[s] == nil; s-- { - sb := &syncBuffer{ - logger: l, - sev: s, - } - if err := sb.rotateFile(now); err != nil { - return err - } - l.file[s] = sb - } - return nil -} - -const flushInterval = 30 * time.Second - -// flushDaemon periodically flushes the log file buffers. -func (l *loggingT) flushDaemon() { - for _ = range time.NewTicker(flushInterval).C { - l.lockAndFlushAll() - } -} - -// lockAndFlushAll is like flushAll but locks l.mu first. -func (l *loggingT) lockAndFlushAll() { - l.mu.Lock() - l.flushAll() - l.mu.Unlock() -} - -// flushAll flushes all the logs and attempts to "sync" their data to disk. -// l.mu is held. -func (l *loggingT) flushAll() { - // Flush from fatal down, in case there's trouble flushing. - for s := fatalLog; s >= infoLog; s-- { - file := l.file[s] - if file != nil { - file.Flush() // ignore error - file.Sync() // ignore error - } - } -} - -// CopyStandardLogTo arranges for messages written to the Go "log" package's -// default logs to also appear in the Google logs for the named and lower -// severities. Subsequent changes to the standard log's default output location -// or format may break this behavior. -// -// Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not -// recognized, CopyStandardLogTo panics. -func CopyStandardLogTo(name string) { - sev, ok := severityByName(name) - if !ok { - panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name)) - } - // Set a log format that captures the user's file and line: - // d.go:23: message - stdLog.SetFlags(stdLog.Lshortfile) - stdLog.SetOutput(logBridge(sev)) -} - -// logBridge provides the Write method that enables CopyStandardLogTo to connect -// Go's standard logs to the logs provided by this package. -type logBridge severity - -// Write parses the standard logging line and passes its components to the -// logger for severity(lb). -func (lb logBridge) Write(b []byte) (n int, err error) { - var ( - file = "???" - line = 1 - text string - ) - // Split "d.go:23: message" into "d.go", "23", and "message". - if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 { - text = fmt.Sprintf("bad log format: %s", b) - } else { - file = string(parts[0]) - text = string(parts[2][1:]) // skip leading space - line, err = strconv.Atoi(string(parts[1])) - if err != nil { - text = fmt.Sprintf("bad line number: %s", b) - line = 1 - } - } - // printWithFileLine with alsoToStderr=true, so standard log messages - // always appear on standard error. - logging.printWithFileLine(severity(lb), file, line, true, text) - return len(b), nil -} - -// setV computes and remembers the V level for a given PC -// when vmodule is enabled. -// File pattern matching takes the basename of the file, stripped -// of its .go suffix, and uses filepath.Match, which is a little more -// general than the *? matching used in C++. -// l.mu is held. -func (l *loggingT) setV(pc uintptr) Level { - fn := runtime.FuncForPC(pc) - file, _ := fn.FileLine(pc) - // The file is something like /a/b/c/d.go. We want just the d. - if strings.HasSuffix(file, ".go") { - file = file[:len(file)-3] - } - if slash := strings.LastIndex(file, "/"); slash >= 0 { - file = file[slash+1:] - } - for _, filter := range l.vmodule.filter { - if filter.match(file) { - l.vmap[pc] = filter.level - return filter.level - } - } - l.vmap[pc] = 0 - return 0 -} - -// Verbose is a boolean type that implements Infof (like Printf) etc. -// See the documentation of V for more information. -type Verbose bool - -// V reports whether verbosity at the call site is at least the requested level. -// The returned value is a boolean of type Verbose, which implements Info, Infoln -// and Infof. These methods will write to the Info log if called. -// Thus, one may write either -// if glog.V(2) { glog.Info("log this") } -// or -// glog.V(2).Info("log this") -// The second form is shorter but the first is cheaper if logging is off because it does -// not evaluate its arguments. -// -// Whether an individual call to V generates a log record depends on the setting of -// the -v and --vmodule flags; both are off by default. If the level in the call to -// V is at least the value of -v, or of -vmodule for the source file containing the -// call, the V call will log. -func V(level Level) Verbose { - // This function tries hard to be cheap unless there's work to do. - // The fast path is two atomic loads and compares. - - // Here is a cheap but safe test to see if V logging is enabled globally. - if logging.verbosity.get() >= level { - return Verbose(true) - } - - // It's off globally but it vmodule may still be set. - // Here is another cheap but safe test to see if vmodule is enabled. - if atomic.LoadInt32(&logging.filterLength) > 0 { - // Now we need a proper lock to use the logging structure. The pcs field - // is shared so we must lock before accessing it. This is fairly expensive, - // but if V logging is enabled we're slow anyway. - logging.mu.Lock() - defer logging.mu.Unlock() - if runtime.Callers(2, logging.pcs[:]) == 0 { - return Verbose(false) - } - v, ok := logging.vmap[logging.pcs[0]] - if !ok { - v = logging.setV(logging.pcs[0]) - } - return Verbose(v >= level) - } - return Verbose(false) -} - -// Info is equivalent to the global Info function, guarded by the value of v. -// See the documentation of V for usage. -func (v Verbose) Info(args ...interface{}) { - if v { - logging.print(infoLog, args...) - } -} - -// Infoln is equivalent to the global Infoln function, guarded by the value of v. -// See the documentation of V for usage. -func (v Verbose) Infoln(args ...interface{}) { - if v { - logging.println(infoLog, args...) - } -} - -// Infof is equivalent to the global Infof function, guarded by the value of v. -// See the documentation of V for usage. -func (v Verbose) Infof(format string, args ...interface{}) { - if v { - logging.printf(infoLog, format, args...) - } -} - -// Info logs to the INFO log. -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Info(args ...interface{}) { - logging.print(infoLog, args...) -} - -// InfoDepth acts as Info but uses depth to determine which call frame to log. -// InfoDepth(0, "msg") is the same as Info("msg"). -func InfoDepth(depth int, args ...interface{}) { - logging.printDepth(infoLog, depth, args...) -} - -// Infoln logs to the INFO log. -// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. -func Infoln(args ...interface{}) { - logging.println(infoLog, args...) -} - -// Infof logs to the INFO log. -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Infof(format string, args ...interface{}) { - logging.printf(infoLog, format, args...) -} - -// Warning logs to the WARNING and INFO logs. -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Warning(args ...interface{}) { - logging.print(warningLog, args...) -} - -// WarningDepth acts as Warning but uses depth to determine which call frame to log. -// WarningDepth(0, "msg") is the same as Warning("msg"). -func WarningDepth(depth int, args ...interface{}) { - logging.printDepth(warningLog, depth, args...) -} - -// Warningln logs to the WARNING and INFO logs. -// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. -func Warningln(args ...interface{}) { - logging.println(warningLog, args...) -} - -// Warningf logs to the WARNING and INFO logs. -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Warningf(format string, args ...interface{}) { - logging.printf(warningLog, format, args...) -} - -// Error logs to the ERROR, WARNING, and INFO logs. -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Error(args ...interface{}) { - logging.print(errorLog, args...) -} - -// ErrorDepth acts as Error but uses depth to determine which call frame to log. -// ErrorDepth(0, "msg") is the same as Error("msg"). -func ErrorDepth(depth int, args ...interface{}) { - logging.printDepth(errorLog, depth, args...) -} - -// Errorln logs to the ERROR, WARNING, and INFO logs. -// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. -func Errorln(args ...interface{}) { - logging.println(errorLog, args...) -} - -// Errorf logs to the ERROR, WARNING, and INFO logs. -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Errorf(format string, args ...interface{}) { - logging.printf(errorLog, format, args...) -} - -// Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Fatal(args ...interface{}) { - logging.print(fatalLog, args...) -} - -// FatalDepth acts as Fatal but uses depth to determine which call frame to log. -// FatalDepth(0, "msg") is the same as Fatal("msg"). -func FatalDepth(depth int, args ...interface{}) { - logging.printDepth(fatalLog, depth, args...) -} - -// Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). -// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. -func Fatalln(args ...interface{}) { - logging.println(fatalLog, args...) -} - -// Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Fatalf(format string, args ...interface{}) { - logging.printf(fatalLog, format, args...) -} - -// fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks. -// It allows Exit and relatives to use the Fatal logs. -var fatalNoStacks uint32 - -// Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Exit(args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.print(fatalLog, args...) -} - -// ExitDepth acts as Exit but uses depth to determine which call frame to log. -// ExitDepth(0, "msg") is the same as Exit("msg"). -func ExitDepth(depth int, args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.printDepth(fatalLog, depth, args...) -} - -// Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). -func Exitln(args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.println(fatalLog, args...) -} - -// Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Exitf(format string, args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.printf(fatalLog, format, args...) -} diff --git a/vendor/github.com/golang/glog/glog_file.go b/vendor/github.com/golang/glog/glog_file.go deleted file mode 100644 index 65075d281..000000000 --- a/vendor/github.com/golang/glog/glog_file.go +++ /dev/null @@ -1,124 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// File I/O for logs. - -package glog - -import ( - "errors" - "flag" - "fmt" - "os" - "os/user" - "path/filepath" - "strings" - "sync" - "time" -) - -// MaxSize is the maximum size of a log file in bytes. -var MaxSize uint64 = 1024 * 1024 * 1800 - -// logDirs lists the candidate directories for new log files. -var logDirs []string - -// If non-empty, overrides the choice of directory in which to write logs. -// See createLogDirs for the full list of possible destinations. -var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory") - -func createLogDirs() { - if *logDir != "" { - logDirs = append(logDirs, *logDir) - } - logDirs = append(logDirs, os.TempDir()) -} - -var ( - pid = os.Getpid() - program = filepath.Base(os.Args[0]) - host = "unknownhost" - userName = "unknownuser" -) - -func init() { - h, err := os.Hostname() - if err == nil { - host = shortHostname(h) - } - - current, err := user.Current() - if err == nil { - userName = current.Username - } - - // Sanitize userName since it may contain filepath separators on Windows. - userName = strings.Replace(userName, `\`, "_", -1) -} - -// shortHostname returns its argument, truncating at the first period. -// For instance, given "www.google.com" it returns "www". -func shortHostname(hostname string) string { - if i := strings.Index(hostname, "."); i >= 0 { - return hostname[:i] - } - return hostname -} - -// logName returns a new log file name containing tag, with start time t, and -// the name for the symlink for tag. -func logName(tag string, t time.Time) (name, link string) { - name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d", - program, - host, - userName, - tag, - t.Year(), - t.Month(), - t.Day(), - t.Hour(), - t.Minute(), - t.Second(), - pid) - return name, program + "." + tag -} - -var onceLogDirs sync.Once - -// create creates a new log file and returns the file and its filename, which -// contains tag ("INFO", "FATAL", etc.) and t. If the file is created -// successfully, create also attempts to update the symlink for that tag, ignoring -// errors. -func create(tag string, t time.Time) (f *os.File, filename string, err error) { - onceLogDirs.Do(createLogDirs) - if len(logDirs) == 0 { - return nil, "", errors.New("log: no log dirs") - } - name, link := logName(tag, t) - var lastErr error - for _, dir := range logDirs { - fname := filepath.Join(dir, name) - f, err := os.Create(fname) - if err == nil { - symlink := filepath.Join(dir, link) - os.Remove(symlink) // ignore err - os.Symlink(name, symlink) // ignore err - return f, fname, nil - } - lastErr = err - } - return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr) -} diff --git a/vendor/k8s.io/klog/.travis.yml b/vendor/k8s.io/klog/.travis.yml index 0f508dae6..5677664c2 100644 --- a/vendor/k8s.io/klog/.travis.yml +++ b/vendor/k8s.io/klog/.travis.yml @@ -5,11 +5,12 @@ go: - 1.9.x - 1.10.x - 1.11.x + - 1.12.x script: - go get -t -v ./... - diff -u <(echo -n) <(gofmt -d .) - diff -u <(echo -n) <(golint $(go list -e ./...)) - - go tool vet . + - go tool vet . || go vet . - go test -v -race ./... install: - go get golang.org/x/lint/golint diff --git a/vendor/k8s.io/klog/README.md b/vendor/k8s.io/klog/README.md index bee306f39..841468b4b 100644 --- a/vendor/k8s.io/klog/README.md +++ b/vendor/k8s.io/klog/README.md @@ -31,7 +31,7 @@ How to use klog - Use `klog.InitFlags(nil)` explicitly for initializing global flags as we no longer use `init()` method to register the flags - You can now use `log-file` instead of `log-dir` for logging to a single file (See `examples/log_file/usage_log_file.go`) - If you want to redirect everything logged using klog somewhere else (say syslog!), you can use `klog.SetOutput()` method and supply a `io.Writer`. (See `examples/set_output/usage_set_output.go`) -- For more logging conventions (See [Logging Conventions](https://github.com/kubernetes/community/blob/master/contributors/devel/logging.md)) +- For more logging conventions (See [Logging Conventions](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md)) ### Coexisting with glog This package can be used side by side with glog. [This example](examples/coexist_glog/coexist_glog.go) shows how to initialize and syncronize flags from the global `flag.CommandLine` FlagSet. In addition, the example makes use of stderr as combined output by setting `alsologtostderr` (or `logtostderr`) to `true`. diff --git a/vendor/k8s.io/klog/go.mod b/vendor/k8s.io/klog/go.mod new file mode 100644 index 000000000..3877d8546 --- /dev/null +++ b/vendor/k8s.io/klog/go.mod @@ -0,0 +1,5 @@ +module k8s.io/klog + +go 1.12 + +require github.com/go-logr/logr v0.1.0 diff --git a/vendor/k8s.io/klog/go.sum b/vendor/k8s.io/klog/go.sum new file mode 100644 index 000000000..fb64d277a --- /dev/null +++ b/vendor/k8s.io/klog/go.sum @@ -0,0 +1,2 @@ +github.com/go-logr/logr v0.1.0 h1:M1Tv3VzNlEHg6uyACnRdtrploV2P7wZqH8BoQMtz0cg= +github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= diff --git a/vendor/k8s.io/klog/klog.go b/vendor/k8s.io/klog/klog.go index 10330d7ef..2520ebdaa 100644 --- a/vendor/k8s.io/klog/klog.go +++ b/vendor/k8s.io/klog/klog.go @@ -20,17 +20,17 @@ // // Basic examples: // -// glog.Info("Prepare to repel boarders") +// klog.Info("Prepare to repel boarders") // -// glog.Fatalf("Initialization failed: %s", err) +// klog.Fatalf("Initialization failed: %s", err) // // See the documentation for the V function for an explanation of these examples: // -// if glog.V(2) { -// glog.Info("Starting transaction...") +// if klog.V(2) { +// klog.Info("Starting transaction...") // } // -// glog.V(2).Infoln("Processed", nItems, "elements") +// klog.V(2).Infoln("Processed", nItems, "elements") // // Log output is buffered and written periodically using Flush. Programs // should call Flush before exiting to guarantee all log output is written. @@ -417,6 +417,7 @@ func InitFlags(flagset *flag.FlagSet) { logging.toStderr = true logging.alsoToStderr = false logging.skipHeaders = false + logging.addDirHeader = false logging.skipLogHeaders = false }) @@ -432,6 +433,7 @@ func InitFlags(flagset *flag.FlagSet) { flagset.BoolVar(&logging.toStderr, "logtostderr", logging.toStderr, "log to standard error instead of files") flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", logging.alsoToStderr, "log to standard error as well as files") flagset.Var(&logging.verbosity, "v", "number for the log level verbosity") + flagset.BoolVar(&logging.skipHeaders, "add_dir_header", logging.addDirHeader, "If true, adds the file directory to the header") flagset.BoolVar(&logging.skipHeaders, "skip_headers", logging.skipHeaders, "If true, avoid header prefixes in the log messages") flagset.BoolVar(&logging.skipLogHeaders, "skip_log_headers", logging.skipLogHeaders, "If true, avoid headers when opening log files") flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") @@ -500,6 +502,9 @@ type loggingT struct { // If true, do not add the headers to log files skipLogHeaders bool + + // If true, add the file directory to the header + addDirHeader bool } // buffer holds a byte Buffer for reuse. The zero value is ready for use. @@ -585,9 +590,14 @@ func (l *loggingT) header(s severity, depth int) (*buffer, string, int) { file = "???" line = 1 } else { - slash := strings.LastIndex(file, "/") - if slash >= 0 { - file = file[slash+1:] + if slash := strings.LastIndex(file, "/"); slash >= 0 { + path := file + file = path[slash+1:] + if l.addDirHeader { + if dirsep := strings.LastIndex(path[:slash], "/"); dirsep >= 0 { + file = path[dirsep+1:] + } + } } } return l.formatHeader(s, file, line), file, line @@ -736,6 +746,8 @@ func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) { // SetOutput sets the output destination for all severities func SetOutput(w io.Writer) { + logging.mu.Lock() + defer logging.mu.Unlock() for s := fatalLog; s >= infoLog; s-- { rb := &redirectBuffer{ w: w, @@ -746,6 +758,8 @@ func SetOutput(w io.Writer) { // SetOutputBySeverity sets the output destination for specific severity func SetOutputBySeverity(name string, w io.Writer) { + logging.mu.Lock() + defer logging.mu.Unlock() sev, ok := severityByName(name) if !ok { panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name)) @@ -771,24 +785,38 @@ func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoTo if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() { os.Stderr.Write(data) } - if l.file[s] == nil { - if err := l.createFiles(s); err != nil { - os.Stderr.Write(data) // Make sure the message appears somewhere. - l.exit(err) + + if logging.logFile != "" { + // Since we are using a single log file, all of the items in l.file array + // will point to the same file, so just use one of them to write data. + if l.file[infoLog] == nil { + if err := l.createFiles(infoLog); err != nil { + os.Stderr.Write(data) // Make sure the message appears somewhere. + l.exit(err) + } } - } - switch s { - case fatalLog: - l.file[fatalLog].Write(data) - fallthrough - case errorLog: - l.file[errorLog].Write(data) - fallthrough - case warningLog: - l.file[warningLog].Write(data) - fallthrough - case infoLog: l.file[infoLog].Write(data) + } else { + if l.file[s] == nil { + if err := l.createFiles(s); err != nil { + os.Stderr.Write(data) // Make sure the message appears somewhere. + l.exit(err) + } + } + + switch s { + case fatalLog: + l.file[fatalLog].Write(data) + fallthrough + case errorLog: + l.file[errorLog].Write(data) + fallthrough + case warningLog: + l.file[warningLog].Write(data) + fallthrough + case infoLog: + l.file[infoLog].Write(data) + } } } if s == fatalLog { @@ -827,7 +855,7 @@ func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoTo // timeoutFlush calls Flush and returns when it completes or after timeout // elapses, whichever happens first. This is needed because the hooks invoked -// by Flush may deadlock when glog.Fatal is called from a hook that holds +// by Flush may deadlock when klog.Fatal is called from a hook that holds // a lock. func timeoutFlush(timeout time.Duration) { done := make(chan bool, 1) @@ -838,7 +866,7 @@ func timeoutFlush(timeout time.Duration) { select { case <-done: case <-time.After(timeout): - fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout) + fmt.Fprintln(os.Stderr, "klog: Flush took longer than", timeout) } } @@ -1094,9 +1122,9 @@ type Verbose bool // The returned value is a boolean of type Verbose, which implements Info, Infoln // and Infof. These methods will write to the Info log if called. // Thus, one may write either -// if glog.V(2) { glog.Info("log this") } +// if klog.V(2) { klog.Info("log this") } // or -// glog.V(2).Info("log this") +// klog.V(2).Info("log this") // The second form is shorter but the first is cheaper if logging is off because it does // not evaluate its arguments. // @@ -1170,7 +1198,7 @@ func InfoDepth(depth int, args ...interface{}) { } // Infoln logs to the INFO log. -// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. +// Arguments are handled in the manner of fmt.Println; a newline is always appended. func Infoln(args ...interface{}) { logging.println(infoLog, args...) } @@ -1194,7 +1222,7 @@ func WarningDepth(depth int, args ...interface{}) { } // Warningln logs to the WARNING and INFO logs. -// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. +// Arguments are handled in the manner of fmt.Println; a newline is always appended. func Warningln(args ...interface{}) { logging.println(warningLog, args...) } @@ -1218,7 +1246,7 @@ func ErrorDepth(depth int, args ...interface{}) { } // Errorln logs to the ERROR, WARNING, and INFO logs. -// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. +// Arguments are handled in the manner of fmt.Println; a newline is always appended. func Errorln(args ...interface{}) { logging.println(errorLog, args...) } @@ -1244,7 +1272,7 @@ func FatalDepth(depth int, args ...interface{}) { // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). -// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. +// Arguments are handled in the manner of fmt.Println; a newline is always appended. func Fatalln(args ...interface{}) { logging.println(fatalLog, args...) } diff --git a/vendor/modules.txt b/vendor/modules.txt index ec70d07a9..aad1e2fef 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -219,8 +219,6 @@ github.com/gogo/protobuf/sortkeys github.com/gogo/protobuf/gogoproto github.com/gogo/protobuf/protoc-gen-gogo/descriptor github.com/gogo/protobuf/types -# github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b -github.com/golang/glog # github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 github.com/golang/groupcache/lru # github.com/golang/mock v1.3.1 @@ -316,10 +314,10 @@ github.com/konsorten/go-windows-terminal-sequences # github.com/kubeedge/beehive v0.0.0-20190627084409-06e0cfa222f7 github.com/kubeedge/beehive/pkg/core github.com/kubeedge/beehive/pkg/common/config -github.com/kubeedge/beehive/pkg/common/log github.com/kubeedge/beehive/pkg/core/context github.com/kubeedge/beehive/pkg/core/model github.com/kubeedge/beehive/pkg/common/util +github.com/kubeedge/beehive/pkg/common/log # github.com/kubeedge/viaduct v0.0.0-20190416034651-df4e595b4e12 github.com/kubeedge/viaduct/pkg/conn github.com/kubeedge/viaduct/pkg/mux @@ -918,7 +916,7 @@ k8s.io/cri-api/pkg/apis/runtime/v1alpha2 # k8s.io/csi-translation-lib v0.0.0 => k8s.io/csi-translation-lib v0.0.0-20190718190424-bef8d46b95de k8s.io/csi-translation-lib/plugins k8s.io/csi-translation-lib -# k8s.io/klog v0.3.3 => k8s.io/klog v0.3.3 +# k8s.io/klog v0.3.3 => k8s.io/klog v0.4.0 k8s.io/klog # k8s.io/kube-openapi v0.0.0-20190718094010-3cf2ea392886 k8s.io/kube-openapi/pkg/util/proto |
