-
Notifications
You must be signed in to change notification settings - Fork 0
/
TelemetryEventClient.go
491 lines (436 loc) · 16.9 KB
/
TelemetryEventClient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package telemetry
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/devtron-labs/template-cron-job/api/bean"
"github.com/devtron-labs/template-cron-job/internal/sql/repository"
util2 "github.com/devtron-labs/template-cron-job/internal/util"
"github.com/devtron-labs/template-cron-job/pkg/attributes"
"github.com/devtron-labs/template-cron-job/pkg/cluster"
"github.com/devtron-labs/template-cron-job/pkg/sso"
"github.com/devtron-labs/template-cron-job/pkg/user"
util3 "github.com/devtron-labs/template-cron-job/pkg/util"
"github.com/devtron-labs/template-cron-job/util"
"github.com/go-pg/pg"
"github.com/patrickmn/go-cache"
"github.com/posthog/posthog-go"
"github.com/robfig/cron/v3"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/api/core/v1"
v12 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/version"
"net/http"
"time"
)
type TelemetryEventClientImpl struct {
cron *cron.Cron
logger *zap.SugaredLogger
client *http.Client
clusterService cluster.ClusterService
K8sUtil *util2.K8sUtil
aCDAuthConfig *util3.ACDAuthConfig
userService user.UserService
attributeRepo repository.AttributesRepository
ssoLoginService sso.SSOLoginService
PosthogClient *PosthogClient
}
type TelemetryEventClient interface {
GetTelemetryMetaInfo() (*TelemetryMetaInfo, error)
SendTelemetryInstallEventEA() (*TelemetryEventType, error)
SendTelemetryDashboardAccessEvent() error
SendTelemetryDashboardLoggedInEvent() error
}
func NewTelemetryEventClientImpl(logger *zap.SugaredLogger, client *http.Client, clusterService cluster.ClusterService,
K8sUtil *util2.K8sUtil, aCDAuthConfig *util3.ACDAuthConfig, userService user.UserService,
attributeRepo repository.AttributesRepository, ssoLoginService sso.SSOLoginService,
PosthogClient *PosthogClient) (*TelemetryEventClientImpl, error) {
watcher := &TelemetryEventClientImpl{
logger: logger,
client: client, clusterService: clusterService,
K8sUtil: K8sUtil, aCDAuthConfig: aCDAuthConfig,
userService: userService, attributeRepo: attributeRepo,
ssoLoginService: ssoLoginService,
PosthogClient: PosthogClient,
}
return watcher, nil
}
func (impl *TelemetryEventClientImpl) StopCron() {
}
type TelemetryEventEA struct {
UCID string `json:"ucid"` //unique client id
Timestamp time.Time `json:"timestamp"`
EventMessage string `json:"eventMessage,omitempty"`
EventType TelemetryEventType `json:"eventType"`
//Summary *SummaryEA `json:"summary,omitempty"`
ServerVersion string `json:"serverVersion,omitempty"`
UserCount int `json:"userCount,omitempty"`
ClusterCount int `json:"clusterCount,omitempty"`
HostURL bool `json:"hostURL,omitempty"`
SSOLogin bool `json:"ssoLogin,omitempty"`
DevtronVersion string `json:"devtronVersion,omitempty"`
DevtronMode string `json:"devtronMode,omitempty"`
}
const DevtronUniqueClientIdConfigMap = "template-cron-job-ucid"
const DevtronUniqueClientIdConfigMapKey = "UCID"
const InstallEventKey = "installEvent"
const UIEventKey = "uiEventKey"
type TelemetryEventType string
const (
Heartbeat TelemetryEventType = "Heartbeat"
InstallationStart TelemetryEventType = "InstallationStart"
InstallationInProgress TelemetryEventType = "InstallationInProgress"
InstallationInterrupt TelemetryEventType = "InstallationInterrupt"
InstallationSuccess TelemetryEventType = "InstallationSuccess"
InstallationFailure TelemetryEventType = "InstallationFailure"
UpgradeStart TelemetryEventType = "UpgradeStart"
UpgradeInProgress TelemetryEventType = "UpgradeInProgress"
UpgradeInterrupt TelemetryEventType = "UpgradeInterrupt"
UpgradeSuccess TelemetryEventType = "UpgradeSuccess"
UpgradeFailure TelemetryEventType = "UpgradeFailure"
Summary TelemetryEventType = "Summary"
InstallationApplicationError TelemetryEventType = "InstallationApplicationError"
DashboardAccessed TelemetryEventType = "DashboardAccessed"
DashboardLoggedIn TelemetryEventType = "DashboardLoggedIn"
)
func (impl *TelemetryEventClientImpl) SummaryDetailsForTelemetry() (cluster []cluster.ClusterBean, user []bean.UserInfo, k8sServerVersion *version.Info, hostURL bool, ssoSetup bool) {
discoveryClient, err := impl.K8sUtil.GetK8sDiscoveryClientInCluster()
if err != nil {
impl.logger.Errorw("exception caught inside telemetry summary event", "err", err)
return
}
k8sServerVersion, err = discoveryClient.ServerVersion()
if err != nil {
impl.logger.Errorw("exception caught inside telemetry summary event", "err", err)
return
}
users, err := impl.userService.GetAll()
if err != nil && err != pg.ErrNoRows {
impl.logger.Errorw("exception caught inside telemetry summery event", "err", err)
return
}
clusters, err := impl.clusterService.FindAllActive()
if err != nil && err != pg.ErrNoRows {
impl.logger.Errorw("exception caught inside telemetry summary event", "err", err)
return
}
hostURL = false
attribute, err := impl.attributeRepo.FindByKey(attributes.HostUrlKey)
if err == nil && attribute.Id > 0 {
hostURL = true
}
ssoSetup = false
ssoConfig, err := impl.ssoLoginService.GetAll()
if err == nil && len(ssoConfig) > 0 {
ssoSetup = true
}
return clusters, users, k8sServerVersion, hostURL, ssoSetup
}
func (impl *TelemetryEventClientImpl) SummaryEventForTelemetryEA() {
ucid, err := impl.getUCID()
if err != nil {
impl.logger.Errorw("exception caught inside telemetry summary event", "err", err)
return
}
if IsOptOut {
impl.logger.Warnw("client is opt-out for telemetry, there will be no events capture", "ucid", ucid)
return
}
clusters, users, k8sServerVersion, hostURL, ssoSetup := impl.SummaryDetailsForTelemetry()
payload := &TelemetryEventEA{UCID: ucid, Timestamp: time.Now(), EventType: Summary, DevtronVersion: "v1"}
payload.ServerVersion = k8sServerVersion.String()
payload.DevtronMode = util.GetDevtronVersion().ServerMode
payload.HostURL = hostURL
payload.SSOLogin = ssoSetup
payload.UserCount = len(users)
payload.ClusterCount = len(clusters)
reqBody, err := json.Marshal(payload)
if err != nil {
impl.logger.Errorw("SummaryEventForTelemetry, payload marshal error", "error", err)
return
}
prop := make(map[string]interface{})
err = json.Unmarshal(reqBody, &prop)
if err != nil {
impl.logger.Errorw("SummaryEventForTelemetry, payload unmarshal error", "error", err)
return
}
err = impl.EnqueuePostHog(ucid, Summary, prop)
if err != nil {
impl.logger.Errorw("SummaryEventForTelemetry, failed to push event", "ucid", ucid, "error", err)
}
}
func (impl *TelemetryEventClientImpl) EnqueuePostHog(ucid string, eventType TelemetryEventType, prop map[string]interface{}) error {
if impl.PosthogClient.Client == nil {
impl.logger.Warn("no posthog client found, creating new")
client, err := impl.retryPosthogClient(PosthogApiKey, PosthogEndpoint)
if err == nil {
impl.PosthogClient.Client = client
}
}
if impl.PosthogClient.Client != nil {
err := impl.PosthogClient.Client.Enqueue(posthog.Capture{
DistinctId: ucid,
Event: string(eventType),
Properties: prop,
})
if err != nil {
impl.logger.Errorw("SummaryEventForTelemetry, failed to push event", "error", err)
return err
}
}
return nil
}
func (impl *TelemetryEventClientImpl) HeartbeatEventForTelemetry() {
ucid, err := impl.getUCID()
if err != nil {
impl.logger.Errorw("exception caught inside telemetry heartbeat event", "err", err)
return
}
if IsOptOut {
impl.logger.Warnw("client is opt-out for telemetry, there will be no events capture", "ucid", ucid)
return
}
discoveryClient, err := impl.K8sUtil.GetK8sDiscoveryClientInCluster()
if err != nil {
impl.logger.Errorw("exception caught inside telemetry heartbeat event", "err", err)
return
}
k8sServerVersion, err := discoveryClient.ServerVersion()
if err != nil {
impl.logger.Errorw("exception caught inside telemetry heartbeat event", "err", err)
return
}
payload := &TelemetryEventEA{UCID: ucid, Timestamp: time.Now(), EventType: Heartbeat, DevtronVersion: "v1"}
payload.ServerVersion = k8sServerVersion.String()
payload.DevtronMode = util.GetDevtronVersion().ServerMode
reqBody, err := json.Marshal(payload)
if err != nil {
impl.logger.Errorw("HeartbeatEventForTelemetry, payload marshal error", "error", err)
return
}
prop := make(map[string]interface{})
err = json.Unmarshal(reqBody, &prop)
if err != nil {
impl.logger.Errorw("HeartbeatEventForTelemetry, payload unmarshal error", "error", err)
return
}
err = impl.EnqueuePostHog(ucid, Heartbeat, prop)
if err != nil {
impl.logger.Warnw("HeartbeatEventForTelemetry, failed to push event", "error", err)
return
}
impl.logger.Debugw("HeartbeatEventForTelemetry success")
return
}
func (impl *TelemetryEventClientImpl) GetTelemetryMetaInfo() (*TelemetryMetaInfo, error) {
ucid, err := impl.getUCID()
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return nil, err
}
data := &TelemetryMetaInfo{
Url: PosthogEndpoint,
UCID: ucid,
ApiKey: PosthogEncodedApiKey,
}
return data, err
}
func (impl *TelemetryEventClientImpl) SendTelemetryInstallEventEA() (*TelemetryEventType, error) {
ucid, err := impl.getUCID()
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return nil, err
}
client, err := impl.K8sUtil.GetClientForInCluster()
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return nil, err
}
payload := &TelemetryEventEA{UCID: ucid, Timestamp: time.Now(), EventType: InstallationSuccess, DevtronVersion: "v1"}
payload.DevtronMode = util.GetDevtronVersion().ServerMode
reqBody, err := json.Marshal(payload)
if err != nil {
impl.logger.Errorw("Installation EventForTelemetry EA Mode, payload marshal error", "error", err)
return nil, nil
}
prop := make(map[string]interface{})
err = json.Unmarshal(reqBody, &prop)
if err != nil {
impl.logger.Errorw("Installation EventForTelemetry EA Mode, payload unmarshal error", "error", err)
return nil, nil
}
cm, err := impl.K8sUtil.GetConfigMap(impl.aCDAuthConfig.ACDConfigMapNamespace, DevtronUniqueClientIdConfigMap, client)
datamap := cm.Data
installEventValue, installEventKeyExists := datamap[InstallEventKey]
if installEventKeyExists == false || installEventValue == "1" {
err = impl.EnqueuePostHog(ucid, InstallationSuccess, prop)
if err == nil {
datamap[InstallEventKey] = "2"
cm.Data = datamap
_, err = impl.K8sUtil.UpdateConfigMap(impl.aCDAuthConfig.ACDConfigMapNamespace, cm, client)
if err != nil {
impl.logger.Warnw("config map update failed for install event", "err", err)
} else {
impl.logger.Debugw("config map apply succeeded for install event")
}
}
}
return nil, nil
}
func (impl *TelemetryEventClientImpl) SendTelemetryDashboardAccessEvent() error {
ucid, err := impl.getUCID()
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return err
}
client, err := impl.K8sUtil.GetClientForInCluster()
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return err
}
payload := &TelemetryEventEA{UCID: ucid, Timestamp: time.Now(), EventType: DashboardAccessed, DevtronVersion: "v1"}
payload.DevtronMode = util.GetDevtronVersion().ServerMode
reqBody, err := json.Marshal(payload)
if err != nil {
impl.logger.Errorw("DashboardAccessed EventForTelemetry, payload marshal error", "error", err)
return err
}
prop := make(map[string]interface{})
err = json.Unmarshal(reqBody, &prop)
if err != nil {
impl.logger.Errorw("DashboardAccessed EventForTelemetry, payload unmarshal error", "error", err)
return err
}
cm, err := impl.K8sUtil.GetConfigMap(impl.aCDAuthConfig.ACDConfigMapNamespace, DevtronUniqueClientIdConfigMap, client)
datamap := cm.Data
accessEventValue, installEventKeyExists := datamap[UIEventKey]
if installEventKeyExists == false || accessEventValue <= "1" {
err = impl.EnqueuePostHog(ucid, DashboardAccessed, prop)
if err == nil {
datamap[UIEventKey] = "2"
cm.Data = datamap
_, err = impl.K8sUtil.UpdateConfigMap(impl.aCDAuthConfig.ACDConfigMapNamespace, cm, client)
if err != nil {
impl.logger.Warnw("config map update failed for install event", "err", err)
} else {
impl.logger.Debugw("config map apply succeeded for install event")
}
}
}
return nil
}
func (impl *TelemetryEventClientImpl) SendTelemetryDashboardLoggedInEvent() error {
ucid, err := impl.getUCID()
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return err
}
client, err := impl.K8sUtil.GetClientForInCluster()
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return err
}
payload := &TelemetryEventEA{UCID: ucid, Timestamp: time.Now(), EventType: DashboardLoggedIn, DevtronVersion: "v1"}
payload.DevtronMode = util.GetDevtronVersion().ServerMode
reqBody, err := json.Marshal(payload)
if err != nil {
impl.logger.Errorw("DashboardLoggedIn EventForTelemetry, payload marshal error", "error", err)
return err
}
prop := make(map[string]interface{})
err = json.Unmarshal(reqBody, &prop)
if err != nil {
impl.logger.Errorw("DashboardLoggedIn EventForTelemetry, payload unmarshal error", "error", err)
return err
}
cm, err := impl.K8sUtil.GetConfigMap(impl.aCDAuthConfig.ACDConfigMapNamespace, DevtronUniqueClientIdConfigMap, client)
datamap := cm.Data
accessEventValue, installEventKeyExists := datamap[UIEventKey]
if installEventKeyExists == false || accessEventValue != "3" {
err = impl.EnqueuePostHog(ucid, DashboardLoggedIn, prop)
if err == nil {
datamap[UIEventKey] = "3"
cm.Data = datamap
_, err = impl.K8sUtil.UpdateConfigMap(impl.aCDAuthConfig.ACDConfigMapNamespace, cm, client)
if err != nil {
impl.logger.Warnw("config map update failed for install event", "err", err)
} else {
impl.logger.Debugw("config map apply succeeded for install event")
}
}
}
return nil
}
type TelemetryMetaInfo struct {
Url string `json:"url,omitempty"`
UCID string `json:"ucid,omitempty"`
ApiKey string `json:"apiKey,omitempty"`
}
func (impl *TelemetryEventClientImpl) getUCID() (string, error) {
ucid, found := impl.PosthogClient.cache.Get(DevtronUniqueClientIdConfigMapKey)
if found {
return ucid.(string), nil
} else {
client, err := impl.K8sUtil.GetClientForInCluster()
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return "", err
}
cm, err := impl.K8sUtil.GetConfigMap(impl.aCDAuthConfig.ACDConfigMapNamespace, DevtronUniqueClientIdConfigMap, client)
if errStatus, ok := status.FromError(err); !ok || errStatus.Code() == codes.NotFound || errStatus.Code() == codes.Unknown {
// if not found, create new cm
cm = &v1.ConfigMap{ObjectMeta: v12.ObjectMeta{Name: DevtronUniqueClientIdConfigMap}}
data := map[string]string{}
data[DevtronUniqueClientIdConfigMapKey] = util.Generate(16) // generate unique random number
data[InstallEventKey] = "1" // used in operator to detect event is install or upgrade
data[UIEventKey] = "1"
cm.Data = data
_, err = impl.K8sUtil.CreateConfigMap(impl.aCDAuthConfig.ACDConfigMapNamespace, cm, client)
if err != nil {
impl.logger.Errorw("exception while getting unique client id", "error", err)
return "", err
}
}
dataMap := cm.Data
ucid = dataMap[DevtronUniqueClientIdConfigMapKey]
impl.PosthogClient.cache.Set(DevtronUniqueClientIdConfigMapKey, ucid, cache.DefaultExpiration)
if cm == nil {
impl.logger.Errorw("configmap not found while getting unique client id", "cm", cm)
return ucid.(string), err
}
flag, err := impl.checkForOptOut(ucid.(string))
if err != nil {
impl.logger.Errorw("error sending event to posthog, failed check for opt-out", "err", err)
return "", err
}
IsOptOut = flag
}
return ucid.(string), nil
}
func (impl *TelemetryEventClientImpl) checkForOptOut(UCID string) (bool, error) {
decodedUrl, err := base64.StdEncoding.DecodeString(TelemetryOptOutApiBaseUrl)
if err != nil {
impl.logger.Errorw("check opt-out list failed, decode error", "err", err)
return false, err
}
encodedUrl := string(decodedUrl)
url := fmt.Sprintf("%s/%s", encodedUrl, UCID)
response, err := util.HttpRequest(url)
if err != nil {
impl.logger.Errorw("check opt-out list failed, rest api error", "err", err)
return false, err
}
flag := response["result"].(bool)
return flag, err
}
func (impl *TelemetryEventClientImpl) retryPosthogClient(PosthogApiKey string, PosthogEndpoint string) (posthog.Client, error) {
client, err := posthog.NewWithConfig(PosthogApiKey, posthog.Config{Endpoint: PosthogEndpoint})
//defer client.Close()
if err != nil {
impl.logger.Errorw("exception caught while creating posthog client", "err", err)
}
return client, err
}