SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(telemetry): remove telemetry (#8326)
Vibhu Pandey250646a354bd
diff --git a/ee/query-service/app/server.go b/ee/query-service/app/server.goindex 29db0f58e6..7c4d1334a6 100644--- a/ee/query-service/app/server.go+++ b/ee/query-service/app/server.go@@ -10,7 +10,6 @@ import ("github.com/gorilla/handlers""github.com/SigNoz/signoz/ee/query-service/app/api"- "github.com/SigNoz/signoz/ee/query-service/constants""github.com/SigNoz/signoz/ee/query-service/integrations/gateway""github.com/SigNoz/signoz/ee/query-service/rules""github.com/SigNoz/signoz/ee/query-service/usage"@@ -39,7 +38,6 @@ import ("github.com/SigNoz/signoz/pkg/query-service/healthcheck"baseint "github.com/SigNoz/signoz/pkg/query-service/interfaces"baserules "github.com/SigNoz/signoz/pkg/query-service/rules"- "github.com/SigNoz/signoz/pkg/query-service/telemetry""github.com/SigNoz/signoz/pkg/query-service/utils""go.uber.org/zap")@@ -157,15 +155,6 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz, jwt *authtypes.JWT)return nil, err}- telemetry.GetInstance().SetReader(reader)- telemetry.GetInstance().SetSqlStore(signoz.SQLStore)- telemetry.GetInstance().SetSaasOperator(constants.SaasSegmentKey)- telemetry.GetInstance().SetSavedViewsInfoCallback(telemetry.GetSavedViewsInfo)- telemetry.GetInstance().SetAlertsInfoCallback(telemetry.GetAlertsInfo)- telemetry.GetInstance().SetGetUsersCallback(telemetry.GetUsers)- telemetry.GetInstance().SetUserCountCallback(telemetry.GetUserCount)- telemetry.GetInstance().SetDashboardsInfoCallback(telemetry.GetDashboardsInfo)-apiOpts := api.APIHandlerOptions{DataConnector: reader,RulesManager: rm,@@ -243,7 +232,6 @@ func (s *Server) createPrivateServer(apiHandler *api.APIHandler) (*http.Server,s.config.APIServer.Timeout.Default,s.config.APIServer.Timeout.Max,).Wrap)- r.Use(middleware.NewAnalytics().Wrap)r.Use(middleware.NewLogging(s.signoz.Instrumentation.Logger(), s.config.APIServer.Logging.ExcludedRoutes).Wrap)apiHandler.RegisterPrivateRoutes(r)@@ -275,7 +263,6 @@ func (s *Server) createPublicServer(apiHandler *api.APIHandler, web web.Web) (*hs.config.APIServer.Timeout.Default,s.config.APIServer.Timeout.Max,).Wrap)- r.Use(middleware.NewAnalytics().Wrap)r.Use(middleware.NewLogging(s.signoz.Instrumentation.Logger(), s.config.APIServer.Logging.ExcludedRoutes).Wrap)apiHandler.RegisterRoutes(r, am)diff --git a/frontend/src/api/userFeedback/sendFeedback.ts b/frontend/src/api/userFeedback/sendFeedback.tsdeleted file mode 100644index abf811378c..0000000000--- a/frontend/src/api/userFeedback/sendFeedback.ts+++ /dev/null@@ -1,21 +0,0 @@-import axios from 'api';-import { Props } from 'types/api/userFeedback/sendResponse';--const sendFeedback = async (props: Props): Promise<number> => {- const response = await axios.post(- '/feedback',- {- email: props.email,- message: props.message,- },- {- headers: {- 'Content-Type': 'application/x-www-form-urlencoded',- },- },- );-- return response.status;-};--export default sendFeedback;diff --git a/pkg/http/middleware/analytics.go b/pkg/http/middleware/analytics.godeleted file mode 100644index 48ca569104..0000000000--- a/pkg/http/middleware/analytics.go+++ /dev/null@@ -1,123 +0,0 @@-package middleware--import (- "bytes"- "encoding/json"- "io"- "net/http"- "regexp"-- v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"- "github.com/SigNoz/signoz/pkg/query-service/telemetry"- "github.com/SigNoz/signoz/pkg/types/authtypes"- "github.com/gorilla/mux"-)--type Analytics struct{}--func NewAnalytics() *Analytics {- return &Analytics{}-}--func (a *Analytics) Wrap(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- route := mux.CurrentRoute(r)- path, _ := route.GetPathTemplate()-- _, _ = a.extractQueryRangeData(path, r)- a.getActiveLogs(path, r)-- badResponseBuffer := new(bytes.Buffer)- writer := newBadResponseLoggingWriter(w, badResponseBuffer)- next.ServeHTTP(writer, r)- })--}--func (a *Analytics) getActiveLogs(path string, r *http.Request) {- // this is for the old logs explorer api.- if path == "/api/v1/logs" {- hasFilters := len(r.URL.Query().Get("q"))- if hasFilters > 0 {- telemetry.GetInstance().AddActiveLogsUser()- }-- }-}--func (a *Analytics) extractQueryRangeData(path string, r *http.Request) (map[string]interface{}, bool) {- pathToExtractBodyFromV3 := "/api/v3/query_range"- pathToExtractBodyFromV4 := "/api/v4/query_range"-- data := map[string]interface{}{}- var postData *v3.QueryRangeParamsV3-- if (r.Method == "POST") && ((path == pathToExtractBodyFromV3) || (path == pathToExtractBodyFromV4)) {- if r.Body != nil {- bodyBytes, err := io.ReadAll(r.Body)- if err != nil {- return nil, false- }- r.Body.Close() // must close- r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))- _ = json.Unmarshal(bodyBytes, &postData)-- } else {- return nil, false- }-- } else {- return nil, false- }-- referrer := r.Header.Get("Referer")-- dashboardMatched, _ := regexp.MatchString(`/dashboard/[a-zA-Z0-9\-]+/(new|edit)(?:\?.*)?$`, referrer)- alertMatched, _ := regexp.MatchString(`/alerts/(new|edit)(?:\?.*)?$`, referrer)- logsExplorerMatched, _ := regexp.MatchString(`/logs/logs-explorer(?:\?.*)?$`, referrer)- traceExplorerMatched, _ := regexp.MatchString(`/traces-explorer(?:\?.*)?$`, referrer)-- queryInfoResult := telemetry.GetInstance().CheckQueryInfo(postData)-- if (queryInfoResult.MetricsUsed || queryInfoResult.LogsUsed || queryInfoResult.TracesUsed) && (queryInfoResult.FilterApplied) {- if queryInfoResult.MetricsUsed {- telemetry.GetInstance().AddActiveMetricsUser()- }- if queryInfoResult.LogsUsed {- telemetry.GetInstance().AddActiveLogsUser()- }- if queryInfoResult.TracesUsed {- telemetry.GetInstance().AddActiveTracesUser()- }- data["metricsUsed"] = queryInfoResult.MetricsUsed- data["logsUsed"] = queryInfoResult.LogsUsed- data["tracesUsed"] = queryInfoResult.TracesUsed- data["filterApplied"] = queryInfoResult.FilterApplied- data["groupByApplied"] = queryInfoResult.GroupByApplied- data["aggregateOperator"] = queryInfoResult.AggregateOperator- data["aggregateAttributeKey"] = queryInfoResult.AggregateAttributeKey- data["numberOfQueries"] = queryInfoResult.NumberOfQueries- data["queryType"] = queryInfoResult.QueryType- data["panelType"] = queryInfoResult.PanelType-- claims, err := authtypes.ClaimsFromContext(r.Context())- if err == nil {- // switch case to set data["screen"] based on the referrer- switch {- case dashboardMatched:- data["screen"] = "panel"- case alertMatched:- data["screen"] = "alert"- case logsExplorerMatched:- data["screen"] = "logs-explorer"- case traceExplorerMatched:- data["screen"] = "traces-explorer"- default:- data["screen"] = "unknown"- return data, true- }- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_QUERY_RANGE_API, data, claims.Email, true, false)- }- }- return data, true-}diff --git a/pkg/modules/user/impluser/module.go b/pkg/modules/user/impluser/module.goindex 741ae74827..5b6793aac8 100644--- a/pkg/modules/user/impluser/module.go+++ b/pkg/modules/user/impluser/module.go@@ -16,7 +16,6 @@ import ("github.com/SigNoz/signoz/pkg/modules/user""github.com/SigNoz/signoz/pkg/query-service/constants""github.com/SigNoz/signoz/pkg/query-service/model"- "github.com/SigNoz/signoz/pkg/query-service/telemetry""github.com/SigNoz/signoz/pkg/types""github.com/SigNoz/signoz/pkg/types/authtypes""github.com/SigNoz/signoz/pkg/types/emailtypes"@@ -94,9 +93,7 @@ func (m *Module) CreateBulkInvite(ctx context.Context, orgID, userID string, bul// send telemetry eventfor i := 0; i < len(invites); i++ {- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_USER_INVITATION_SENT, map[string]interface{}{- "invited user email": invites[i].Email,- }, creator.Email, true, false)+ m.analytics.TrackUser(ctx, orgID, creator.ID.String(), "Invite Sent", map[string]any{"invitee_email": invites[i].Email, "invitee_role": invites[i].Role})if err := m.emailing.SendHTML(ctx, invites[i].Email, "You are invited to join a team in SigNoz", emailtypes.TemplateNameInvitationEmail, map[string]any{"CustomerName": invites[i].Name,diff --git a/pkg/query-service/app/clickhouseReader/reader.go b/pkg/query-service/app/clickhouseReader/reader.goindex f9b4ed908b..a2f5335585 100644--- a/pkg/query-service/app/clickhouseReader/reader.go+++ b/pkg/query-service/app/clickhouseReader/reader.go@@ -33,7 +33,6 @@ import ("github.com/ClickHouse/clickhouse-go/v2""github.com/ClickHouse/clickhouse-go/v2/lib/driver""github.com/SigNoz/signoz/pkg/cache"- "github.com/SigNoz/signoz/pkg/types/authtypes""go.uber.org/zap"@@ -48,7 +47,6 @@ import ("github.com/SigNoz/signoz/pkg/query-service/metrics""github.com/SigNoz/signoz/pkg/query-service/model"v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"- "github.com/SigNoz/signoz/pkg/query-service/telemetry""github.com/SigNoz/signoz/pkg/query-service/utils")@@ -875,7 +873,6 @@ func (r *ClickHouseReader) GetWaterfallSpansForTraceWithMetadata(ctx context.Convar serviceNameIntervalMap = map[string][]tracedetail.Interval{}var hasMissingSpans bool- claims, errv2 := authtypes.ClaimsFromContext(ctx)cachedTraceData, err := r.GetWaterfallSpansForTraceWithMetadataCache(ctx, orgID, traceID)if err == nil {startTime = cachedTraceData.StartTime@@ -887,10 +884,6 @@ func (r *ClickHouseReader) GetWaterfallSpansForTraceWithMetadata(ctx context.ContotalSpans = cachedTraceData.TotalSpanstotalErrorSpans = cachedTraceData.TotalErrorSpanshasMissingSpans = cachedTraceData.HasMissingSpans-- if errv2 == nil {- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_TRACE_DETAIL_API, map[string]interface{}{"traceSize": totalSpans}, claims.Email, true, false)- }}if err != nil {@@ -904,11 +897,6 @@ func (r *ClickHouseReader) GetWaterfallSpansForTraceWithMetadata(ctx context.Conreturn response, nil}totalSpans = uint64(len(searchScanResponses))-- if errv2 == nil {- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_TRACE_DETAIL_API, map[string]interface{}{"traceSize": totalSpans}, claims.Email, true, false)- }-processingBeforeCache := time.Now()for _, item := range searchScanResponses {ref := []model.OtelSpanRef{}@@ -2310,35 +2298,6 @@ func (r *ClickHouseReader) getPrevErrorID(ctx context.Context, queryParams *mode}}-func (r *ClickHouseReader) GetTotalSpans(ctx context.Context) (uint64, error) {-- var totalSpans uint64-- queryStr := fmt.Sprintf("SELECT count() from %s.%s;", signozTraceDBName, r.traceTableName)- r.db.QueryRow(ctx, queryStr).Scan(&totalSpans)-- return totalSpans, nil-}--// deprecated: remove this function in the next major release-func (r *ClickHouseReader) GetSpansInLastHeartBeatInterval(ctx context.Context, interval time.Duration) (uint64, error) {- var spansInLastHeartBeatInterval uint64- r.db.QueryRow(ctx, fmt.Sprintf("SELECT count() from %s.%s where ts_bucket_start >= toUInt64(toUnixTimestamp(now() - toIntervalMinute(%d))) - 1800 and timestamp > toUnixTimestamp(now()-toIntervalMinute(%d));", signozTraceDBName, r.traceTableName, int(interval.Minutes()), int(interval.Minutes()))).Scan(&spansInLastHeartBeatInterval)-- return spansInLastHeartBeatInterval, nil-}--// deprecated: remove this function in the next major release-func (r *ClickHouseReader) GetTotalLogs(ctx context.Context) (uint64, error) {-- var totalLogs uint64-- queryStr := fmt.Sprintf("SELECT count() from %s.%s;", r.logsDB, r.logsTableName)- r.db.QueryRow(ctx, queryStr).Scan(&totalLogs)-- return totalLogs, nil-}-func (r *ClickHouseReader) FetchTemporality(ctx context.Context, orgID valuer.UUID, metricNames []string) (map[string]map[v3.Temporality]bool, error) {metricNameToTemporality := make(map[string]map[v3.Temporality]bool)var metricNamesToQuery []string@@ -2379,127 +2338,6 @@ func (r *ClickHouseReader) FetchTemporality(ctx context.Context, orgID valuer.UUreturn metricNameToTemporality, nil}-// deprecated: remove this function in the next major release-func (r *ClickHouseReader) GetTimeSeriesInfo(ctx context.Context) (map[string]interface{}, error) {-- queryStr := fmt.Sprintf("SELECT countDistinct(fingerprint) as count from %s.%s where metric_name not like 'signoz_%%' group by metric_name order by count desc;", signozMetricDBName, signozTSTableNameV41Day)-- rows, _ := r.db.Query(ctx, queryStr)-- var totalTS uint64- totalTS = 0-- var maxTS uint64- maxTS = 0-- count := 0- for rows.Next() {-- var value uint64- rows.Scan(&value)- totalTS += value- if count == 0 {- maxTS = value- }- count += 1- }-- timeSeriesData := map[string]interface{}{}- timeSeriesData["totalTS"] = totalTS- timeSeriesData["maxTS"] = maxTS-- return timeSeriesData, nil-}--// deprecated: remove this function in the next major release-func (r *ClickHouseReader) GetSamplesInfoInLastHeartBeatInterval(ctx context.Context, interval time.Duration) (uint64, error) {-- var totalSamples uint64-- queryStr := fmt.Sprintf("select count() from %s.%s where metric_name not like 'signoz_%%' and unix_milli > toUnixTimestamp(now()-toIntervalMinute(%d))*1000;", signozMetricDBName, signozSampleTableName, int(interval.Minutes()))-- r.db.QueryRow(ctx, queryStr).Scan(&totalSamples)-- return totalSamples, nil-}--// deprecated: remove this function in the next major release-func (r *ClickHouseReader) GetTotalSamples(ctx context.Context) (uint64, error) {- var totalSamples uint64-- queryStr := fmt.Sprintf("select count() from %s.%s where metric_name not like 'signoz_%%';", signozMetricDBName, signozSampleTableName)-- r.db.QueryRow(ctx, queryStr).Scan(&totalSamples)-- return totalSamples, nil-}--// deprecated: remove this function in the next major release-func (r *ClickHouseReader) GetDistributedInfoInLastHeartBeatInterval(ctx context.Context) (map[string]interface{}, error) {-- clusterInfo := []model.ClusterInfo{}-- queryStr := `SELECT shard_num, shard_weight, replica_num, errors_count, slowdowns_count, estimated_recovery_time FROM system.clusters where cluster='cluster';`- r.db.Select(ctx, &clusterInfo, queryStr)- if len(clusterInfo) == 1 {- return clusterInfo[0].GetMapFromStruct(), nil- }-- return nil, nil-}--// deprecated: remove this function in the next major release-func (r *ClickHouseReader) GetLogsInfoInLastHeartBeatInterval(ctx context.Context, interval time.Duration) (uint64, error) {-- var totalLogLines uint64-- queryStr := fmt.Sprintf("select count() from %s.%s where timestamp > toUnixTimestamp(now()-toIntervalMinute(%d))*1000000000;", r.logsDB, r.logsTableV2, int(interval.Minutes()))-- err := r.db.QueryRow(ctx, queryStr).Scan(&totalLogLines)-- return totalLogLines, err-}--// deprecated: remove this function in the next major release-func (r *ClickHouseReader) GetTagsInfoInLastHeartBeatInterval(ctx context.Context, interval time.Duration) (*model.TagsInfo, error) {- queryStr := fmt.Sprintf(`select serviceName, resources_string['deployment.environment'] as env,- resources_string['telemetry.sdk.language'] as language from %s.%s- where timestamp > toUnixTimestamp(now()-toIntervalMinute(%d))- group by serviceName, env, language;`, r.TraceDB, r.traceTableName, int(interval.Minutes()))-- tagTelemetryDataList := []model.TagTelemetryData{}- err := r.db.Select(ctx, &tagTelemetryDataList, queryStr)-- if err != nil {- zap.L().Error("Error in processing sql query: ", zap.Error(err))- return nil, err- }-- tagsInfo := model.TagsInfo{- Languages: make(map[string]interface{}),- Services: make(map[string]interface{}),- }-- for _, tagTelemetryData := range tagTelemetryDataList {-- if len(tagTelemetryData.ServiceName) != 0 && strings.Contains(tagTelemetryData.ServiceName, "prod") {- tagsInfo.Env = tagTelemetryData.ServiceName- }- if len(tagTelemetryData.Env) != 0 && strings.Contains(tagTelemetryData.Env, "prod") {- tagsInfo.Env = tagTelemetryData.Env- }- if len(tagTelemetryData.Language) != 0 {- tagsInfo.Languages[tagTelemetryData.Language] = struct{}{}- }- if len(tagTelemetryData.ServiceName) != 0 {- tagsInfo.Services[tagTelemetryData.ServiceName] = struct{}{}- }-- }-- return &tagsInfo, nil-}-func (r *ClickHouseReader) GetLogFields(ctx context.Context) (*model.GetFieldsResponse, *model.ApiError) {// response will contain top level fields from the otel log modelresponse := model.GetFieldsResponse{@@ -6113,51 +5951,24 @@ func (r *ClickHouseReader) SearchTraces(ctx context.Context, params *model.Searc}if traceSummary.NumSpans > uint64(params.MaxSpansInTrace) {- zap.L().Error("Max spans allowed in a trace limit reached", zap.Int("MaxSpansInTrace", params.MaxSpansInTrace),- zap.Uint64("Count", traceSummary.NumSpans))- claims, errv2 := authtypes.ClaimsFromContext(ctx)- if errv2 == nil {- data := map[string]interface{}{- "traceSize": traceSummary.NumSpans,- "maxSpansInTraceLimit": params.MaxSpansInTrace,- "algo": "smart",- }- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_MAX_SPANS_ALLOWED_LIMIT_REACHED, data, claims.Email, true, false)- }+ zap.L().Error("Max spans allowed in a trace limit reached", zap.Int("MaxSpansInTrace", params.MaxSpansInTrace), zap.Uint64("Count", traceSummary.NumSpans))return nil, fmt.Errorf("max spans allowed in trace limit reached, please contact support for more details")}- claims, errv2 := authtypes.ClaimsFromContext(ctx)- if errv2 == nil {- data := map[string]interface{}{- "traceSize": traceSummary.NumSpans,- "algo": "smart",- }- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_TRACE_DETAIL_API, data, claims.Email, true, false)- }-var startTime, endTime, durationNano uint64var searchScanResponses []model.SpanItemV2query := fmt.Sprintf("SELECT timestamp, duration_nano, span_id, trace_id, has_error, kind, resource_string_service$$name, name, references, attributes_string, attributes_number, attributes_bool, resources_string, events, status_message, status_code_string, kind_string FROM %s.%s WHERE trace_id=$1 and ts_bucket_start>=$2 and ts_bucket_start<=$3", r.TraceDB, r.traceTableName)-- start := time.Now()-err = r.db.Select(ctx, &searchScanResponses, query, params.TraceID, strconv.FormatInt(traceSummary.Start.Unix()-1800, 10), strconv.FormatInt(traceSummary.End.Unix(), 10))-- zap.L().Info(query)-if err != nil {zap.L().Error("Error in processing sql query", zap.Error(err))return nil, fmt.Errorf("error in processing sql query")}- end := time.Now()- zap.L().Debug("getTraceSQLQuery took: ", zap.Duration("duration", end.Sub(start)))searchSpansResult[0].Events = make([][]interface{}, len(searchScanResponses))searchSpanResponses := []model.SearchSpanResponseItem{}- start = time.Now()+for _, item := range searchScanResponses {ref := []model.OtelSpanRef{}err := json.Unmarshal([]byte(item.References), &ref)@@ -6206,26 +6017,12 @@ func (r *ClickHouseReader) SearchTraces(ctx context.Context, params *model.SearcdurationNano = uint64(jsonItem.DurationNano)}}- end = time.Now()- zap.L().Debug("getTraceSQLQuery unmarshal took: ", zap.Duration("duration", end.Sub(start)))if len(searchScanResponses) > params.SpansRenderLimit {- start = time.Now()searchSpansResult, err = smart.SmartTraceAlgorithm(searchSpanResponses, params.SpanID, params.LevelUp, params.LevelDown, params.SpansRenderLimit)if err != nil {return nil, err}- end = time.Now()- zap.L().Debug("smartTraceAlgo took: ", zap.Duration("duration", end.Sub(start)))- claims, errv2 := authtypes.ClaimsFromContext(ctx)- if errv2 == nil {- data := map[string]interface{}{- "traceSize": len(searchScanResponses),- "spansRenderLimit": params.SpansRenderLimit,- "algo": "smart",- }- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_LARGE_TRACE_OPENED, data, claims.Email, true, false)- }} else {for i, item := range searchSpanResponses {spanEvents := item.GetValues()diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.goindex 9c838d9bf5..94d465fd10 100644--- a/pkg/query-service/app/http_handler.go+++ b/pkg/query-service/app/http_handler.go@@ -74,7 +74,6 @@ import ("github.com/SigNoz/signoz/pkg/query-service/interfaces""github.com/SigNoz/signoz/pkg/query-service/model""github.com/SigNoz/signoz/pkg/query-service/rules"- "github.com/SigNoz/signoz/pkg/query-service/telemetry""github.com/SigNoz/signoz/pkg/version"querierAPI "github.com/SigNoz/signoz/pkg/querier"@@ -527,8 +526,6 @@ func (aH *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {router.HandleFunc("/api/v1/explorer/views/{viewId}", am.ViewAccess(aH.Signoz.Handlers.SavedView.Get)).Methods(http.MethodGet)router.HandleFunc("/api/v1/explorer/views/{viewId}", am.EditAccess(aH.Signoz.Handlers.SavedView.Update)).Methods(http.MethodPut)router.HandleFunc("/api/v1/explorer/views/{viewId}", am.EditAccess(aH.Signoz.Handlers.SavedView.Delete)).Methods(http.MethodDelete)-- router.HandleFunc("/api/v1/feedback", am.OpenAccess(aH.submitFeedback)).Methods(http.MethodPost)router.HandleFunc("/api/v1/event", am.ViewAccess(aH.registerEvent)).Methods(http.MethodPost)router.HandleFunc("/api/v1/services", am.ViewAccess(aH.getServices)).Methods(http.MethodPost)@@ -1529,38 +1526,6 @@ func (aH *APIHandler) queryMetrics(w http.ResponseWriter, r *http.Request) {}-func (aH *APIHandler) submitFeedback(w http.ResponseWriter, r *http.Request) {-- var postData map[string]interface{}- err := json.NewDecoder(r.Body).Decode(&postData)- if err != nil {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: err}, "Error reading request body")- return- }-- message, ok := postData["message"]- if !ok {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: fmt.Errorf("message not present in request body")}, "Error reading message from request body")- return- }- messageStr := fmt.Sprintf("%s", message)- if len(messageStr) == 0 {- RespondError(w, &model.ApiError{Typ: model.ErrorBadData, Err: fmt.Errorf("empty message in request body")}, "empty message in request body")- return- }-- email := postData["email"]-- data := map[string]interface{}{- "email": email,- "message": message,- }- claims, errv2 := authtypes.ClaimsFromContext(r.Context())- if errv2 == nil {- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_INPRODUCT_FEEDBACK, data, claims.Email, true, false)- }-}-func (aH *APIHandler) registerEvent(w http.ResponseWriter, r *http.Request) {request, err := parseRegisterEventRequest(r)if aH.HandleError(w, err, http.StatusBadRequest) {@@ -1570,12 +1535,7 @@ func (aH *APIHandler) registerEvent(w http.ResponseWriter, r *http.Request) {if errv2 == nil {switch request.EventType {case model.TrackEvent:- telemetry.GetInstance().SendEvent(request.EventName, request.Attributes, claims.Email, request.RateLimited, true)aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, request.EventName, request.Attributes)- case model.GroupEvent:- telemetry.GetInstance().SendGroupEvent(request.Attributes, claims.Email)- case model.IdentifyEvent:- telemetry.GetInstance().SendIdentifyEvent(request.Attributes, claims.Email)}aH.WriteJSON(w, r, map[string]string{"data": "Event Processed Successfully"})} else {@@ -1682,7 +1642,6 @@ func (aH *APIHandler) getServicesTopLevelOps(w http.ResponseWriter, r *http.Requ}func (aH *APIHandler) getServices(w http.ResponseWriter, r *http.Request) {-query, err := parseGetServicesRequest(r)if aH.HandleError(w, err, http.StatusBadRequest) {return@@ -1693,18 +1652,6 @@ func (aH *APIHandler) getServices(w http.ResponseWriter, r *http.Request) {return}- data := map[string]interface{}{- "number": len(*result),- }- claims, errv2 := authtypes.ClaimsFromContext(r.Context())- if errv2 == nil {- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_NUMBER_OF_SERVICES, data, claims.Email, true, false)- }-- if (data["number"] != 0) && (data["number"] != telemetry.DEFAULT_NUMBER_OF_SERVICES) {- telemetry.GetInstance().AddActiveTracesUser()- }-aH.WriteJSON(w, r, result)}@@ -4518,7 +4465,7 @@ func (aH *APIHandler) queryRangeV3(ctx context.Context, queryRangeParams *v3.Quepostprocess.ApplyHavingClause(result, queryRangeParams)postprocess.ApplyMetricLimit(result, queryRangeParams)- sendQueryResultEvents(r, result, queryRangeParams)+ aH.sendQueryResultEvents(r, result, queryRangeParams, "v3")// only adding applyFunctions instead of postProcess since experssion are// are executed in clickhouse directly and we wanted to add support for timeshiftif queryRangeParams.CompositeQuery.QueryType == v3.QueryTypeBuilder {@@ -4554,96 +4501,63 @@ func (aH *APIHandler) queryRangeV3(ctx context.Context, queryRangeParams *v3.QueaH.Respond(w, resp)}-func sendQueryResultEvents(r *http.Request, result []*v3.Result, queryRangeParams *v3.QueryRangeParamsV3) {+func (aH *APIHandler) sendQueryResultEvents(r *http.Request, result []*v3.Result, queryRangeParams *v3.QueryRangeParamsV3, version string) {+ claims, err := authtypes.ClaimsFromContext(r.Context())+ if err != nil {+ return+ }++ queryInfoResult := NewQueryInfoResult(queryRangeParams, version)+ if !(len(result) > 0 && (len(result[0].Series) > 0 || len(result[0].List) > 0)) {+ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, "Telemetry Query Returned Empty", queryInfoResult.ToMap())+ return+ }++ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, "Telemetry Query Returned Results", queryInfoResult.ToMap())++ if !(queryInfoResult.LogsUsed || queryInfoResult.MetricsUsed || queryInfoResult.TracesUsed) {+ return+ }+referrer := r.Header.Get("Referer")+ if referrer == "" {+ return+ }- dashboardMatched, err := regexp.MatchString(`/dashboard/[a-zA-Z0-9\-]+/(new|edit)(?:\?.*)?$`, referrer)- if err != nil {- zap.L().Error("error while matching the referrer", zap.Error(err))- }- alertMatched, err := regexp.MatchString(`/alerts/(new|edit)(?:\?.*)?$`, referrer)- if err != nil {- zap.L().Error("error while matching the alert: ", zap.Error(err))- }-- if alertMatched || dashboardMatched {-- if len(result) > 0 && (len(result[0].Series) > 0 || len(result[0].List) > 0) {-- claims, errv2 := authtypes.ClaimsFromContext(r.Context())- if errv2 == nil {- queryInfoResult := telemetry.GetInstance().CheckQueryInfo(queryRangeParams)- if queryInfoResult.LogsUsed || queryInfoResult.MetricsUsed || queryInfoResult.TracesUsed {-- if dashboardMatched {- var dashboardID, widgetID string- var dashboardIDMatch, widgetIDMatch []string- dashboardIDRegex, err := regexp.Compile(`/dashboard/([a-f0-9\-]+)/`)- if err == nil {- dashboardIDMatch = dashboardIDRegex.FindStringSubmatch(referrer)- } else {- zap.S().Errorf("error while matching the dashboardIDRegex: %v", err)- }- widgetIDRegex, err := regexp.Compile(`widgetId=([a-f0-9\-]+)`)- if err == nil {- widgetIDMatch = widgetIDRegex.FindStringSubmatch(referrer)- } else {- zap.S().Errorf("error while matching the widgetIDRegex: %v", err)- }-- if len(dashboardIDMatch) > 1 {- dashboardID = dashboardIDMatch[1]- }-- if len(widgetIDMatch) > 1 {- widgetID = widgetIDMatch[1]- }- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_SUCCESSFUL_DASHBOARD_PANEL_QUERY, map[string]interface{}{- "queryType": queryRangeParams.CompositeQuery.QueryType,- "panelType": queryRangeParams.CompositeQuery.PanelType,- "tracesUsed": queryInfoResult.TracesUsed,- "logsUsed": queryInfoResult.LogsUsed,- "metricsUsed": queryInfoResult.MetricsUsed,- "numberOfQueries": queryInfoResult.NumberOfQueries,- "groupByApplied": queryInfoResult.GroupByApplied,- "aggregateOperator": queryInfoResult.AggregateOperator,- "aggregateAttributeKey": queryInfoResult.AggregateAttributeKey,- "filterApplied": queryInfoResult.FilterApplied,- "dashboardId": dashboardID,- "widgetId": widgetID,- }, claims.Email, true, false)- }- if alertMatched {- var alertID string- var alertIDMatch []string- alertIDRegex, err := regexp.Compile(`ruleId=(\d+)`)- if err != nil {- zap.S().Errorf("error while matching the alertIDRegex: %v", err)- } else {- alertIDMatch = alertIDRegex.FindStringSubmatch(referrer)- }-- if len(alertIDMatch) > 1 {- alertID = alertIDMatch[1]- }- telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_SUCCESSFUL_ALERT_QUERY, map[string]interface{}{- "queryType": queryRangeParams.CompositeQuery.QueryType,- "panelType": queryRangeParams.CompositeQuery.PanelType,- "tracesUsed": queryInfoResult.TracesUsed,- "logsUsed": queryInfoResult.LogsUsed,- "metricsUsed": queryInfoResult.MetricsUsed,- "numberOfQueries": queryInfoResult.NumberOfQueries,- "groupByApplied": queryInfoResult.GroupByApplied,- "aggregateOperator": queryInfoResult.AggregateOperator,- "aggregateAttributeKey": queryInfoResult.AggregateAttributeKey,- "filterApplied": queryInfoResult.FilterApplied,- "alertId": alertID,- }, claims.Email, true, false)- }- }+ if matched, _ := regexp.MatchString(`/dashboard/[a-zA-Z0-9\-]+/(new|edit)(?:\?.*)?$`, referrer); matched {+ properties := queryInfoResult.ToMap()++ if dashboardIDRegex, err := regexp.Compile(`/dashboard/([a-f0-9\-]+)/`); err == nil {+ if matches := dashboardIDRegex.FindStringSubmatch(referrer); len(matches) > 1 {+ properties["dashboard_id"] = matches[1]+ }+ }++ if widgetIDRegex, err := regexp.Compile(`widgetId=([a-f0-9\-]+)`); err == nil {+ if matches := widgetIDRegex.FindStringSubmatch(referrer); len(matches) > 1 {+ properties["widget_id"] = matches[1]+ }+ }++ properties["referrer"] = referrer+ properties["module_name"] = "dashboard"+ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, "Telemetry Query Returned Results", properties)+ }++ if matched, _ := regexp.MatchString(`/alerts/(new|edit)(?:\?.*)?$`, referrer); matched {+ properties := queryInfoResult.ToMap()++ if alertIDRegex, err := regexp.Compile(`ruleId=(\d+)`); err == nil {+ if matches := alertIDRegex.FindStringSubmatch(referrer); len(matches) > 1 {+ properties["alert_id"] = matches[1]}}++ properties["referrer"] = referrer+ properties["module_name"] = "rule"+ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, "Telemetry Query Returned Results", properties)}+}func (aH *APIHandler) QueryRangeV3(w http.ResponseWriter, r *http.Request) {@@ -4935,7 +4849,7 @@ func (aH *APIHandler) queryRangeV4(ctx context.Context, queryRangeParams *v3.QueRespondError(w, apiErrObj, errQuriesByName)return}- sendQueryResultEvents(r, result, queryRangeParams)+ aH.sendQueryResultEvents(r, result, queryRangeParams, "v4")resp := v3.QueryRangeResponse{Result: result,}diff --git a/pkg/query-service/app/query_info.go b/pkg/query-service/app/query_info.gonew file mode 100644index 0000000000..e501d098ce--- /dev/null+++ b/pkg/query-service/app/query_info.go@@ -0,0 +1,99 @@+package app++import (+ "encoding/json"+ "strings"++ v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"+)++// TODO(srikanthccv): Move to the querier layer+type QueryInfoResult struct {+ Version string `json:"version"`+ LogsUsed bool `json:"logs_used,omitempty"`+ MetricsUsed bool `json:"metrics_used,omitempty"`+ TracesUsed bool `json:"traces_used,omitempty"`+ FilterApplied bool `json:"filter_applied,omitempty"`+ GroupByApplied bool `json:"group_by_applied,omitempty"`+ AggregateOperator v3.AggregateOperator `json:"aggregate_operator,omitempty"`+ AggregateAttributeKey string `json:"aggregate_attribute_key,omitempty"`+ QueryType v3.QueryType `json:"query_type,omitempty"`+ PanelType v3.PanelType `json:"panel_type,omitempty"`+ NumberOfQueries int `json:"number_of_queries,omitempty"`+}++func NewQueryInfoResult(postData *v3.QueryRangeParamsV3, version string) QueryInfoResult {+ queryInfoResult := QueryInfoResult{+ Version: version,+ }++ if postData == nil {+ return queryInfoResult+ }++ if postData.CompositeQuery == nil {+ return queryInfoResult+ }++ queryInfoResult.PanelType = postData.CompositeQuery.PanelType+ queryInfoResult.QueryType = postData.CompositeQuery.QueryType++ if postData.CompositeQuery.QueryType == v3.QueryTypeBuilder {+ queryInfoResult.NumberOfQueries = len(postData.CompositeQuery.BuilderQueries)+ for _, query := range postData.CompositeQuery.BuilderQueries {+ if query.DataSource == v3.DataSourceLogs {+ queryInfoResult.LogsUsed = true+ } else if query.DataSource == v3.DataSourceMetrics {+ queryInfoResult.MetricsUsed = true++ } else if query.DataSource == v3.DataSourceTraces {+ queryInfoResult.TracesUsed = true+ }+ if query.Filters != nil && len(query.Filters.Items) > 0 {+ queryInfoResult.FilterApplied = true+ }+ if query.GroupBy != nil && len(query.GroupBy) > 0 {+ queryInfoResult.GroupByApplied = true+ }+ queryInfoResult.AggregateOperator = query.AggregateOperator+ if len(query.AggregateAttribute.Key) > 0 && !strings.Contains(query.AggregateAttribute.Key, "signoz_") {+ queryInfoResult.AggregateAttributeKey = query.AggregateAttribute.Key+ }+ }+ } else if postData.CompositeQuery.QueryType == v3.QueryTypePromQL {+ for _, query := range postData.CompositeQuery.PromQueries {+ if !strings.Contains(query.Query, "signoz_") && len(query.Query) > 0 {+ queryInfoResult.MetricsUsed = true+ }+ }+ } else if postData.CompositeQuery.QueryType == v3.QueryTypeClickHouseSQL {+ for _, query := range postData.CompositeQuery.ClickHouseQueries {+ if strings.Contains(query.Query, "signoz_metrics") && len(query.Query) > 0 {+ queryInfoResult.MetricsUsed = true+ }+ if strings.Contains(query.Query, "signoz_logs") && len(query.Query) > 0 {+ queryInfoResult.LogsUsed = true+ }+ if strings.Contains(query.Query, "signoz_traces") && len(query.Query) > 0 {+ queryInfoResult.TracesUsed = true+ }+ }+ }++ return queryInfoResult+}++func (queryInfoResult QueryInfoResult) ToMap() map[string]interface{} {+ marshalled, err := json.Marshal(queryInfoResult)+ if err != nil {+ return nil+ }++ var result map[string]interface{}+ err = json.Unmarshal(marshalled, &result)+ if err != nil {+ return nil+ }++ return result+}diff --git a/pkg/query-service/app/server.go b/pkg/query-service/app/server.goindex e4905c039d..6bc7014178 100644--- a/pkg/query-service/app/server.go+++ b/pkg/query-service/app/server.go@@ -36,7 +36,6 @@ import ("github.com/SigNoz/signoz/pkg/query-service/healthcheck""github.com/SigNoz/signoz/pkg/query-service/interfaces""github.com/SigNoz/signoz/pkg/query-service/rules"- "github.com/SigNoz/signoz/pkg/query-service/telemetry""github.com/SigNoz/signoz/pkg/query-service/utils""go.uber.org/zap")@@ -104,15 +103,6 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz, jwt *authtypes.JWT)return nil, err}- // todo(remove): remove in favour of statsreporter and analytics- telemetry.GetInstance().SetReader(reader)- telemetry.GetInstance().SetSqlStore(signoz.SQLStore)- telemetry.GetInstance().SetSavedViewsInfoCallback(telemetry.GetSavedViewsInfo)- telemetry.GetInstance().SetAlertsInfoCallback(telemetry.GetAlertsInfo)- telemetry.GetInstance().SetGetUsersCallback(telemetry.GetUsers)- telemetry.GetInstance().SetUserCountCallback(telemetry.GetUserCount)- telemetry.GetInstance().SetDashboardsInfoCallback(telemetry.GetDashboardsInfo)-apiHandler, err := NewAPIHandler(APIHandlerOpts{Reader: reader,RuleManager: rm,@@ -203,7 +193,6 @@ func (s *Server) createPrivateServer(api *APIHandler) (*http.Server, error) {s.config.APIServer.Timeout.Default,s.config.APIServer.Timeout.Max,).Wrap)- r.Use(middleware.NewAnalytics().Wrap)r.Use(middleware.NewAPIKey(s.signoz.SQLStore, []string{"SIGNOZ-API-KEY"}, s.signoz.Instrumentation.Logger(), s.signoz.Sharder).Wrap)r.Use(middleware.NewLogging(s.signoz.Instrumentation.Logger(), s.config.APIServer.Logging.ExcludedRoutes).Wrap)@@ -234,7 +223,6 @@ func (s *Server) createPublicServer(api *APIHandler, web web.Web) (*http.Server,s.config.APIServer.Timeout.Default,s.config.APIServer.Timeout.Max,).Wrap)- r.Use(middleware.NewAnalytics().Wrap)r.Use(middleware.NewAPIKey(s.signoz.SQLStore, []string{"SIGNOZ-API-KEY"}, s.signoz.Instrumentation.Logger(), s.signoz.Sharder).Wrap)r.Use(middleware.NewLogging(s.signoz.Instrumentation.Logger(), s.config.APIServer.Logging.ExcludedRoutes).Wrap)diff --git a/pkg/query-service/constants/constants.go b/pkg/query-service/constants/constants.goindex 41196368b4..3be0bef5b9 100644--- a/pkg/query-service/constants/constants.go+++ b/pkg/query-service/constants/constants.go@@ -4,7 +4,6 @@ import ("maps""os""strconv"- "testing""time""github.com/SigNoz/signoz/pkg/query-service/model"@@ -18,31 +17,8 @@ const (OpAmpWsEndpoint = "0.0.0.0:4320" // address for opamp websocket)-// Deprecated: Use the new analytics service instead-var DEFAULT_TELEMETRY_ANONYMOUS = false--// Deprecated: Use the new analytics service instead-func IsOSSTelemetryEnabled() bool {- ossSegmentKey := GetOrDefaultEnv("OSS_TELEMETRY_ENABLED", "true")- return ossSegmentKey == "true"-}-const MaxAllowedPointsInTimeSeries = 300-// Deprecated: Use the new analytics service instead-func IsTelemetryEnabled() bool {- if testing.Testing() {- return false- }-- isTelemetryEnabledStr := os.Getenv("TELEMETRY_ENABLED")- isTelemetryEnabledBool, err := strconv.ParseBool(isTelemetryEnabledStr)- if err != nil {- return true- }- return isTelemetryEnabledBool-}-const TraceTTL = "traces"const MetricsTTL = "metrics"const LogsTTL = "logs"@@ -51,12 +27,6 @@ const SpanSearchScopeRoot = "isroot"const SpanSearchScopeEntryPoint = "isentrypoint"const OrderBySpanCount = "span_count"-// Deprecated: Use the new statsreporter service instead-var TELEMETRY_HEART_BEAT_DURATION_MINUTES = GetOrDefaultEnvInt("TELEMETRY_HEART_BEAT_DURATION_MINUTES", 720)--// Deprecated: Use the new statsreporter service instead-var TELEMETRY_ACTIVE_USER_DURATION_MINUTES = GetOrDefaultEnvInt("TELEMETRY_ACTIVE_USER_DURATION_MINUTES", 360)-// Deprecated: Use the new emailing service insteadvar InviteEmailTemplate = GetOrDefaultEnv("INVITE_EMAIL_TEMPLATE", "/root/templates/invitation_email.gotmpl")diff --git a/pkg/query-service/interfaces/interface.go b/pkg/query-service/interfaces/interface.goindex 1a44504157..833368e53c 100644--- a/pkg/query-service/interfaces/interface.go+++ b/pkg/query-service/interfaces/interface.go@@ -63,16 +63,6 @@ type Reader interface {GetListResultV3(ctx context.Context, query string) ([]*v3.Row, error)LiveTailLogsV3(ctx context.Context, query string, timestampStart uint64, idStart string, client *model.LogsLiveTailClient)LiveTailLogsV4(ctx context.Context, query string, timestampStart uint64, idStart string, client *model.LogsLiveTailClientV2)-- GetTotalSpans(ctx context.Context) (uint64, error)- GetTotalLogs(ctx context.Context) (uint64, error)- GetTotalSamples(ctx context.Context) (uint64, error)- GetSpansInLastHeartBeatInterval(ctx context.Context, interval time.Duration) (uint64, error)- GetTimeSeriesInfo(ctx context.Context) (map[string]interface{}, error)- GetSamplesInfoInLastHeartBeatInterval(ctx context.Context, interval time.Duration) (uint64, error)- GetLogsInfoInLastHeartBeatInterval(ctx context.Context, interval time.Duration) (uint64, error)- GetTagsInfoInLastHeartBeatInterval(ctx context.Context, interval time.Duration) (*model.TagsInfo, error)- GetDistributedInfoInLastHeartBeatInterval(ctx context.Context) (map[string]interface{}, error)// LogsGetLogFields(ctx context.Context) (*model.GetFieldsResponse, *model.ApiError)GetLogFieldsFromNames(ctx context.Context, fieldNames []string) (*model.GetFieldsResponse, *model.ApiError)diff --git a/pkg/query-service/telemetry/dashboard.go b/pkg/query-service/telemetry/dashboard.godeleted file mode 100644index 1bd2c2e4f9..0000000000--- a/pkg/query-service/telemetry/dashboard.go+++ /dev/null@@ -1,232 +0,0 @@-package telemetry--import (- "context"- "encoding/json"- "slices"- "strings"-- "github.com/SigNoz/signoz/pkg/query-service/model"- "github.com/SigNoz/signoz/pkg/sqlstore"- "github.com/SigNoz/signoz/pkg/types/dashboardtypes"- "go.uber.org/zap"-)--// deprecated: remove this function in the next major release-func GetDashboardsInfo(ctx context.Context, sqlstore sqlstore.SQLStore) (*model.DashboardsInfo, error) {- dashboardsInfo := model.DashboardsInfo{}- // fetch dashboards from dashboard db- dashboards := []dashboardtypes.StorableDashboard{}- err := sqlstore.BunDB().NewSelect().Model(&dashboards).Scan(ctx)- if err != nil {- zap.L().Error("Error in processing sql query", zap.Error(err))- return &dashboardsInfo, err- }- totalDashboardsWithPanelAndName := 0- var dashboardNames []string- count := 0- queriesWithTagAttrs := 0- for _, dashboard := range dashboards {- if isDashboardWithPanelAndName(dashboard.Data) {- totalDashboardsWithPanelAndName = totalDashboardsWithPanelAndName + 1- }- dashboardName := extractDashboardName(dashboard.Data)- if dashboardName != "" {- dashboardNames = append(dashboardNames, dashboardName)- }- dashboardInfo := countPanelsInDashboard(dashboard.Data)- dashboardsInfo.LogsBasedPanels += dashboardInfo.LogsBasedPanels- dashboardsInfo.TracesBasedPanels += dashboardInfo.TracesBasedPanels- dashboardsInfo.MetricBasedPanels += dashboardInfo.MetricBasedPanels- dashboardsInfo.LogsPanelsWithAttrContainsOp += dashboardInfo.LogsPanelsWithAttrContainsOp- dashboardsInfo.DashboardsWithLogsChQuery += dashboardInfo.DashboardsWithLogsChQuery- dashboardsInfo.DashboardsWithTraceChQuery += dashboardInfo.DashboardsWithTraceChQuery- if isDashboardWithTSV2(dashboard.Data) {- count = count + 1- }-- if isDashboardWithTagAttrs(dashboard.Data) {- queriesWithTagAttrs += 1- }-- if dashboardInfo.DashboardsWithTraceChQuery > 0 {- dashboardsInfo.DashboardNamesWithTraceChQuery = append(dashboardsInfo.DashboardNamesWithTraceChQuery, dashboardName)- }-- // check if dashboard is a has a log operator with contains- }-- dashboardsInfo.DashboardNames = dashboardNames- dashboardsInfo.TotalDashboards = len(dashboards)- dashboardsInfo.TotalDashboardsWithPanelAndName = totalDashboardsWithPanelAndName- dashboardsInfo.QueriesWithTSV2 = count- dashboardsInfo.QueriesWithTagAttrs = queriesWithTagAttrs- return &dashboardsInfo, nil-}--// deprecated: remove this function in the next major release-func isDashboardWithTSV2(data map[string]interface{}) bool {- jsonData, err := json.Marshal(data)- if err != nil {- return false- }- return strings.Contains(string(jsonData), "time_series_v2")-}--// deprecated: remove this function in the next major release-func isDashboardWithTagAttrs(data map[string]interface{}) bool {- jsonData, err := json.Marshal(data)- if err != nil {- return false- }- return strings.Contains(string(jsonData), "span_attributes") ||- strings.Contains(string(jsonData), "tag_attributes")-}--// deprecated: remove this function in the next major release-func isDashboardWithLogsClickhouseQuery(data map[string]interface{}) bool {- jsonData, err := json.Marshal(data)- if err != nil {- return false- }- result := strings.Contains(string(jsonData), "signoz_logs.distributed_logs") ||- strings.Contains(string(jsonData), "signoz_logs.logs")- return result-}--// deprecated: remove this function in the next major release-func isDashboardWithTracesClickhouseQuery(data map[string]interface{}) bool {- jsonData, err := json.Marshal(data)- if err != nil {- return false- }-- // also check if the query is actually active- str := string(jsonData)- result := strings.Contains(str, "signoz_traces.distributed_signoz_index_v2") ||- strings.Contains(str, "signoz_traces.distributed_signoz_spans") ||- strings.Contains(str, "signoz_traces.distributed_signoz_error_index_v2")- return result-}--// deprecated: remove this function in the next major release-func isDashboardWithPanelAndName(data map[string]interface{}) bool {- isDashboardName := false- isDashboardWithPanelAndName := false- if data != nil && data["title"] != nil && data["widgets"] != nil {- title, ok := data["title"].(string)- if ok && title != "Sample Title" {- isDashboardName = true- }- widgets, ok := data["widgets"]- if ok && isDashboardName {- data, ok := widgets.([]interface{})- if ok && len(data) > 0 {- isDashboardWithPanelAndName = true- }- }- }-- return isDashboardWithPanelAndName-}--// deprecated: remove this function in the next major release-func extractDashboardName(data map[string]interface{}) string {- if data != nil && data["title"] != nil {- title, ok := data["title"].(string)- if ok {- return title- }- }-- return ""-}--// deprecated: remove this function in the next major release-func checkLogPanelAttrContains(data map[string]interface{}) int {- var logsPanelsWithAttrContains int- filters, ok := data["filters"].(map[string]interface{})- if ok && filters["items"] != nil {- items, ok := filters["items"].([]interface{})- if ok {- for _, item := range items {- itemMap, ok := item.(map[string]interface{})- if ok {- opStr, ok := itemMap["op"].(string)- if ok {- if slices.Contains([]string{"contains", "ncontains", "like", "nlike"}, opStr) {- // check if it's not body- key, ok := itemMap["key"].(map[string]string)- if ok && key["key"] != "body" {- logsPanelsWithAttrContains++- }- }- }- }- }- }- }- return logsPanelsWithAttrContains-}--// deprecated: remove this function in the next major release-func countPanelsInDashboard(inputData map[string]interface{}) model.DashboardsInfo {- var logsPanelCount, tracesPanelCount, metricsPanelCount, logsPanelsWithAttrContains int- traceChQueryCount := 0- logChQueryCount := 0-- // totalPanels := 0- if inputData != nil && inputData["widgets"] != nil {- widgets, ok := inputData["widgets"]- if ok {- data, ok := widgets.([]interface{})- if ok {- for _, widget := range data {- sData, ok := widget.(map[string]interface{})- if ok && sData["query"] != nil {- // totalPanels++- query, ok := sData["query"].(map[string]interface{})- if ok && query["queryType"] == "builder" && query["builder"] != nil {- builderData, ok := query["builder"].(map[string]interface{})- if ok && builderData["queryData"] != nil {- builderQueryData, ok := builderData["queryData"].([]interface{})- if ok {- for _, queryData := range builderQueryData {- data, ok := queryData.(map[string]interface{})- if ok {- if data["dataSource"] == "traces" {- tracesPanelCount++- } else if data["dataSource"] == "metrics" {- metricsPanelCount++- } else if data["dataSource"] == "logs" {- logsPanelCount++- logsPanelsWithAttrContains += checkLogPanelAttrContains(data)- }- }- }- }- }- } else if ok && query["queryType"] == "clickhouse_sql" && query["clickhouse_sql"] != nil {- if isDashboardWithLogsClickhouseQuery(inputData) {- logChQueryCount = 1- }- if isDashboardWithTracesClickhouseQuery(inputData) {- traceChQueryCount = 1- }- }- }- }- }- }- }-- return model.DashboardsInfo{- LogsBasedPanels: logsPanelCount,- TracesBasedPanels: tracesPanelCount,- MetricBasedPanels: metricsPanelCount,-- DashboardsWithLogsChQuery: logChQueryCount,- DashboardsWithTraceChQuery: traceChQueryCount,- LogsPanelsWithAttrContainsOp: logsPanelsWithAttrContains,- }-}diff --git a/pkg/query-service/telemetry/ignored.go b/pkg/query-service/telemetry/ignored.godeleted file mode 100644index aba1f08587..0000000000--- a/pkg/query-service/telemetry/ignored.go+++ /dev/null@@ -1,16 +0,0 @@-package telemetry--// deprecated: remove this function in the next major release-func ignoreEvents(event string, attributes map[string]interface{}) bool {- if event == TELEMETRY_EVENT_ACTIVE_USER {- for attr_key, attr_val := range attributes {-- if attr_key == "any" && attr_val.(int8) == 0 {- return true- }-- }- }-- return false-}diff --git a/pkg/query-service/telemetry/rule.go b/pkg/query-service/telemetry/rule.godeleted file mode 100644index 538aeaf748..0000000000--- a/pkg/query-service/telemetry/rule.go+++ /dev/null@@ -1,142 +0,0 @@-package telemetry--import (- "context"- "encoding/json"- "slices"- "strings"-- "github.com/SigNoz/signoz/pkg/query-service/model"- v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"- "github.com/SigNoz/signoz/pkg/sqlstore"- "github.com/SigNoz/signoz/pkg/types/alertmanagertypes"- "github.com/SigNoz/signoz/pkg/types/ruletypes"- "go.uber.org/zap"-)--// deprecated: remove this function in the next major release-func getChannels(ctx context.Context, sqlstore sqlstore.SQLStore) ([]*alertmanagertypes.Channel, error) {- channels := []*alertmanagertypes.Channel{}- if err := sqlstore.BunDB().NewSelect().Model(&channels).Scan(ctx); err != nil {- return nil, err- }-- return channels, nil-}--// deprecated: remove this function in the next major release-func GetAlertsInfo(ctx context.Context, sqlstore sqlstore.SQLStore) (*model.AlertsInfo, error) {- alertsInfo := model.AlertsInfo{}-- var alertsData []string- var alertNames []string- err := sqlstore.BunDB().NewSelect().Model((*ruletypes.Rule)(nil)).Column("data").Scan(ctx, &alertsData)- if err != nil {- zap.L().Error("Error in processing sql query", zap.Error(err))- return &alertsInfo, err- }- for _, alert := range alertsData {- var rule ruletypes.GettableRule- if strings.Contains(alert, "time_series_v2") {- alertsInfo.AlertsWithTSV2 = alertsInfo.AlertsWithTSV2 + 1- }- err = json.Unmarshal([]byte(alert), &rule)- if err != nil {- zap.L().Error("invalid rule data", zap.Error(err))- continue- }- alertNames = append(alertNames, rule.AlertName)- if rule.AlertType == ruletypes.AlertTypeLogs {- alertsInfo.LogsBasedAlerts = alertsInfo.LogsBasedAlerts + 1-- if rule.RuleCondition != nil && rule.RuleCondition.CompositeQuery != nil {- if rule.RuleCondition.CompositeQuery.QueryType == v3.QueryTypeClickHouseSQL {- if strings.Contains(alert, "signoz_logs.distributed_logs") ||- strings.Contains(alert, "signoz_logs.logs") {- alertsInfo.AlertsWithLogsChQuery = alertsInfo.AlertsWithLogsChQuery + 1- }- }- }-- for _, query := range rule.RuleCondition.CompositeQuery.BuilderQueries {- if rule.RuleCondition.CompositeQuery.QueryType == v3.QueryTypeBuilder {- if query.Filters != nil {- for _, item := range query.Filters.Items {- if slices.Contains([]string{"contains", "ncontains", "like", "nlike"}, string(item.Operator)) {- if item.Key.Key != "body" {- alertsInfo.AlertsWithLogsContainsOp += 1- }- }- }- }- }- }- } else if rule.AlertType == ruletypes.AlertTypeMetric {- alertsInfo.MetricBasedAlerts = alertsInfo.MetricBasedAlerts + 1- if rule.RuleCondition != nil && rule.RuleCondition.CompositeQuery != nil {- if rule.RuleCondition.CompositeQuery.QueryType == v3.QueryTypeBuilder {- alertsInfo.MetricsBuilderQueries = alertsInfo.MetricsBuilderQueries + 1- } else if rule.RuleCondition.CompositeQuery.QueryType == v3.QueryTypeClickHouseSQL {- alertsInfo.MetricsClickHouseQueries = alertsInfo.MetricsClickHouseQueries + 1- } else if rule.RuleCondition.CompositeQuery.QueryType == v3.QueryTypePromQL {- alertsInfo.MetricsPrometheusQueries = alertsInfo.MetricsPrometheusQueries + 1- for _, query := range rule.RuleCondition.CompositeQuery.PromQueries {- if strings.Contains(query.Query, "signoz_") {- alertsInfo.SpanMetricsPrometheusQueries = alertsInfo.SpanMetricsPrometheusQueries + 1- }- }- }- }- if rule.RuleType == ruletypes.RuleTypeAnomaly {- alertsInfo.AnomalyBasedAlerts = alertsInfo.AnomalyBasedAlerts + 1- }- } else if rule.AlertType == ruletypes.AlertTypeTraces {- alertsInfo.TracesBasedAlerts = alertsInfo.TracesBasedAlerts + 1-- if rule.RuleCondition != nil && rule.RuleCondition.CompositeQuery != nil {- if rule.RuleCondition.CompositeQuery.QueryType == v3.QueryTypeClickHouseSQL {- if strings.Contains(alert, "signoz_traces.distributed_signoz_index_v2") ||- strings.Contains(alert, "signoz_traces.distributed_signoz_spans") ||- strings.Contains(alert, "signoz_traces.distributed_signoz_error_index_v2") {- alertsInfo.AlertsWithTraceChQuery = alertsInfo.AlertsWithTraceChQuery + 1- }- }- }- }- alertsInfo.TotalAlerts = alertsInfo.TotalAlerts + 1- if !rule.PostableRule.Disabled {- alertsInfo.TotalActiveAlerts = alertsInfo.TotalActiveAlerts + 1- }- }- alertsInfo.AlertNames = alertNames-- channels, err := getChannels(ctx, sqlstore)- if err != nil {- return &alertsInfo, err- }- if channels != nil {- alertsInfo.TotalChannels = len(channels)- for _, channel := range channels {- if channel.Type == "slack" {- alertsInfo.SlackChannels = alertsInfo.SlackChannels + 1- }- if channel.Type == "webhook" {- alertsInfo.WebHookChannels = alertsInfo.WebHookChannels + 1- }- if channel.Type == "email" {- alertsInfo.EmailChannels = alertsInfo.EmailChannels + 1- }- if channel.Type == "pagerduty" {- alertsInfo.PagerDutyChannels = alertsInfo.PagerDutyChannels + 1- }- if channel.Type == "opsgenie" {- alertsInfo.OpsGenieChannels = alertsInfo.OpsGenieChannels + 1- }- if channel.Type == "msteams" {- alertsInfo.MSTeamsChannels = alertsInfo.MSTeamsChannels + 1- }- }- }-- return &alertsInfo, nil-}diff --git a/pkg/query-service/telemetry/saved_view.go b/pkg/query-service/telemetry/saved_view.godeleted file mode 100644index d15cf110de..0000000000--- a/pkg/query-service/telemetry/saved_view.go+++ /dev/null@@ -1,89 +0,0 @@-package telemetry--import (- "context"- "encoding/json"- "fmt"- "slices"- "strings"-- "github.com/SigNoz/signoz/pkg/query-service/model"- v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"- "github.com/SigNoz/signoz/pkg/sqlstore"- "github.com/SigNoz/signoz/pkg/types"- "go.uber.org/zap"-)--// deprecated: remove this function in the next major release-func GetViews(ctx context.Context, sqlstore sqlstore.SQLStore, orgID string) ([]*v3.SavedView, error) {- var views []types.SavedView- err := sqlstore.BunDB().NewSelect().Model(&views).Where("org_id = ?", orgID).Scan(ctx)- if err != nil {- return nil, fmt.Errorf("error in getting saved views: %s", err.Error())- }-- var savedViews []*v3.SavedView- for _, view := range views {- var compositeQuery v3.CompositeQuery- err = json.Unmarshal([]byte(view.Data), &compositeQuery)- if err != nil {- return nil, fmt.Errorf("error in unmarshalling explorer query data: %s", err.Error())- }- savedViews = append(savedViews, &v3.SavedView{- ID: view.ID,- Name: view.Name,- Category: view.Category,- CreatedAt: view.CreatedAt,- CreatedBy: view.CreatedBy,- UpdatedAt: view.UpdatedAt,- UpdatedBy: view.UpdatedBy,- Tags: strings.Split(view.Tags, ","),- SourcePage: view.SourcePage,- CompositeQuery: &compositeQuery,- ExtraData: view.ExtraData,- })- }- return savedViews, nil-}--// deprecated: remove this function in the next major release-func GetSavedViewsInfo(ctx context.Context, sqlstore sqlstore.SQLStore) (*model.SavedViewsInfo, error) {- savedViewsInfo := model.SavedViewsInfo{}- // get single org ID from db- var orgIDs []string- err := sqlstore.BunDB().NewSelect().Model((*types.Organization)(nil)).Column("id").Scan(ctx, &orgIDs)- if err != nil {- return nil, fmt.Errorf("error in getting org IDs: %s", err.Error())- }- if len(orgIDs) != 1 {- zap.S().Warn("GetSavedViewsInfo: Zero or multiple org IDs found in the database", zap.Int("orgIDs", len(orgIDs)))- return &savedViewsInfo, nil- }- savedViews, err := GetViews(ctx, sqlstore, orgIDs[0])- if err != nil {- zap.S().Debug("Error in fetching saved views info: ", err)- return &savedViewsInfo, err- }-- savedViewsInfo.TotalSavedViews = len(savedViews)- for _, view := range savedViews {- if view.SourcePage == "traces" {- savedViewsInfo.TracesSavedViews += 1- } else if view.SourcePage == "logs" {- savedViewsInfo.LogsSavedViews += 1-- for _, query := range view.CompositeQuery.BuilderQueries {- if query.Filters != nil {- for _, item := range query.Filters.Items {- if slices.Contains([]string{"contains", "ncontains", "like", "nlike"}, string(item.Operator)) {- if item.Key.Key != "body" {- savedViewsInfo.LogsSavedViewWithContainsOp += 1- }- }- }- }- }- }- }- return &savedViewsInfo, nil-}diff --git a/pkg/query-service/telemetry/telemetry.go b/pkg/query-service/telemetry/telemetry.godeleted file mode 100644index d80b8b758c..0000000000--- a/pkg/query-service/telemetry/telemetry.go+++ /dev/null@@ -1,846 +0,0 @@-package telemetry--import (- "context"- "io"- "math/rand"- "net/http"- "os"- "strings"- "sync"- "testing"- "time"-- "github.com/go-co-op/gocron"- analytics "github.com/segmentio/analytics-go/v3"- "go.uber.org/zap"-- "github.com/SigNoz/signoz/pkg/query-service/constants"- "github.com/SigNoz/signoz/pkg/query-service/interfaces"- "github.com/SigNoz/signoz/pkg/query-service/model"- v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"- "github.com/SigNoz/signoz/pkg/sqlstore"- "github.com/SigNoz/signoz/pkg/types"- "github.com/SigNoz/signoz/pkg/version"-)--const (- TELEMETRY_EVENT_PATH = "API Call"- TELEMETRY_EVENT_USER = "User"- TELEMETRY_EVENT_INPRODUCT_FEEDBACK = "InProduct Feedback Submitted"- TELEMETRY_EVENT_NUMBER_OF_SERVICES = "Number of Services"- TELEMETRY_EVENT_HEART_BEAT = "Heart Beat"- TELEMETRY_EVENT_ORG_SETTINGS = "Org Settings"- DEFAULT_SAMPLING = 0.1- TELEMETRY_LICENSE_CHECK_FAILED = "License Check Failed"- TELEMETRY_LICENSE_UPDATED = "License Updated"- TELEMETRY_LICENSE_ACT_FAILED = "License Activation Failed"- TELEMETRY_EVENT_ENVIRONMENT = "Environment"- TELEMETRY_EVENT_LANGUAGE = "Language"- TELEMETRY_EVENT_SERVICE = "ServiceName"- TELEMETRY_EVENT_LOGS_FILTERS = "Logs Filters"- TELEMETRY_EVENT_LARGE_TRACE_OPENED = "Large Trace Opened"- TELEMETRY_EVENT_TRACE_DETAIL_API = "Trace Detail API"- TELEMETRY_EVENT_MAX_SPANS_ALLOWED_LIMIT_REACHED = "Max spans in a trace limit reached"- TELEMETRY_EVENT_DISTRIBUTED = "Distributed"- TELEMETRY_EVENT_QUERY_RANGE_API = "Query Range API"- TELEMETRY_EVENT_DASHBOARDS_ALERTS = "Dashboards/Alerts Info"- TELEMETRY_EVENT_ACTIVE_USER = "Active User"- TELEMETRY_EVENT_USER_INVITATION_SENT = "User Invitation Sent"- TELEMETRY_EVENT_USER_INVITATION_ACCEPTED = "User Invitation Accepted"- TELEMETRY_EVENT_SUCCESSFUL_DASHBOARD_PANEL_QUERY = "Successful Dashboard Panel Query"- TELEMETRY_EVENT_SUCCESSFUL_ALERT_QUERY = "Successful Alert Query"- DEFAULT_CLOUD_EMAIL = "[email protected]"-)--var SAAS_EVENTS_LIST = map[string]struct{}{- TELEMETRY_EVENT_NUMBER_OF_SERVICES: {},- TELEMETRY_EVENT_HEART_BEAT: {},- TELEMETRY_EVENT_LANGUAGE: {},- TELEMETRY_EVENT_SERVICE: {},- TELEMETRY_EVENT_ENVIRONMENT: {},- TELEMETRY_EVENT_USER_INVITATION_SENT: {},- TELEMETRY_EVENT_USER_INVITATION_ACCEPTED: {},- TELEMETRY_EVENT_DASHBOARDS_ALERTS: {},- TELEMETRY_EVENT_SUCCESSFUL_DASHBOARD_PANEL_QUERY: {},- TELEMETRY_EVENT_SUCCESSFUL_ALERT_QUERY: {},- TELEMETRY_EVENT_QUERY_RANGE_API: {},- TELEMETRY_EVENT_MAX_SPANS_ALLOWED_LIMIT_REACHED: {},- TELEMETRY_EVENT_LARGE_TRACE_OPENED: {},- TELEMETRY_EVENT_TRACE_DETAIL_API: {},-}--var OSS_EVENTS_LIST = map[string]struct{}{- TELEMETRY_EVENT_NUMBER_OF_SERVICES: {},- TELEMETRY_EVENT_HEART_BEAT: {},- TELEMETRY_EVENT_LANGUAGE: {},- TELEMETRY_EVENT_ENVIRONMENT: {},- TELEMETRY_EVENT_DASHBOARDS_ALERTS: {},- TELEMETRY_EVENT_ACTIVE_USER: {},- TELEMETRY_EVENT_PATH: {},- TELEMETRY_EVENT_ORG_SETTINGS: {},- TELEMETRY_LICENSE_CHECK_FAILED: {},- TELEMETRY_LICENSE_UPDATED: {},- TELEMETRY_LICENSE_ACT_FAILED: {},-}--type QueryInfoResult struct {- LogsUsed bool- MetricsUsed bool- TracesUsed bool- FilterApplied bool- GroupByApplied bool- AggregateOperator v3.AggregateOperator- AggregateAttributeKey string- QueryType v3.QueryType- PanelType v3.PanelType- NumberOfQueries int-}--const api_key = "9kRrJ7oPCGPEJLF6QjMPLt5bljFhRQBr"--const IP_NOT_FOUND_PLACEHOLDER = "NA"-const DEFAULT_NUMBER_OF_SERVICES = 6--const SCHEDULE_START_TIME = "04:00" // 4 AM UTC--const RATE_LIMIT_CHECK_DURATION = 1 * time.Minute-const RATE_LIMIT_VALUE = 1--var telemetry *Telemetry-var once sync.Once--// deprecated: remove this function in the next major release-func (a *Telemetry) IsSampled() bool {-- random_number := a.minRandInt + rand.Intn(a.maxRandInt-a.minRandInt) + 1-- if (random_number % a.maxRandInt) == 0 {- return true- } else {- return false- }--}--// deprecated: remove this function in the next major release-func (telemetry *Telemetry) CheckQueryInfo(postData *v3.QueryRangeParamsV3) QueryInfoResult {- queryInfoResult := QueryInfoResult{}- if postData != nil && postData.CompositeQuery != nil {- queryInfoResult.PanelType = postData.CompositeQuery.PanelType- queryInfoResult.QueryType = postData.CompositeQuery.QueryType- if postData.CompositeQuery.QueryType == v3.QueryTypeBuilder {- queryInfoResult.NumberOfQueries = len(postData.CompositeQuery.BuilderQueries)- for _, query := range postData.CompositeQuery.BuilderQueries {- if query.DataSource == v3.DataSourceLogs {- queryInfoResult.LogsUsed = true- } else if query.DataSource == v3.DataSourceMetrics {- queryInfoResult.MetricsUsed = true-- } else if query.DataSource == v3.DataSourceTraces {- queryInfoResult.TracesUsed = true- }- if query.Filters != nil && len(query.Filters.Items) > 0 {- queryInfoResult.FilterApplied = true- }- if query.GroupBy != nil && len(query.GroupBy) > 0 {- queryInfoResult.GroupByApplied = true- }- queryInfoResult.AggregateOperator = query.AggregateOperator- if len(query.AggregateAttribute.Key) > 0 && !strings.Contains(query.AggregateAttribute.Key, "signoz_") {- queryInfoResult.AggregateAttributeKey = query.AggregateAttribute.Key- }- }- } else if postData.CompositeQuery.QueryType == v3.QueryTypePromQL {- for _, query := range postData.CompositeQuery.PromQueries {- if !strings.Contains(query.Query, "signoz_") && len(query.Query) > 0 {- queryInfoResult.MetricsUsed = true- }- }- } else if postData.CompositeQuery.QueryType == v3.QueryTypeClickHouseSQL {- for _, query := range postData.CompositeQuery.ClickHouseQueries {- if strings.Contains(query.Query, "signoz_metrics") && len(query.Query) > 0 {- queryInfoResult.MetricsUsed = true- }- if strings.Contains(query.Query, "signoz_logs") && len(query.Query) > 0 {- queryInfoResult.LogsUsed = true- }- if strings.Contains(query.Query, "signoz_traces") && len(query.Query) > 0 {- queryInfoResult.TracesUsed = true- }- }- }- }- return queryInfoResult-}--// deprecated: remove this function in the next major release-func (telemetry *Telemetry) AddActiveTracesUser() {- telemetry.mutex.Lock()- telemetry.activeUser["traces"] = 1- telemetry.mutex.Unlock()-}--// deprecated: remove this function in the next major release-func (telemetry *Telemetry) AddActiveMetricsUser() {- telemetry.mutex.Lock()- telemetry.activeUser["metrics"] = 1- telemetry.mutex.Unlock()-}--// deprecated: remove this function in the next major release-func (telemetry *Telemetry) AddActiveLogsUser() {- telemetry.mutex.Lock()- telemetry.activeUser["logs"] = 1- telemetry.mutex.Unlock()-}--// deprecated: remove this function in the next major release-type Telemetry struct {- ossOperator analytics.Client- saasOperator analytics.Client- ipAddress string- userEmail string- isEnabled bool- isAnonymous bool- reader interfaces.Reader- sqlStore sqlstore.SQLStore- companyDomain string- minRandInt int- maxRandInt int- rateLimits map[string]int8- activeUser map[string]int8- patTokenUser bool- mutex sync.RWMutex-- alertsInfoCallback func(ctx context.Context, store sqlstore.SQLStore) (*model.AlertsInfo, error)- userCountCallback func(ctx context.Context, store sqlstore.SQLStore) (int, error)- getUsersCallback func(ctx context.Context, store sqlstore.SQLStore) ([]TelemetryUser, error)- dashboardsInfoCallback func(ctx context.Context, store sqlstore.SQLStore) (*model.DashboardsInfo, error)- savedViewsInfoCallback func(ctx context.Context, store sqlstore.SQLStore) (*model.SavedViewsInfo, error)-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetAlertsInfoCallback(callback func(ctx context.Context, store sqlstore.SQLStore) (*model.AlertsInfo, error)) {- a.alertsInfoCallback = callback-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetUserCountCallback(callback func(ctx context.Context, store sqlstore.SQLStore) (int, error)) {- a.userCountCallback = callback-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetGetUsersCallback(callback func(ctx context.Context, store sqlstore.SQLStore) ([]TelemetryUser, error)) {- a.getUsersCallback = callback-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetSavedViewsInfoCallback(callback func(ctx context.Context, store sqlstore.SQLStore) (*model.SavedViewsInfo, error)) {- a.savedViewsInfoCallback = callback-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetDashboardsInfoCallback(callback func(ctx context.Context, store sqlstore.SQLStore) (*model.DashboardsInfo, error)) {- a.dashboardsInfoCallback = callback-}--// deprecated: remove this function in the next major release-func createTelemetry() {- // Do not do anything in CI (not even resolving the outbound IP address)- if testing.Testing() {- telemetry = &Telemetry{- isEnabled: false,- }- return- }-- if constants.IsOSSTelemetryEnabled() {- telemetry = &Telemetry{- ossOperator: analytics.New(api_key),- ipAddress: getOutboundIP(),- rateLimits: make(map[string]int8),- activeUser: make(map[string]int8),- }- } else {- telemetry = &Telemetry{- ipAddress: getOutboundIP(),- rateLimits: make(map[string]int8),- activeUser: make(map[string]int8),- }- }- telemetry.minRandInt = 0- telemetry.maxRandInt = int(1 / DEFAULT_SAMPLING)-- telemetry.SetTelemetryEnabled(constants.IsTelemetryEnabled())-- // Create a new scheduler- s := gocron.NewScheduler(time.UTC)-- HEART_BEAT_DURATION := time.Duration(constants.TELEMETRY_HEART_BEAT_DURATION_MINUTES) * time.Minute- ACTIVE_USER_DURATION := time.Duration(constants.TELEMETRY_ACTIVE_USER_DURATION_MINUTES) * time.Minute-- rateLimitTicker := time.NewTicker(RATE_LIMIT_CHECK_DURATION)-- go func() {- //lint:ignore S1000 false positive- for {- select {- case <-rateLimitTicker.C:- telemetry.rateLimits = make(map[string]int8)- }- }- }()- ctx := context.Background()- // Define heartbeat function- heartbeatFunc := func() {- tagsInfo, err := telemetry.reader.GetTagsInfoInLastHeartBeatInterval(ctx, HEART_BEAT_DURATION)- if err != nil {- zap.L().Error("heartbeatFunc: failed to get tags info", zap.Error(err))- return- }-- if len(tagsInfo.Env) != 0 {- telemetry.SendEvent(TELEMETRY_EVENT_ENVIRONMENT, map[string]interface{}{"value": tagsInfo.Env}, "", true, false)- }-- languages := []string{}- for language := range tagsInfo.Languages {- languages = append(languages, language)- }- if len(languages) > 0 {- telemetry.SendEvent(TELEMETRY_EVENT_LANGUAGE, map[string]interface{}{"language": languages}, "", true, false)- }- services := []string{}- for service := range tagsInfo.Services {- services = append(services, service)- }- if len(services) > 0 {- telemetry.SendEvent(TELEMETRY_EVENT_SERVICE, map[string]interface{}{"serviceName": services}, "", true, false)- }- totalSpans, _ := telemetry.reader.GetTotalSpans(ctx)- totalLogs, _ := telemetry.reader.GetTotalLogs(ctx)- spansInLastHeartBeatInterval, _ := telemetry.reader.GetSpansInLastHeartBeatInterval(ctx, HEART_BEAT_DURATION)- getSamplesInfoInLastHeartBeatInterval, _ := telemetry.reader.GetSamplesInfoInLastHeartBeatInterval(ctx, HEART_BEAT_DURATION)- totalSamples, _ := telemetry.reader.GetTotalSamples(ctx)- tsInfo, _ := telemetry.reader.GetTimeSeriesInfo(ctx)-- getLogsInfoInLastHeartBeatInterval, _ := telemetry.reader.GetLogsInfoInLastHeartBeatInterval(ctx, HEART_BEAT_DURATION)-- // TODO update this post bootstrap decision- traceTTL, _ := telemetry.reader.GetTTL(ctx, "", &model.GetTTLParams{Type: constants.TraceTTL})- metricsTTL, _ := telemetry.reader.GetTTL(ctx, "", &model.GetTTLParams{Type: constants.MetricsTTL})- logsTTL, _ := telemetry.reader.GetTTL(ctx, "", &model.GetTTLParams{Type: constants.LogsTTL})-- userCount, _ := telemetry.userCountCallback(ctx, telemetry.sqlStore)-- data := map[string]interface{}{- "totalSpans": totalSpans,- "spansInLastHeartBeatInterval": spansInLastHeartBeatInterval,- "totalSamples": totalSamples,- "getSamplesInfoInLastHeartBeatInterval": getSamplesInfoInLastHeartBeatInterval,- "totalLogs": totalLogs,- "getLogsInfoInLastHeartBeatInterval": getLogsInfoInLastHeartBeatInterval,- "countUsers": userCount,- "metricsTTLStatus": metricsTTL.Status,- "metricsTTLValue": metricsTTL.MetricsMoveTime,- "tracesTTLStatus": traceTTL.Status,- "traceTTLValue": traceTTL.TracesTime,- "logsTTLStatus": logsTTL.Status,- "logsTTLValue": logsTTL.LogsTime,- "patUser": telemetry.patTokenUser,- }- telemetry.patTokenUser = false- for key, value := range tsInfo {- data[key] = value- }-- users, apiErr := telemetry.getUsersCallback(ctx, telemetry.sqlStore)- if apiErr == nil {- for _, user := range users {- if user.Email == DEFAULT_CLOUD_EMAIL {- continue- }- telemetry.SendEvent(TELEMETRY_EVENT_HEART_BEAT, data, user.Email, false, false)- }- }-- alertsInfo, err := telemetry.alertsInfoCallback(ctx, telemetry.sqlStore)- if err != nil {- telemetry.SendEvent(TELEMETRY_EVENT_DASHBOARDS_ALERTS, map[string]interface{}{"error": err.Error()}, "", true, false)- }- if err == nil {- dashboardsInfo, err := telemetry.dashboardsInfoCallback(ctx, telemetry.sqlStore)- if err == nil {- savedViewsInfo, err := telemetry.savedViewsInfoCallback(ctx, telemetry.sqlStore)- if err == nil {- dashboardsAlertsData := map[string]interface{}{- "totalDashboards": dashboardsInfo.TotalDashboards,- "totalDashboardsWithPanelAndName": dashboardsInfo.TotalDashboardsWithPanelAndName,- "dashboardNames": dashboardsInfo.DashboardNames,- "alertNames": alertsInfo.AlertNames,- "logsBasedPanels": dashboardsInfo.LogsBasedPanels,- "logsPanelsWithAttrContains": dashboardsInfo.LogsPanelsWithAttrContainsOp,- "metricBasedPanels": dashboardsInfo.MetricBasedPanels,- "tracesBasedPanels": dashboardsInfo.TracesBasedPanels,- "dashboardsWithTSV2": dashboardsInfo.QueriesWithTSV2,- "dashboardsWithTagAttrs": dashboardsInfo.QueriesWithTagAttrs,- "dashboardWithLogsChQuery": dashboardsInfo.DashboardsWithLogsChQuery,- "dashboardWithTraceChQuery": dashboardsInfo.DashboardsWithTraceChQuery,- "dashboardNamesWithTraceChQuery": dashboardsInfo.DashboardNamesWithTraceChQuery,- "totalAlerts": alertsInfo.TotalAlerts,- "totalActiveAlerts": alertsInfo.TotalActiveAlerts,- "alertsWithTSV2": alertsInfo.AlertsWithTSV2,- "logsBasedAlerts": alertsInfo.LogsBasedAlerts,- "metricBasedAlerts": alertsInfo.MetricBasedAlerts,- "anomalyBasedAlerts": alertsInfo.AnomalyBasedAlerts,- "tracesBasedAlerts": alertsInfo.TracesBasedAlerts,- "totalChannels": alertsInfo.TotalChannels,- "totalSavedViews": savedViewsInfo.TotalSavedViews,- "logsSavedViews": savedViewsInfo.LogsSavedViews,- "tracesSavedViews": savedViewsInfo.TracesSavedViews,- "logSavedViewsWithContainsOp": savedViewsInfo.LogsSavedViewWithContainsOp,- "slackChannels": alertsInfo.SlackChannels,- "webHookChannels": alertsInfo.WebHookChannels,- "pagerDutyChannels": alertsInfo.PagerDutyChannels,- "opsGenieChannels": alertsInfo.OpsGenieChannels,- "emailChannels": alertsInfo.EmailChannels,- "msteamsChannels": alertsInfo.MSTeamsChannels,- "metricsBuilderQueries": alertsInfo.MetricsBuilderQueries,- "metricsClickHouseQueries": alertsInfo.MetricsClickHouseQueries,- "metricsPrometheusQueries": alertsInfo.MetricsPrometheusQueries,- "spanMetricsPrometheusQueries": alertsInfo.SpanMetricsPrometheusQueries,- "alertsWithLogsChQuery": alertsInfo.AlertsWithLogsChQuery,- "alertsWithLogsContainsOp": alertsInfo.AlertsWithLogsContainsOp,- "alertsWithTraceChQuery": alertsInfo.AlertsWithTraceChQuery,- }- // send event only if there are dashboards or alerts or channels- if (dashboardsInfo.TotalDashboards > 0 || alertsInfo.TotalAlerts > 0 || alertsInfo.TotalChannels > 0 || savedViewsInfo.TotalSavedViews > 0) && apiErr == nil {- for _, user := range users {- if user.Email == DEFAULT_CLOUD_EMAIL {- continue- }- telemetry.SendEvent(TELEMETRY_EVENT_DASHBOARDS_ALERTS, dashboardsAlertsData, user.Email, false, false)- }- }- telemetry.SendIdentifyEvent(map[string]interface{}{- "total_logs": totalLogs,- "total_traces": totalSpans,- "total_metrics": totalSamples,- "total_users": userCount,- "total_channels": alertsInfo.TotalChannels,- "total_dashboards_with_panel": dashboardsInfo.TotalDashboardsWithPanelAndName,- "total_saved_views": savedViewsInfo.TotalSavedViews,- "total_active_alerts": alertsInfo.TotalActiveAlerts,- "total_traces_based_alerts": alertsInfo.TracesBasedAlerts,- "total_logs_based_alerts": alertsInfo.LogsBasedAlerts,- "total_metric_based_alerts": alertsInfo.MetricBasedAlerts,- "total_anomaly_based_alerts": alertsInfo.AnomalyBasedAlerts,- "total_metrics_based_panels": dashboardsInfo.MetricBasedPanels,- "total_logs_based_panels": dashboardsInfo.LogsBasedPanels,- "total_traces_based_panels": dashboardsInfo.TracesBasedPanels,- }, "")- telemetry.SendGroupEvent(map[string]interface{}{- "total_logs": totalLogs,- "total_traces": totalSpans,- "total_metrics": totalSamples,- "total_users": userCount,- "total_channels": alertsInfo.TotalChannels,- "total_dashboards_with_panel": dashboardsInfo.TotalDashboardsWithPanelAndName,- "total_saved_views": savedViewsInfo.TotalSavedViews,- "total_active_alerts": alertsInfo.TotalActiveAlerts,- "total_traces_based_alerts": alertsInfo.TracesBasedAlerts,- "total_logs_based_alerts": alertsInfo.LogsBasedAlerts,- "total_metric_based_alerts": alertsInfo.MetricBasedAlerts,- "total_anomaly_based_alerts": alertsInfo.AnomalyBasedAlerts,- "total_metrics_based_panels": dashboardsInfo.MetricBasedPanels,- "total_logs_based_panels": dashboardsInfo.LogsBasedPanels,- "total_traces_based_panels": dashboardsInfo.TracesBasedPanels,- }, "")- }- }- }-- if totalLogs > 0 {- telemetry.SendIdentifyEvent(map[string]interface{}{"sent_logs": true}, "")- telemetry.SendGroupEvent(map[string]interface{}{"sent_logs": true}, "")- }- if totalSpans > 0 {- telemetry.SendIdentifyEvent(map[string]interface{}{"sent_traces": true}, "")- telemetry.SendGroupEvent(map[string]interface{}{"sent_traces": true}, "")- }- if totalSamples > 0 {- telemetry.SendIdentifyEvent(map[string]interface{}{"sent_metrics": true}, "")- telemetry.SendGroupEvent(map[string]interface{}{"sent_metrics": true}, "")- }-- getDistributedInfoInLastHeartBeatInterval, _ := telemetry.reader.GetDistributedInfoInLastHeartBeatInterval(ctx)- telemetry.SendEvent(TELEMETRY_EVENT_DISTRIBUTED, getDistributedInfoInLastHeartBeatInterval, "", true, false)- }-- // Define active user function- activeUserFunc := func() {- if telemetry.activeUser["logs"] != 0 {- getLogsInfoInLastHeartBeatInterval, err := telemetry.reader.GetLogsInfoInLastHeartBeatInterval(ctx, ACTIVE_USER_DURATION)- if err != nil && getLogsInfoInLastHeartBeatInterval == 0 {- telemetry.activeUser["logs"] = 0- }- }- if telemetry.activeUser["metrics"] != 0 {- getSamplesInfoInLastHeartBeatInterval, err := telemetry.reader.GetSamplesInfoInLastHeartBeatInterval(ctx, ACTIVE_USER_DURATION)- if err != nil && getSamplesInfoInLastHeartBeatInterval == 0 {- telemetry.activeUser["metrics"] = 0- }- }- if (telemetry.activeUser["traces"] != 0) || (telemetry.activeUser["metrics"] != 0) || (telemetry.activeUser["logs"] != 0) {- telemetry.activeUser["any"] = 1- }- telemetry.SendEvent(TELEMETRY_EVENT_ACTIVE_USER, map[string]interface{}{- "traces": telemetry.activeUser["traces"],- "metrics": telemetry.activeUser["metrics"],- "logs": telemetry.activeUser["logs"],- "any": telemetry.activeUser["any"]},- "", true, false)- telemetry.activeUser = map[string]int8{"traces": 0, "metrics": 0, "logs": 0, "any": 0}- }-- // Calculate next run time based on duration and start time- calculateNextRun := func(duration time.Duration, startTimeStr string) time.Time {- now := time.Now().UTC()- startTime, _ := time.Parse("15:04", startTimeStr)- todayStartTime := time.Date(now.Year(), now.Month(), now.Day(), startTime.Hour(), startTime.Minute(), 0, 0, time.UTC)-- if now.Before(todayStartTime) {- todayStartTime = todayStartTime.Add(-24 * time.Hour)- }-- diff := now.Sub(todayStartTime)- intervalsPassed := int(diff / duration)- nextRun := todayStartTime.Add(time.Duration(intervalsPassed+1) * duration)-- return nextRun- }-- // Schedule next runs- scheduleNextRuns := func() {- nextHeartbeat := calculateNextRun(HEART_BEAT_DURATION, SCHEDULE_START_TIME)- nextActiveUser := calculateNextRun(ACTIVE_USER_DURATION, SCHEDULE_START_TIME)-- _, _ = s.Every(HEART_BEAT_DURATION).StartAt(nextHeartbeat).Do(heartbeatFunc)- _, _ = s.Every(ACTIVE_USER_DURATION).StartAt(nextActiveUser).Do(activeUserFunc)- }-- // Schedule immediate execution and subsequent runs- scheduleNextRuns()-- // Start the scheduler in a separate goroutine- go s.StartBlocking()-}--// deprecated: remove this function in the next major release-func getOutboundIP() string {-- ip := []byte(IP_NOT_FOUND_PLACEHOLDER)- resp, err := http.Get("https://api.ipify.org?format=text")-- if err != nil {- return string(ip)- }-- defer resp.Body.Close()- ipBody, err := io.ReadAll(resp.Body)- if err == nil {- ip = ipBody- }-- return string(ip)-}--// deprecated: remove this function in the next major release-func (a *Telemetry) IdentifyUser(user *types.User) {- if user.Email == DEFAULT_CLOUD_EMAIL {- return- }- a.SetCompanyDomain(user.Email)- a.SetUserEmail(user.Email)- if !a.isTelemetryEnabled() || a.isTelemetryAnonymous() {- return- }-- if a.saasOperator != nil {- _ = a.saasOperator.Enqueue(analytics.Identify{- UserId: a.userEmail,- Traits: analytics.NewTraits().SetName(user.DisplayName).SetEmail(user.Email).Set("role", user.Role),- })-- _ = a.saasOperator.Enqueue(analytics.Group{- UserId: a.userEmail,- GroupId: a.getCompanyDomain(),- Traits: analytics.NewTraits().Set("company_domain", a.getCompanyDomain()),- })- }-- if a.ossOperator != nil {- _ = a.ossOperator.Enqueue(analytics.Identify{- UserId: a.ipAddress,- Traits: analytics.NewTraits().SetName(user.DisplayName).SetEmail(user.Email).Set("ip", a.ipAddress),- })- // Updating a groups properties- _ = a.ossOperator.Enqueue(analytics.Group{- UserId: a.ipAddress,- GroupId: a.getCompanyDomain(),- Traits: analytics.NewTraits().Set("company_domain", a.getCompanyDomain()),- })- }-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SendIdentifyEvent(data map[string]interface{}, userEmail string) {-- if !a.isTelemetryEnabled() || a.isTelemetryAnonymous() {- return- }- // ignore telemetry for default user- if userEmail == DEFAULT_CLOUD_EMAIL || a.GetUserEmail() == DEFAULT_CLOUD_EMAIL {- return- }-- if userEmail != "" {- a.SetUserEmail(userEmail)- a.SetCompanyDomain(userEmail)- }- traits := analytics.NewTraits()-- for k, v := range data {- traits.Set(k, v)- }- if a.saasOperator != nil {- _ = a.saasOperator.Enqueue(analytics.Identify{- UserId: a.GetUserEmail(),- Traits: traits,- })- }- if a.ossOperator != nil {- _ = a.ossOperator.Enqueue(analytics.Identify{- UserId: a.ipAddress,- Traits: traits,- })- }-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SendGroupEvent(data map[string]interface{}, userEmail string) {- if !a.isTelemetryEnabled() || a.isTelemetryAnonymous() {- return- }- // ignore telemetry for default user- if userEmail == DEFAULT_CLOUD_EMAIL || a.GetUserEmail() == DEFAULT_CLOUD_EMAIL {- return- }-- if userEmail != "" {- a.SetUserEmail(userEmail)- a.SetCompanyDomain(userEmail)- }- traits := analytics.NewTraits()-- for k, v := range data {- traits.Set(k, v)- }- if a.saasOperator != nil {- _ = a.saasOperator.Enqueue(analytics.Group{- UserId: a.GetUserEmail(),- GroupId: a.getCompanyDomain(),- Traits: traits,- })- }- if a.ossOperator != nil {- _ = a.ossOperator.Enqueue(analytics.Group{- UserId: a.ipAddress,- GroupId: a.getCompanyDomain(),- Traits: traits,- })- }-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetUserEmail(email string) {- a.userEmail = email-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetPatTokenUser() {- a.patTokenUser = true-}--// deprecated: remove this function in the next major release-func (a *Telemetry) GetUserEmail() string {- return a.userEmail-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetSaasOperator(saasOperatorKey string) {- if saasOperatorKey == "" {- return- }- a.saasOperator = analytics.New(saasOperatorKey)-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetCompanyDomain(email string) {-- email_split := strings.Split(email, "@")- if len(email_split) != 2 {- a.companyDomain = email- }- a.companyDomain = email_split[1]--}--// deprecated: remove this function in the next major release-func (a *Telemetry) getCompanyDomain() string {- return a.companyDomain-}--// deprecated: remove this function in the next major release-func (a *Telemetry) checkEvents(event string) bool {- sendEvent := true- if event == TELEMETRY_EVENT_USER && a.isTelemetryAnonymous() {- sendEvent = false- }- return sendEvent-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SendEvent(event string, data map[string]interface{}, userEmail string, rateLimitFlag bool, viaEventsAPI bool) {-- // ignore telemetry for default user- if userEmail == DEFAULT_CLOUD_EMAIL || a.GetUserEmail() == DEFAULT_CLOUD_EMAIL {- return- }-- if userEmail != "" {- a.SetUserEmail(userEmail)- a.SetCompanyDomain(userEmail)- }-- if !a.isTelemetryEnabled() {- return- }-- ok := a.checkEvents(event)- if !ok {- return- }-- // drop events with properties matching- if ignoreEvents(event, data) {- return- }-- if rateLimitFlag {- telemetry.mutex.Lock()- limit := a.rateLimits[event]- if limit < RATE_LIMIT_VALUE {- a.rateLimits[event] += 1- telemetry.mutex.Unlock()- } else {- telemetry.mutex.Unlock()- return- }- }-- // zap.L().Info(data)- properties := analytics.NewProperties()- properties.Set("version", version.Info.Version())- properties.Set("deploymentType", getDeploymentType())- properties.Set("companyDomain", a.getCompanyDomain())-- for k, v := range data {- properties.Set(k, v)- }-- userId := a.ipAddress- if a.isTelemetryAnonymous() || userId == IP_NOT_FOUND_PLACEHOLDER {- userId = "anonymous"- }-- // check if event is part of SAAS_EVENTS_LIST- _, isSaaSEvent := SAAS_EVENTS_LIST[event]-- if a.saasOperator != nil && a.GetUserEmail() != "" && (isSaaSEvent || viaEventsAPI) {- _ = a.saasOperator.Enqueue(analytics.Track{- Event: event,- UserId: a.GetUserEmail(),- Properties: properties,- Context: &analytics.Context{- Extra: map[string]interface{}{- "groupId": a.getCompanyDomain(),- },- },- })- }-- _, isOSSEvent := OSS_EVENTS_LIST[event]-- if a.ossOperator != nil && isOSSEvent {- _ = a.ossOperator.Enqueue(analytics.Track{- Event: event,- UserId: userId,- Properties: properties,- Context: &analytics.Context{- Extra: map[string]interface{}{- "groupId": a.getCompanyDomain(),- },- },- })- }-}--// deprecated: remove this function in the next major release-func (a *Telemetry) isTelemetryAnonymous() bool {- return a.isAnonymous-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetTelemetryAnonymous(value bool) {- a.isAnonymous = value-}--// deprecated: remove this function in the next major release-func (a *Telemetry) isTelemetryEnabled() bool {- return a.isEnabled-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetTelemetryEnabled(value bool) {- a.isEnabled = value-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetReader(reader interfaces.Reader) {- a.reader = reader-}--// deprecated: remove this function in the next major release-func (a *Telemetry) SetSqlStore(store sqlstore.SQLStore) {- a.sqlStore = store-}--// deprecated: remove this function in the next major release-func GetInstance() *Telemetry {- once.Do(func() {- createTelemetry()- })-- return telemetry-}--// deprecated: remove this function in the next major release-func getDeploymentType() string {- deploymentType := os.Getenv("DEPLOYMENT_TYPE")- if deploymentType == "" {- return "unknown"- }- return deploymentType-}diff --git a/pkg/query-service/telemetry/user.go b/pkg/query-service/telemetry/user.godeleted file mode 100644index 5788469acb..0000000000--- a/pkg/query-service/telemetry/user.go+++ /dev/null@@ -1,65 +0,0 @@-package telemetry--import (- "context"-- "github.com/SigNoz/signoz/pkg/errors"- "github.com/SigNoz/signoz/pkg/sqlstore"- "github.com/SigNoz/signoz/pkg/types"-)--type TelemetryUser struct {- types.User- Organization string-}--// deprecated: remove this function in the next major release-func GetUsers(ctx context.Context, sqlstore sqlstore.SQLStore) ([]TelemetryUser, error) {- return GetUsersWithOpts(ctx, 0, sqlstore)-}--// deprecated: remove this function in the next major release-func GetUserCount(ctx context.Context, sqlstore sqlstore.SQLStore) (int, error) {- users, err := GetUsersWithOpts(ctx, 0, sqlstore)- if err != nil {- return 0, err- }- return len(users), nil-}--// deprecated: remove this function in the next major release-func GetUsersWithOpts(ctx context.Context, limit int, sqlstore sqlstore.SQLStore) ([]TelemetryUser, error) {- var displayName string- err := sqlstore.BunDB().NewSelect().- Model(&types.Organization{}).- Column("display_name").- Scan(ctx, &displayName)- if err != nil {- return nil, sqlstore.WrapNotFoundErrf(err, errors.CodeNotFound, "cannot find organization")- }-- users := []types.User{}-- query := sqlstore.- BunDB().- NewSelect().- Model(&users)- if limit > 0 {- query.Limit(limit)- }-- err = query.Scan(ctx)- if err != nil {- return nil, sqlstore.WrapNotFoundErrf(err, errors.CodeNotFound, "failed to get users")- }-- telemetryUsers := []TelemetryUser{}- for _, user := range users {- telemetryUsers = append(telemetryUsers, TelemetryUser{- User: user,- Organization: displayName,- })- }-- return telemetryUsers, nil-}diff --git a/pkg/statsreporter/analyticsstatsreporter/provider.go b/pkg/statsreporter/analyticsstatsreporter/provider.goindex 17458f23ae..afc5545885 100644--- a/pkg/statsreporter/analyticsstatsreporter/provider.go+++ b/pkg/statsreporter/analyticsstatsreporter/provider.go@@ -218,17 +218,23 @@ func (provider *provider) collectOrg(ctx context.Context, orgID valuer.UUID) mapvar tracesLastSeenAt time.Timeif err := provider.telemetryStore.ClickhouseDB().QueryRow(ctx, "SELECT max(timestamp) FROM signoz_traces.distributed_signoz_index_v3").Scan(&tracesLastSeenAt); err == nil {- stats["telemetry.traces.last_observed.time"] = tracesLastSeenAt.UTC()+ if tracesLastSeenAt.Unix() != 0 {+ stats["telemetry.traces.last_observed.time"] = tracesLastSeenAt.UTC()+ }}var logsLastSeenAt time.Timeif err := provider.telemetryStore.ClickhouseDB().QueryRow(ctx, "SELECT fromUnixTimestamp64Nano(max(timestamp)) FROM signoz_logs.distributed_logs_v2").Scan(&logsLastSeenAt); err == nil {- stats["telemetry.logs.last_observed.time"] = logsLastSeenAt.UTC()+ if logsLastSeenAt.Unix() != 0 {+ stats["telemetry.logs.last_observed.time"] = logsLastSeenAt.UTC()+ }}var metricsLastSeenAt time.Timeif err := provider.telemetryStore.ClickhouseDB().QueryRow(ctx, "SELECT toDateTime(max(unix_milli) / 1000) FROM signoz_metrics.distributed_samples_v4").Scan(&metricsLastSeenAt); err == nil {- stats["telemetry.metrics.last_observed.time"] = metricsLastSeenAt.UTC()+ if metricsLastSeenAt.Unix() != 0 {+ stats["telemetry.metrics.last_observed.time"] = metricsLastSeenAt.UTC()+ }}return stats