diff --git a/go.mod b/go.mod index dcf6670ce..cc9768b97 100644 --- a/go.mod +++ b/go.mod @@ -4,14 +4,13 @@ go 1.19 require ( github.com/container-storage-interface/spec v1.8.0 - github.com/docker/go-units v0.5.0 github.com/google/uuid v1.3.1 - github.com/jpillora/go-ogle-analytics v0.0.0-20161213085824-14b04e0594ef github.com/kubernetes-csi/csi-lib-iscsi v0.0.0-20200118015005-959f12c91ca8 github.com/kubernetes-csi/csi-lib-utils v0.14.0 github.com/onsi/ginkgo v1.16.4 github.com/onsi/gomega v1.27.7 github.com/openebs/api/v3 v3.0.2 + github.com/openebs/google-analytics-4 v0.1.0 github.com/pkg/errors v0.9.1 github.com/sirupsen/logrus v1.9.0 github.com/spf13/cobra v1.7.0 @@ -24,7 +23,7 @@ require ( k8s.io/client-go v0.27.2 k8s.io/code-generator v0.27.2 k8s.io/kubernetes v0.0.0-00010101000000-000000000000 - k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 + k8s.io/utils v0.0.0-20230505201702-9f6742963106 ) require ( @@ -32,6 +31,7 @@ require ( github.com/blang/semver/v4 v4.0.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/docker/go-units v0.5.0 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-logr/logr v1.3.0 // indirect @@ -45,7 +45,7 @@ require ( github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/google/gofuzz v1.2.0 // indirect - github.com/imdario/mergo v0.3.8 // indirect + github.com/imdario/mergo v0.3.15 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect @@ -57,6 +57,7 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/nxadm/tail v1.4.8 // indirect github.com/opencontainers/selinux v1.10.0 // indirect + github.com/openebs/lib-csi v0.8.2 // indirect github.com/prometheus/client_golang v1.16.0 // indirect github.com/prometheus/client_model v0.4.0 // indirect github.com/prometheus/common v0.44.0 // indirect diff --git a/go.sum b/go.sum index 7021a4ab6..0288b14a6 100644 --- a/go.sum +++ b/go.sum @@ -820,14 +820,12 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.8 h1:CGgOkSJeqMRmt0D9XLWExdT4m4F1vd3FV3VPt+0VxkQ= -github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.15 h1:M8XP7IuFNsqUx6VPK2P9OSmsYsI/YFaGil0uD21V3dM= +github.com/imdario/mergo v0.3.15/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/jpillora/go-ogle-analytics v0.0.0-20161213085824-14b04e0594ef h1:jLpa0vamfyIGeIJ/CfUJEWoKriw4ODeOgF1XxDvgMZ4= -github.com/jpillora/go-ogle-analytics v0.0.0-20161213085824-14b04e0594ef/go.mod h1:PlwhC7q1VSK73InDzdDatVetQrTsQHIbOvcJAZzitY0= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= @@ -891,6 +889,10 @@ github.com/opencontainers/selinux v1.10.0 h1:rAiKF8hTcgLI3w0DHm6i0ylVVcOrlgR1kK9 github.com/opencontainers/selinux v1.10.0/go.mod h1:2i0OySw99QjzBBQByd1Gr9gSjvuho1lHsJxIJ3gGbJI= github.com/openebs/api/v3 v3.0.2 h1:pHSMJATl9ETdw0AZ75e5UcgeN/ERmGZbdU9gdzWfMu0= github.com/openebs/api/v3 v3.0.2/go.mod h1:cED/PzY/8Jr9pWVl90qHnuQk2hSG9NLCawrNsqEDWkA= +github.com/openebs/google-analytics-4 v0.1.0 h1:6aUDbQoh1ezb+NU/MkapFKffogW4QK3WYt8g2UmENe8= +github.com/openebs/google-analytics-4 v0.1.0/go.mod h1:3DkQfGCo79pZhL76Xtg0/R7LNLMttW6Bm/uP0yiZQHU= +github.com/openebs/lib-csi v0.8.2 h1:HmoiZX3VXFPglwqnRPnRus7K58ixDWBa19OpPZGk2Ws= +github.com/openebs/lib-csi v0.8.2/go.mod h1:4yc0Q1thH+oU80z73zGELfrOw2yeLdLNIRmcrxBxsBc= github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2dXMnm1mY= github.com/phpdave11/gofpdi v1.0.12/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= github.com/phpdave11/gofpdi v1.0.13/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= @@ -1665,8 +1667,8 @@ k8s.io/kubernetes v1.27.2 h1:g4v9oY6u7vBUDEuq4FvC50Bbw2K7GZuvM00IIESWVf4= k8s.io/kubernetes v1.27.2/go.mod h1:U8ZXeKBAPxeb4J4/HOaxjw1A9K6WfSH+fY2SS7CR6IM= k8s.io/mount-utils v0.27.2 h1:fEqtBdAv88xpoPr3nR0MgYs6P+2PjXyUTwd4NmqSBjY= k8s.io/mount-utils v0.27.2/go.mod h1:vmcjYdi2Vg1VTWY7KkhvwJVY6WDHxb/QQhiQKkR8iNs= -k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 h1:qY1Ad8PODbnymg2pRbkyMT/ylpTrCM8P2RJ0yroCyIk= -k8s.io/utils v0.0.0-20230406110748-d93618cff8a2/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +k8s.io/utils v0.0.0-20230505201702-9f6742963106 h1:EObNQ3TW2D+WptiYXlApGNLVy0zm/JIBVY9i+M4wpAU= +k8s.io/utils v0.0.0-20230505201702-9f6742963106/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= modernc.org/cc/v3 v3.36.0/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI= diff --git a/pkg/driver/controller.go b/pkg/driver/controller.go index 469ff6266..e598b0024 100644 --- a/pkg/driver/controller.go +++ b/pkg/driver/controller.go @@ -26,8 +26,8 @@ import ( "github.com/openebs/cstor-csi/pkg/env" k8snode "github.com/openebs/cstor-csi/pkg/kubernetes/node" csipayload "github.com/openebs/cstor-csi/pkg/payload" - analytics "github.com/openebs/cstor-csi/pkg/usage" utils "github.com/openebs/cstor-csi/pkg/utils" + analytics "github.com/openebs/google-analytics-4/usage" errors "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/net/context" @@ -37,6 +37,17 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) +const ( + // Ping event is sent periodically + Ping string = "ping" + // DefaultCASType Event application name constant for volume event + DefaultCASType string = "cstor" + // Replica Event replication + Replica string = "replica:" + // DefaultReplicaCount holds the replica count string + DefaultReplicaCount string = "replica:3" +) + // controller is the server implementation // for CSI Controller type controller struct { @@ -354,12 +365,11 @@ func getAccessibilityRequirements(requirement *csi.TopologyRequirement) (string, // sendEventOrIgnore sends anonymous cstor provision/delete events func sendEventOrIgnore(pvcName, pvName, capacity, replicaCount, stgType, method string) { if env.Truthy(env.OpenEBSEnableAnalytics) { - analytics.New().Build().ApplicationBuilder(). - SetVolumeType(stgType, method). - SetDocumentTitle(pvName). - SetCampaignName(pvcName). + analytics.New().CommonBuild(GetVolumeType(stgType, method)).ApplicationBuilder(). + SetVolumeName(pvName). + SetVolumeClaimName(pvcName). SetLabel(analytics.EventLabelCapacity). - SetReplicaCount(replicaCount, method). + SetAction(GetReplicaCount(stgType, method)). SetCategory(method). SetVolumeCapacity(capacity).Send() } @@ -408,3 +418,26 @@ func (cs *controller) ControllerGetVolume(ctx context.Context, req *csi.Controll }, }, nil } + +// SetVolumeType Wrapper for setting the default storage-engine for volume-provision event +func GetVolumeType(volType, method string) string { + if method == analytics.VolumeProvision && volType == "" { + // Set the default storage engine, if not specified in the request + return DefaultCASType + } else { + return volType + } +} + +// GetReplicaCount Wrapper for setting replica count for volume events +func GetReplicaCount(count, method string) string { + if method == analytics.VolumeProvision && count == "" { + // Case: When volume-provision the replica count isn't specified + // it is set to three by default by the cstor-operators + return DefaultReplicaCount + } else { + // Catch all case for volume-deprovision event and + // volume-provision event with an overridden replica-count + return Replica + count + } +} diff --git a/pkg/driver/service.go b/pkg/driver/service.go index 34f55d1de..893405a35 100644 --- a/pkg/driver/service.go +++ b/pkg/driver/service.go @@ -22,8 +22,9 @@ import ( "github.com/container-storage-interface/spec/lib/go/csi" config "github.com/openebs/cstor-csi/pkg/config" "github.com/openebs/cstor-csi/pkg/env" - analytics "github.com/openebs/cstor-csi/pkg/usage" utils "github.com/openebs/cstor-csi/pkg/utils" + "github.com/openebs/cstor-csi/pkg/version" + analytics "github.com/openebs/google-analytics-4/usage" "github.com/sirupsen/logrus" ) @@ -124,8 +125,9 @@ func (d *CSIDriver) Run() error { // Send Event only after starting controller. // ControllerServer(cs) will be non-empty only if driver is running as controller service if d.cs != nil && env.Truthy(env.OpenEBSEnableAnalytics) { - analytics.New().Build().InstallBuilder(true).Send() - go analytics.PingCheck() + analytics.RegisterVersionGetter(version.GetVersionDetails) + analytics.New().CommonBuild(DefaultCASType).InstallBuilder(true).Send() + go analytics.PingCheck(DefaultCASType, Ping) } s.Wait() diff --git a/pkg/usage/const.go b/pkg/usage/const.go deleted file mode 100644 index 94eb864d6..000000000 --- a/pkg/usage/const.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2020 The OpenEBS Authors. - -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 usage - -const ( - // GAclientID is the unique code of OpenEBS project in Google Analytics - GAclientID string = "UA-127388617-1" - - // supported events categories - - // InstallEvent event is sent on pod starts - InstallEvent string = "install" - // Ping event is sent periodically - Ping string = "cstor-csi-ping" - // VolumeProvision event is sent when a volume is created - VolumeProvision string = "volume-provision" - // VolumeDeprovision event is sent when a volume is deleted - VolumeDeprovision string = "volume-deprovision" - // AppName the application name - AppName string = "OpenEBS" - - // RunningStatus status is running - RunningStatus string = "running" - // EventLabelNode holds the string label "nodes" - EventLabelNode string = "nodes" - // EventLabelCapacity holds the string label "capacity" - EventLabelCapacity string = "capacity" - - // Replica Event replication - Replica string = "replica:" - // DefaultReplicaCount holds the replica count string - DefaultReplicaCount string = "replica:3" - - // DefaultCASType Event application name constant for volume event - DefaultCASType string = "cstor" -) diff --git a/pkg/usage/googleanalytics.go b/pkg/usage/googleanalytics.go deleted file mode 100644 index 80da91562..000000000 --- a/pkg/usage/googleanalytics.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2020 The OpenEBS Authors. - -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 usage - -import ( - analytics "github.com/jpillora/go-ogle-analytics" - "github.com/sirupsen/logrus" -) - -// Send sends a single usage metric to Google Analytics with some -// compulsory fields defined in Google Analytics API -// bindings(jpillora/go-ogle-analytics) -func (u *Usage) Send() { - // Instantiate a Gclient with the tracking ID - go func() { - // Un-wrap the gaClient struct back here - gaClient, err := analytics.NewClient(u.Gclient.trackID) - if err != nil { - return - } - gaClient.ClientID(u.clientID). - CampaignSource(u.campaignSource). - CampaignContent(u.clientID). - CampaignName(u.campaignName). - ApplicationID(u.appID). - ApplicationVersion(u.appVersion). - DataSource(u.dataSource). - ApplicationName(u.appName). - ApplicationInstallerID(u.appInstallerID). - DocumentTitle(u.documentTitle) - // Un-wrap the Event struct back here - event := analytics.NewEvent(u.category, u.action) - event.Label(u.label) - event.Value(u.value) - if err := gaClient.Send(event); err != nil { - logrus.Errorf(err.Error()) - return - } - }() -} diff --git a/pkg/usage/ping.go b/pkg/usage/ping.go deleted file mode 100644 index 0895d5ddf..000000000 --- a/pkg/usage/ping.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2020 The OpenEBS Authors. - -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 usage - -import ( - "fmt" - "time" - - "github.com/openebs/cstor-csi/pkg/env" -) - -const ( - // defaultPingPeriod sets the default ping heartbeat interval - defaultPingPeriod time.Duration = 24 * time.Hour - // minimumPingPeriod sets the minimum possible configurable - // heartbeat period, if a value lower than this will be set, the - // defaultPingPeriod will be used - minimumPingPeriod time.Duration = 1 * time.Hour -) - -// PingCheck sends ping events to Google Analytics -func PingCheck() { - // Create a new usage field - u := New() - duration := getPingPeriod() - ticker := time.NewTicker(duration) - for range ticker.C { - u.Build(). - InstallBuilder(true). - SetCategory(Ping). - Send() - } -} - -// getPingPeriod sets the duration of health events, defaults to 24 -func getPingPeriod() time.Duration { - value := env.GetOrDefault(env.OpenEBSPingPeriod, fmt.Sprint(defaultPingPeriod)) - duration, _ := time.ParseDuration(value) - // Sanitychecks for setting time duration of health events - // This way, we are checking for negative and zero time duration and we - // also have a minimum possible configurable time duration between health events - if duration < minimumPingPeriod { - // Avoid corner case when the ENV value is undesirable - return time.Duration(defaultPingPeriod) - } - - return time.Duration(duration) - -} diff --git a/pkg/usage/ping_test.go b/pkg/usage/ping_test.go deleted file mode 100644 index 0a0d54dde..000000000 --- a/pkg/usage/ping_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 The OpenEBS Authors -// -// 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 usage - -import ( - "os" - "testing" - "time" - - "github.com/openebs/cstor-csi/pkg/env" -) - -func TestGetPingPeriod(t *testing.T) { - beforeFunc := func(value string) { - if err := os.Setenv(string(env.OpenEBSPingPeriod), value); err != nil { - t.Logf("Unable to set environment variable") - } - } - afterFunc := func() { - if err := os.Unsetenv(string(env.OpenEBSPingPeriod)); err != nil { - t.Logf("Unable to unset environment variable") - } - } - testSuite := map[string]struct { - OpenEBSPingPeriodValue string - ExpectedPeriodValue time.Duration - }{ - "24 seconds": {"24s", 86400000000000}, - "24 minutes": {"24m", 86400000000000}, - "24 hours": {"24h", 86400000000000}, - "Negative 24 hours": {"-24h", 86400000000000}, - "Random string input": {"Apache", 86400000000000}, - "Two hours": {"2h", 7200000000000}, - "Three hundred hours": {"300h", 1080000000000000}, - "Fifty two seconds": {"52000000000ns", 86400000000000}, - "Empty env value": {"", 86400000000000}, - } - for testKey, testData := range testSuite { - beforeFunc(testData.OpenEBSPingPeriodValue) - evaluatedValue := getPingPeriod() - if evaluatedValue != testData.ExpectedPeriodValue { - t.Fatalf("Tests failed for %s, expected=%d, got=%d", testKey, testData.ExpectedPeriodValue, evaluatedValue) - } - afterFunc() - } -} diff --git a/pkg/usage/size.go b/pkg/usage/size.go deleted file mode 100644 index c435d0d4f..000000000 --- a/pkg/usage/size.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright 2020 The OpenEBS Authors. - -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 usage - -import units "github.com/docker/go-units" - -// toGigaUnits converts a size from xB to bytes where x={k,m,g,t,p...} -// and return the number of Gigabytes as an integer -// 1 gigabyte=1000 megabyte -func toGigaUnits(size string) (int64, error) { - sizeInBytes, err := units.FromHumanSize(size) - return sizeInBytes / units.GB, err -} diff --git a/pkg/usage/size_test.go b/pkg/usage/size_test.go deleted file mode 100644 index 23e85634a..000000000 --- a/pkg/usage/size_test.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2020 The OpenEBS Authors. - -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 usage - -import "testing" - -func TestToGigaUnits(t *testing.T) { - tests := map[string]struct { - stringSize string - expectedGsize int64 - positiveTest bool - }{ - "One Hundred Twenty Three thousand Four Hundred Fifty Six Teribytes": { - "123456 TiB", - 123456000, - true, - }, - "One Gibibyte": { - "1 GiB", - 1, - true, - }, - "One Megabyte": { - "1 MB", - 0, // One cannot express <1GB in integer - true, - }, - "One Megabyte negative-case": { - "1 MB", - 1, - false, - // 1 MB isn't 1 GB - }, - "One hundred four point five gigabyte": { - "104.5 GB", - 104, - true, - }, - } - - for testKey, testSuite := range tests { - gotValue, err := toGigaUnits(testSuite.stringSize) - if (gotValue != testSuite.expectedGsize || err != nil) && testSuite.positiveTest { - t.Fatalf("Tests failed for %s, expected=%d, got=%d", testKey, testSuite.expectedGsize, gotValue) - } - } -} diff --git a/pkg/usage/usage.go b/pkg/usage/usage.go deleted file mode 100644 index fbd6cf82d..000000000 --- a/pkg/usage/usage.go +++ /dev/null @@ -1,265 +0,0 @@ -/* -Copyright 2020 The OpenEBS Authors. - -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 usage - -import ( - node "github.com/openebs/cstor-csi/pkg/kubernetes/node" -) - -// Usage struct represents all information about a usage metric sent to -// Google Analytics with respect to the application -type Usage struct { - // Embedded Event struct as we are currently only sending hits of type - // 'event' - Event - - // https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#an - // use-case: cstor volume, m-apiserver/cstor-opertors application - // Embedded field for application - Application - - // Embedded Gclient struct - Gclient -} - -// Event is a represents usage of OpenEBS -// Event contains all the query param fields when hits is of type='event' -// Ref: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ec -type Event struct { - // (Required) Event Category, ec - category string - // (Required) Event Action, ea - action string - // (Optional) Event Label, el - label string - // (Optional) Event vallue, ev - // Non negative - value int64 -} - -// NewEvent returns an Event struct with eventCategory, eventAction, -// eventLabel, eventValue fields -func (u *Usage) NewEvent(c, a, l string, v int64) *Usage { - u.category = c - u.action = a - u.label = l - u.value = v - return u -} - -// Application struct holds details about the Application -type Application struct { - // eg. project version - appVersion string - - // eg. kubernetes version - appInstallerID string - - // Name of the application, usage(OpenEBS/NDM) - appID string - - // eg. usage(os-type/architecture) of system or volume's CASType - appName string -} - -// Gclient struct represents a Google Analytics hit -type Gclient struct { - // constant tracking-id used to send a hit - trackID string - - // anonymous client-id - clientID string - - // anonymous campaign source - campaignSource string - - // anonymous campaign name - campaignName string - - // https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ds - // (usecase) node-detail - dataSource string - - // Document-title property in Google Analytics - // https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#dt - // use-case: uuid of the volume objects or a uuid to anonymously tell objects apart - documentTitle string -} - -// New returns an instance of Usage -func New() *Usage { - return &Usage{} -} - -// SetDataSource : usage(os-type, kernel) -func (u *Usage) SetDataSource(dataSource string) *Usage { - u.dataSource = dataSource - return u -} - -// SetTrackingID Sets the GA-code for the project -func (u *Usage) SetTrackingID(track string) *Usage { - u.trackID = track - return u -} - -// SetCampaignSource : source of openebs installater like: -// helm or operator etc. This will have to be configured -// via ENV variable OPENEBS_IO_INSTALLER_TYPE -func (u *Usage) SetCampaignSource(campaignSrc string) *Usage { - u.campaignSource = campaignSrc - return u -} - -// SetDocumentTitle : usecase(anonymous-id) -func (u *Usage) SetDocumentTitle(documentTitle string) *Usage { - u.documentTitle = documentTitle - return u -} - -// SetApplicationName : usecase(os-type/arch, volume CASType) -func (u *Usage) SetApplicationName(appName string) *Usage { - u.appName = appName - return u -} - -// SetCampaignName : set the name of the PVC or will be empty. -func (u *Usage) SetCampaignName(campaignName string) *Usage { - u.campaignName = campaignName - return u -} - -// SetApplicationID : usecase(OpenEBS/NDM) -func (u *Usage) SetApplicationID(appID string) *Usage { - u.appID = appID - return u -} - -// SetApplicationVersion : usecase(project-version) -func (u *Usage) SetApplicationVersion(appVersion string) *Usage { - u.appVersion = appVersion - return u -} - -// SetApplicationInstallerID : usecase(k8s-version) -func (u *Usage) SetApplicationInstallerID(appInstallerID string) *Usage { - u.appInstallerID = appInstallerID - return u -} - -// SetClientID sets the anonymous user id -func (u *Usage) SetClientID(userID string) *Usage { - u.clientID = userID - return u -} - -// SetCategory sets the category of an event -func (u *Usage) SetCategory(c string) *Usage { - u.category = c - return u -} - -// SetAction sets the action of an event -func (u *Usage) SetAction(a string) *Usage { - u.action = a - return u -} - -// SetLabel sets the label for an event -func (u *Usage) SetLabel(l string) *Usage { - u.label = l - return u -} - -// SetValue sets the value for an event's label -func (u *Usage) SetValue(v int64) *Usage { - u.value = v - return u -} - -// Build is a builder method for Usage struct -func (u *Usage) Build() *Usage { - // Default ApplicationID for openebs project is OpenEBS - v := NewVersion() - v.getVersion(false) - u.SetApplicationID(AppName). - SetTrackingID(GAclientID). - SetClientID(v.id). - SetCampaignSource(v.installerType) - // TODO: Add condition for version over-ride - // Case: CAS/Jiva version, etc - return u -} - -// ApplicationBuilder Application builder is used for adding k8s&openebs environment detail -// for non install events -func (u *Usage) ApplicationBuilder() *Usage { - v := NewVersion() - v.getVersion(false) - u.SetApplicationVersion(v.openebsVersion). - SetApplicationName(v.k8sArch). - SetApplicationInstallerID(v.k8sVersion). - SetDataSource(v.nodeType) - return u -} - -// SetVolumeCapacity sets the storage capacity of the volume for a volume event -func (u *Usage) SetVolumeCapacity(volCapG string) *Usage { - s, _ := toGigaUnits(volCapG) - u.SetValue(s) - return u -} - -// SetVolumeType Wrapper for setting the default storage-engine for volume-provision event -func (u *Usage) SetVolumeType(volType, method string) *Usage { - if method == VolumeProvision && volType == "" { - // Set the default storage engine, if not specified in the request - u.SetApplicationName(DefaultCASType) - } else { - u.SetApplicationName(volType) - } - return u -} - -// SetReplicaCount Wrapper for setting replica count for volume events -func (u *Usage) SetReplicaCount(count, method string) *Usage { - if method == VolumeProvision && count == "" { - // Case: When volume-provision the replica count isn't specified - // it is set to three by default by the cstor-operators - u.SetAction(DefaultReplicaCount) - } else { - // Catch all case for volume-deprovision event and - // volume-provision event with an overridden replica-count - u.SetAction(Replica + count) - } - return u -} - -// InstallBuilder is a concrete builder for install events -func (u *Usage) InstallBuilder(override bool) *Usage { - v := NewVersion() - clusterSize, _ := node.NumberOfNodes() - v.getVersion(override) - u.SetApplicationVersion(v.openebsVersion). - SetApplicationName(v.k8sArch). - SetApplicationInstallerID(v.k8sVersion). - SetDataSource(v.nodeType). - SetDocumentTitle(v.id). - SetApplicationID(AppName). - NewEvent(InstallEvent, RunningStatus, EventLabelNode, int64(clusterSize)) - return u -} diff --git a/pkg/usage/versionset.go b/pkg/usage/versionset.go deleted file mode 100644 index 6e6a61eb9..000000000 --- a/pkg/usage/versionset.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -Copyright 2020 The OpenEBS Authors. - -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 usage - -import ( - env "github.com/openebs/cstor-csi/pkg/env" - "github.com/openebs/cstor-csi/pkg/kubernetes/client" - ns "github.com/openebs/cstor-csi/pkg/kubernetes/namespace" - node "github.com/openebs/cstor-csi/pkg/kubernetes/node" - "github.com/openebs/cstor-csi/pkg/version" - "github.com/sirupsen/logrus" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -var ( - clusterUUID env.ENVKey = "OPENEBS_IO_USAGE_UUID" - clusterVersion env.ENVKey = "OPENEBS_IO_K8S_VERSION" - clusterArch env.ENVKey = "OPENEBS_IO_K8S_ARCH" - openEBSversion env.ENVKey = "OPENEBS_IO_VERSION_TAG" - nodeType env.ENVKey = "OPENEBS_IO_NODE_TYPE" - installerType env.ENVKey = "OPENEBS_IO_INSTALLER_TYPE" -) - -// VersionSet is a struct which stores (sort of) fixed information about a -// k8s environment -type VersionSet struct { - id string // OPENEBS_IO_USAGE_UUID - k8sVersion string // OPENEBS_IO_K8S_VERSION - k8sArch string // OPENEBS_IO_K8S_ARCH - openebsVersion string // OPENEBS_IO_VERSION_TAG - nodeType string // OPENEBS_IO_NODE_TYPE - installerType string // OPENEBS_IO_INSTALLER_TYPE -} - -// NewVersion returns a new versionSet struct -func NewVersion() *VersionSet { - return &VersionSet{} -} - -// fetchAndSetVersion consumes the Kubernetes API to get environment constants -// and returns a versionSet struct -func (v *VersionSet) fetchAndSetVersion() error { - var err error - v.id, err = getUUIDbyNS("default") - if err != nil { - return err - } - env.Set(clusterUUID, v.id) - - k8s, err := client.GetServerVersion() - if err != nil { - return err - } - // eg. linux/amd64 - v.k8sArch = k8s.Platform - v.k8sVersion = k8s.GitVersion - env.Set(clusterArch, v.k8sArch) - env.Set(clusterVersion, v.k8sVersion) - v.nodeType, err = node.GetOSAndKernelVersion() - env.Set(nodeType, v.nodeType) - if err != nil { - return err - } - v.openebsVersion = version.GetVersionDetails() - env.Set(openEBSversion, v.openebsVersion) - return nil -} - -// getVersion is a wrapper over fetchAndSetVersion -func (v *VersionSet) getVersion(override bool) error { - // If ENVs aren't set or the override is true, fetch the required - // values from the K8s APIserver - if _, present := env.Lookup(openEBSversion); !present || override { - if err := v.fetchAndSetVersion(); err != nil { - logrus.Error(err.Error()) - return err - } - } - // Fetch data from ENV - v.id = env.Get(clusterUUID) - v.k8sArch = env.Get(clusterArch) - v.k8sVersion = env.Get(clusterVersion) - v.nodeType = env.Get(nodeType) - v.openebsVersion = env.Get(openEBSversion) - v.installerType = env.Get(installerType) - return nil -} - -// getUUIDbyNS returns the metadata.object.uid of a namespace in Kubernetes -func getUUIDbyNS(namespace string) (string, error) { - NSstruct, err := ns.NewKubeClient().Get(namespace, metav1.GetOptions{}) - if err != nil { - return "", err - } - if NSstruct != nil { - return string(NSstruct.GetObjectMeta().GetUID()), nil - } - return "", nil -}