From fa538a850cd916482f38501e16a4b4098d449e52 Mon Sep 17 00:00:00 2001 From: mitchell Date: Wed, 13 Sep 2023 10:37:09 -0400 Subject: [PATCH] Move analytics source into clients. Also improve forwarding events on behalf of executors. --- cmd/state-installer/cmd.go | 40 +++++++++---------- cmd/state-offline-installer/install.go | 8 ++-- cmd/state-offline-installer/main.go | 3 +- cmd/state-offline-uninstaller/main.go | 3 +- cmd/state-offline-uninstaller/uninstall.go | 10 ++--- cmd/state-remote-installer/main.go | 3 +- cmd/state-svc/internal/resolver/resolver.go | 12 +++--- cmd/state-svc/internal/rtwatcher/watcher.go | 4 +- cmd/state-svc/internal/server/server.go | 6 +-- cmd/state-svc/main.go | 3 +- cmd/state/autoupdate.go | 14 +++---- cmd/state/internal/cmdtree/activate.go | 8 ++-- cmd/state/internal/cmdtree/tutorial.go | 4 +- cmd/state/main.go | 8 ++-- internal/analytics/analytics.go | 5 ++- internal/analytics/client/async/client.go | 21 ++++++++-- internal/analytics/client/sync/client.go | 23 +++++++++-- internal/analytics/constants/constants.go | 15 +++++-- internal/captain/command.go | 10 ++--- internal/prompt/prompt.go | 8 ++-- internal/runbits/activation/activation.go | 2 +- internal/runbits/requirements/requirements.go | 2 +- internal/runners/activate/activate.go | 2 +- internal/runners/config/set.go | 2 +- .../runners/deploy/uninstall/uninstall.go | 2 +- internal/runners/ppm/convert.go | 16 ++++---- internal/runners/ppm/shim.go | 6 +-- internal/runners/tutorial/tutorial.go | 14 +++---- internal/svcctl/comm.go | 4 +- internal/updater/checker.go | 4 +- internal/updater/fetcher.go | 2 +- internal/updater/updater.go | 2 +- pkg/cmdlets/errors/errors.go | 2 +- pkg/cmdlets/git/git.go | 2 +- pkg/platform/runtime/analytics/analytics.go | 25 ++++++++++++ pkg/platform/runtime/runtime.go | 17 +++----- pkg/platform/runtime/setup/setup.go | 17 +++----- 37 files changed, 193 insertions(+), 136 deletions(-) create mode 100644 pkg/platform/runtime/analytics/analytics.go diff --git a/cmd/state-installer/cmd.go b/cmd/state-installer/cmd.go index b5b1faa54b..462444eff5 100644 --- a/cmd/state-installer/cmd.go +++ b/cmd/state-installer/cmd.go @@ -123,8 +123,8 @@ func main() { logging.Debug("Original Args: %v", os.Args) logging.Debug("Processed Args: %v", processedArgs) - an = sync.New(cfg, nil, out) - an.Event(anaConst.CatInstallerFunnel, "start", anaConst.SrcStateTool) + an = sync.New(anaConst.SrcStateInstaller, cfg, nil, out) + an.Event(anaConst.CatInstallerFunnel, "start") params := newParams() cmd := captain.NewCommand( @@ -191,30 +191,30 @@ func main() { }, ) - an.Event(anaConst.CatInstallerFunnel, "pre-exec", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "pre-exec") err = cmd.Execute(processedArgs[1:]) if err != nil { errors.ReportError(err, cmd, an) if locale.IsInputError(err) { - an.EventWithLabel(anaConst.CatInstaller, "input-error", anaConst.SrcStateTool, errs.JoinMessage(err)) + an.EventWithLabel(anaConst.CatInstaller, "input-error", errs.JoinMessage(err)) logging.Debug("Installer input error: " + errs.JoinMessage(err)) } else { - an.EventWithLabel(anaConst.CatInstaller, "error", anaConst.SrcStateTool, errs.JoinMessage(err)) + an.EventWithLabel(anaConst.CatInstaller, "error", errs.JoinMessage(err)) multilog.Critical("Installer error: " + errs.JoinMessage(err)) } - an.EventWithLabel(anaConst.CatInstallerFunnel, "fail", anaConst.SrcStateTool, errs.JoinMessage(err)) + an.EventWithLabel(anaConst.CatInstallerFunnel, "fail", errs.JoinMessage(err)) exitCode, err = errors.ParseUserFacing(err) if err != nil { out.Error(err) } } else { - an.Event(anaConst.CatInstallerFunnel, "success", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "success") } } func execute(out output.Outputer, cfg *config.Instance, an analytics.Dispatcher, args []string, params *Params) error { - an.Event(anaConst.CatInstallerFunnel, "exec", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "exec") if params.path == "" { var err error @@ -272,13 +272,13 @@ func execute(out output.Outputer, cfg *config.Instance, an analytics.Dispatcher, if params.isUpdate { route = "update" } - an.Event(anaConst.CatInstallerFunnel, route, anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, route) // Check if state tool already installed if !params.isUpdate && !params.force && stateToolInstalled && !targetingSameBranch { logging.Debug("Cancelling out because State Tool is already installed") out.Print(fmt.Sprintf("State Tool Package Manager is already installed at [NOTICE]%s[/RESET]. To reinstall use the [ACTIONABLE]--force[/RESET] flag.", installPath)) - an.Event(anaConst.CatInstallerFunnel, "already-installed", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "already-installed") params.isUpdate = true return postInstallEvents(out, cfg, an, params) } @@ -293,7 +293,7 @@ func execute(out output.Outputer, cfg *config.Instance, an analytics.Dispatcher, // installOrUpdateFromLocalSource is invoked when we're performing an installation where the payload is already provided func installOrUpdateFromLocalSource(out output.Outputer, cfg *config.Instance, an analytics.Dispatcher, payloadPath string, params *Params) error { logging.Debug("Install from local source") - an.Event(anaConst.CatInstallerFunnel, "local-source", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "local-source") if !params.isUpdate { // install.sh or install.ps1 downloaded this installer and is running it. out.Print(output.Title("Installing State Tool Package Manager")) @@ -322,12 +322,12 @@ func installOrUpdateFromLocalSource(out output.Outputer, cfg *config.Instance, a } // Run installer - an.Event(anaConst.CatInstallerFunnel, "pre-installer", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "pre-installer") if err := installer.Install(); err != nil { out.Print("[ERROR]x Failed[/RESET]") return err } - an.Event(anaConst.CatInstallerFunnel, "post-installer", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "post-installer") out.Print("[SUCCESS]✔ Done[/RESET]") if !params.isUpdate { @@ -340,7 +340,7 @@ func installOrUpdateFromLocalSource(out output.Outputer, cfg *config.Instance, a } func postInstallEvents(out output.Outputer, cfg *config.Instance, an analytics.Dispatcher, params *Params) error { - an.Event(anaConst.CatInstallerFunnel, "post-install-events", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "post-install-events") installPath, err := resolveInstallPath(params.path) if err != nil { @@ -366,30 +366,30 @@ func postInstallEvents(out output.Outputer, cfg *config.Instance, an analytics.D switch { // Execute provided --command case params.command != "": - an.Event(anaConst.CatInstallerFunnel, "forward-command", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "forward-command") out.Print(fmt.Sprintf("\nRunning `[ACTIONABLE]%s[/RESET]`\n", params.command)) cmd, args := exeutils.DecodeCmd(params.command) if _, _, err := exeutils.ExecuteAndPipeStd(cmd, args, envSlice(binPath)); err != nil { - an.EventWithLabel(anaConst.CatInstallerFunnel, "forward-command-err", anaConst.SrcStateTool, err.Error()) + an.EventWithLabel(anaConst.CatInstallerFunnel, "forward-command-err", err.Error()) return errs.Silence(errs.Wrap(err, "Running provided command failed, error returned: %s", errs.JoinMessage(err))) } // Activate provided --activate Namespace case params.activate.IsValid(): - an.Event(anaConst.CatInstallerFunnel, "forward-activate", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "forward-activate") out.Print(fmt.Sprintf("\nRunning `[ACTIONABLE]state activate %s[/RESET]`\n", params.activate.String())) if _, _, err := exeutils.ExecuteAndPipeStd(stateExe, []string{"activate", params.activate.String()}, envSlice(binPath)); err != nil { - an.EventWithLabel(anaConst.CatInstallerFunnel, "forward-activate-err", anaConst.SrcStateTool, err.Error()) + an.EventWithLabel(anaConst.CatInstallerFunnel, "forward-activate-err", err.Error()) return errs.Silence(errs.Wrap(err, "Could not activate %s, error returned: %s", params.activate.String(), errs.JoinMessage(err))) } // Activate provided --activate-default Namespace case params.activateDefault.IsValid(): - an.Event(anaConst.CatInstallerFunnel, "forward-activate-default", anaConst.SrcStateTool) + an.Event(anaConst.CatInstallerFunnel, "forward-activate-default") out.Print(fmt.Sprintf("\nRunning `[ACTIONABLE]state activate --default %s[/RESET]`\n", params.activateDefault.String())) if _, _, err := exeutils.ExecuteAndPipeStd(stateExe, []string{"activate", params.activateDefault.String(), "--default"}, envSlice(binPath)); err != nil { - an.EventWithLabel(anaConst.CatInstallerFunnel, "forward-activate-default-err", anaConst.SrcStateTool, err.Error()) + an.EventWithLabel(anaConst.CatInstallerFunnel, "forward-activate-default-err", err.Error()) return errs.Silence(errs.Wrap(err, "Could not activate %s, error returned: %s", params.activateDefault.String(), errs.JoinMessage(err))) } case !params.isUpdate && terminal.IsTerminal(int(os.Stdin.Fd())) && os.Getenv(constants.InstallerNoSubshell) != "true" && os.Getenv("TERM") != "dumb": diff --git a/cmd/state-offline-installer/install.go b/cmd/state-offline-installer/install.go index cd46faa035..42d7d0da76 100644 --- a/cmd/state-offline-installer/install.go +++ b/cmd/state-offline-installer/install.go @@ -92,9 +92,9 @@ func (r *runner) Run(params *Params) (rerr error) { return } if locale.IsInputError(rerr) { - r.analytics.EventWithLabel(ac.CatOfflineInstaller, ac.ActOfflineInstallerAbort, ac.SrcOfflineInstaller, errs.JoinMessage(rerr), installerDimensions) + r.analytics.EventWithLabel(ac.CatOfflineInstaller, ac.ActOfflineInstallerAbort, errs.JoinMessage(rerr), installerDimensions) } else { - r.analytics.EventWithLabel(ac.CatOfflineInstaller, ac.ActOfflineInstallerFailure, ac.SrcOfflineInstaller, errs.JoinMessage(rerr), installerDimensions) + r.analytics.EventWithLabel(ac.CatOfflineInstaller, ac.ActOfflineInstallerFailure, errs.JoinMessage(rerr), installerDimensions) } }() @@ -122,7 +122,7 @@ func (r *runner) Run(params *Params) (rerr error) { CommitID: &r.icfg.CommitID, Trigger: ptr.To(target.TriggerOfflineInstaller.String()), } - r.analytics.Event(ac.CatOfflineInstaller, "start", ac.SrcOfflineInstaller, installerDimensions) + r.analytics.Event(ac.CatOfflineInstaller, "start", installerDimensions) // Detect target path targetPath, err := r.getTargetPath(params.path) @@ -248,7 +248,7 @@ func (r *runner) Run(params *Params) (rerr error) { return errs.Wrap(err, "Could not configure environment") } - r.analytics.Event(ac.CatOfflineInstaller, ac.ActOfflineInstallerSuccess, ac.SrcOfflineInstaller, installerDimensions) + r.analytics.Event(ac.CatOfflineInstaller, ac.ActOfflineInstallerSuccess, installerDimensions) r.out.Print(fmt.Sprintf(`Installation complete. Your language runtime has been installed in [ACTIONABLE]%s[/RESET].`, targetPath)) diff --git a/cmd/state-offline-installer/main.go b/cmd/state-offline-installer/main.go index 89dc821608..82b8cd86e7 100644 --- a/cmd/state-offline-installer/main.go +++ b/cmd/state-offline-installer/main.go @@ -8,6 +8,7 @@ import ( "github.com/ActiveState/cli/internal/analytics" "github.com/ActiveState/cli/internal/analytics/client/sync" + anaConst "github.com/ActiveState/cli/internal/analytics/constants" "github.com/ActiveState/cli/internal/captain" "github.com/ActiveState/cli/internal/config" "github.com/ActiveState/cli/internal/constants" @@ -78,7 +79,7 @@ func main() { return } - an = sync.New(cfg, nil, out) + an = sync.New(anaConst.SrcOfflineInstaller, cfg, nil, out) prime := primer.New( nil, out, nil, diff --git a/cmd/state-offline-uninstaller/main.go b/cmd/state-offline-uninstaller/main.go index 822e831dfb..0ba17527c5 100644 --- a/cmd/state-offline-uninstaller/main.go +++ b/cmd/state-offline-uninstaller/main.go @@ -8,6 +8,7 @@ import ( "github.com/ActiveState/cli/internal/analytics" "github.com/ActiveState/cli/internal/analytics/client/sync" + anaConst "github.com/ActiveState/cli/internal/analytics/constants" "github.com/ActiveState/cli/internal/captain" "github.com/ActiveState/cli/internal/config" "github.com/ActiveState/cli/internal/constants" @@ -78,7 +79,7 @@ func main() { return } - an = sync.New(cfg, nil, out) + an = sync.New(anaConst.SrcOfflineInstaller, cfg, nil, out) prime := primer.New( nil, out, nil, diff --git a/cmd/state-offline-uninstaller/uninstall.go b/cmd/state-offline-uninstaller/uninstall.go index 209891f9ff..08a86065fc 100644 --- a/cmd/state-offline-uninstaller/uninstall.go +++ b/cmd/state-offline-uninstaller/uninstall.go @@ -79,9 +79,9 @@ func (r *runner) Run(params *Params) (rerr error) { return } if locale.IsInputError(rerr) { - r.analytics.EventWithLabel(ac.CatOfflineInstaller, ac.ActOfflineInstallerAbort, ac.SrcOfflineInstaller, errs.JoinMessage(rerr), installerDimensions) + r.analytics.EventWithLabel(ac.CatOfflineInstaller, ac.ActOfflineInstallerAbort, errs.JoinMessage(rerr), installerDimensions) } else { - r.analytics.EventWithLabel(ac.CatOfflineInstaller, ac.ActOfflineInstallerFailure, ac.SrcOfflineInstaller, errs.JoinMessage(rerr), installerDimensions) + r.analytics.EventWithLabel(ac.CatOfflineInstaller, ac.ActOfflineInstallerFailure, errs.JoinMessage(rerr), installerDimensions) } }() @@ -116,7 +116,7 @@ func (r *runner) Run(params *Params) (rerr error) { CommitID: &r.icfg.CommitID, Trigger: ptr.To(target.TriggerOfflineUninstaller.String()), } - r.analytics.Event(ac.CatOfflineInstaller, ac.ActOfflineInstallerStart, ac.SrcOfflineInstaller, installerDimensions) + r.analytics.Event(ac.CatOfflineInstaller, ac.ActOfflineInstallerStart, installerDimensions) r.out.Print("Removing environment configuration") err = r.removeEnvPaths(namespace) @@ -130,8 +130,8 @@ func (r *runner) Run(params *Params) (rerr error) { return errs.Wrap(err, "Error removing installation directory") } - r.analytics.Event(ac.CatOfflineInstaller, ac.ActOfflineInstallerSuccess, ac.SrcOfflineInstaller, installerDimensions) - r.analytics.Event(ac.CatRuntimeUsage, ac.ActRuntimeDelete, ac.SrcOfflineInstaller, installerDimensions) + r.analytics.Event(ac.CatOfflineInstaller, ac.ActOfflineInstallerSuccess, installerDimensions) + r.analytics.Event(ac.CatRuntimeUsage, ac.ActRuntimeDelete, installerDimensions) r.out.Print("Uninstall Complete") diff --git a/cmd/state-remote-installer/main.go b/cmd/state-remote-installer/main.go index 6320c67d0f..73ce0feaf2 100644 --- a/cmd/state-remote-installer/main.go +++ b/cmd/state-remote-installer/main.go @@ -10,6 +10,7 @@ import ( "github.com/ActiveState/cli/internal/analytics" "github.com/ActiveState/cli/internal/analytics/client/sync" + anaConst "github.com/ActiveState/cli/internal/analytics/constants" "github.com/ActiveState/cli/internal/captain" "github.com/ActiveState/cli/internal/config" "github.com/ActiveState/cli/internal/constants" @@ -94,7 +95,7 @@ func main() { return } - an = sync.New(cfg, nil, out) + an = sync.New(anaConst.SrcStateRemoteInstaller, cfg, nil, out) // Set up prompter prompter := prompt.New(true, an) diff --git a/cmd/state-svc/internal/resolver/resolver.go b/cmd/state-svc/internal/resolver/resolver.go index f027de602f..4f23ea3754 100644 --- a/cmd/state-svc/internal/resolver/resolver.go +++ b/cmd/state-svc/internal/resolver/resolver.go @@ -73,7 +73,9 @@ func New(cfg *config.Instance, an *sync.Client, auth *authentication.Auth) (*Res usageChecker := rtusage.NewChecker(cfg, auth) - anForClient := sync.New(cfg, auth, nil) + // Note: source does not matter here, as analytics sent via the resolver have a source + // (e.g. State Tool or Executor), and that source will be used. + anForClient := sync.New(anaConsts.SrcStateTool, cfg, auth, nil) return &Resolver{ cfg, msg, @@ -102,7 +104,7 @@ func (r *Resolver) Query() genserver.QueryResolver { return r } func (r *Resolver) Version(ctx context.Context) (*graph.Version, error) { defer func() { handlePanics(recover(), debug.Stack()) }() - r.an.EventWithLabel(anaConsts.CatStateSvc, "endpoint", anaConsts.SrcStateTool, "Version") + r.an.EventWithLabel(anaConsts.CatStateSvc, "endpoint", "Version") logging.Debug("Version resolver") return &graph.Version{ State: &graph.StateVersion{ @@ -118,7 +120,7 @@ func (r *Resolver) Version(ctx context.Context) (*graph.Version, error) { func (r *Resolver) AvailableUpdate(ctx context.Context) (*graph.AvailableUpdate, error) { defer func() { handlePanics(recover(), debug.Stack()) }() - r.an.EventWithLabel(anaConsts.CatStateSvc, "endpoint", anaConsts.SrcStateTool, "AvailableUpdate") + r.an.EventWithLabel(anaConsts.CatStateSvc, "endpoint", "AvailableUpdate") logging.Debug("AvailableUpdate resolver") defer logging.Debug("AvailableUpdate done") @@ -142,7 +144,7 @@ func (r *Resolver) AvailableUpdate(ctx context.Context) (*graph.AvailableUpdate, func (r *Resolver) Projects(ctx context.Context) ([]*graph.Project, error) { defer func() { handlePanics(recover(), debug.Stack()) }() - r.an.EventWithLabel(anaConsts.CatStateSvc, "endpoint", anaConsts.SrcStateTool, "Projects") + r.an.EventWithLabel(anaConsts.CatStateSvc, "endpoint", "Projects") logging.Debug("Projects resolver") var projects []*graph.Project localConfigProjects := projectfile.GetProjectMapping(r.cfg) @@ -188,7 +190,7 @@ func (r *Resolver) AnalyticsEvent(_ context.Context, category, action, source st return nil }) - r.anForClient.EventWithLabel(category, action, source, label, dims) + r.anForClient.EventWithSourceAndLabel(category, action, source, label, dims) return &graph.AnalyticsEventResponse{Sent: true}, nil } diff --git a/cmd/state-svc/internal/rtwatcher/watcher.go b/cmd/state-svc/internal/rtwatcher/watcher.go index fa22aaeaff..0b68b11895 100644 --- a/cmd/state-svc/internal/rtwatcher/watcher.go +++ b/cmd/state-svc/internal/rtwatcher/watcher.go @@ -30,7 +30,7 @@ type Watcher struct { } type analytics interface { - Event(category, action, source string, dim ...*dimensions.Values) + EventWithSource(category, action, source string, dim ...*dimensions.Values) } func New(cfg *config.Instance, an analytics) *Watcher { @@ -97,7 +97,7 @@ func (w *Watcher) check() { func (w *Watcher) RecordUsage(e entry) { logging.Debug("Recording usage of %s (%d)", e.Exec, e.PID) - w.an.Event(anaConst.CatRuntimeUsage, anaConst.ActRuntimeHeartbeat, anaConst.SrcStateTool, e.Dims) + w.an.EventWithSource(anaConst.CatRuntimeUsage, anaConst.ActRuntimeHeartbeat, anaConst.SrcExecutor, e.Dims) } func (w *Watcher) Close() error { diff --git a/cmd/state-svc/internal/server/server.go b/cmd/state-svc/internal/server/server.go index f1048e1730..9750b77711 100644 --- a/cmd/state-svc/internal/server/server.go +++ b/cmd/state-svc/internal/server/server.go @@ -75,16 +75,16 @@ func (s *Server) Resolver() *resolver.Resolver { } func (s *Server) Start() error { - s.analytics.Event(constants.CatStateSvc, "start", constants.SrcStateTool) + s.analytics.Event(constants.CatStateSvc, "start") err := s.httpServer.Start(s.listener.Addr().String()) if err != nil { - s.analytics.Event(constants.CatStateSvc, "start-failure", constants.SrcStateTool) + s.analytics.Event(constants.CatStateSvc, "start-failure") } return err } func (s *Server) Shutdown() error { - s.analytics.Event(constants.CatStateSvc, "shutdown", constants.SrcStateTool) + s.analytics.Event(constants.CatStateSvc, "shutdown") logging.Debug("shutting down server") ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() diff --git a/cmd/state-svc/main.go b/cmd/state-svc/main.go index 22faee2da8..0234ad634b 100644 --- a/cmd/state-svc/main.go +++ b/cmd/state-svc/main.go @@ -13,6 +13,7 @@ import ( "github.com/ActiveState/cli/cmd/state-svc/autostart" anaSync "github.com/ActiveState/cli/internal/analytics/client/sync" + anaConst "github.com/ActiveState/cli/internal/analytics/constants" "github.com/ActiveState/cli/internal/captain" "github.com/ActiveState/cli/internal/config" "github.com/ActiveState/cli/internal/constants" @@ -98,7 +99,7 @@ func run(cfg *config.Instance) error { } auth := authentication.New(cfg) - an := anaSync.New(cfg, auth, out) + an := anaSync.New(anaConst.SrcStateService, cfg, auth, out) defer an.Wait() if err := autostart.RegisterConfigListener(cfg); err != nil { diff --git a/cmd/state/autoupdate.go b/cmd/state/autoupdate.go index 0992bff9be..54ffc6c74e 100644 --- a/cmd/state/autoupdate.go +++ b/cmd/state/autoupdate.go @@ -63,7 +63,7 @@ func autoUpdate(args []string, cfg *config.Instance, an analytics.Dispatcher, ou if !isEnabled(cfg) { logging.Debug("Not performing autoupdates because user turned off autoupdates.") - an.EventWithLabel(anaConst.CatUpdates, anaConst.ActShouldUpdate, anaConst.SrcStateTool, anaConst.UpdateLabelDisabledConfig) + an.EventWithLabel(anaConst.CatUpdates, anaConst.ActShouldUpdate, anaConst.UpdateLabelDisabledConfig) out.Notice(output.Title(locale.Tl("update_available_header", "Auto Update"))) out.Notice(locale.Tr("update_available", constants.Version, up.Version)) return false, nil @@ -77,20 +77,20 @@ func autoUpdate(args []string, cfg *config.Instance, an analytics.Dispatcher, ou err = up.InstallBlocking("") if err != nil { if os.IsPermission(err) { - an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateInstall, anaConst.SrcStateTool, anaConst.UpdateLabelFailed, &dimensions.Values{ + an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateInstall, anaConst.UpdateLabelFailed, &dimensions.Values{ TargetVersion: ptr.To(up.Version), Error: ptr.To("Could not update the state tool due to insufficient permissions."), }) return false, locale.WrapInputError(err, locale.Tl("auto_update_permission_err", "", constants.DocumentationURL, errs.JoinMessage(err))) } if errs.Matches(err, &updater.ErrorInProgress{}) { - an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateInstall, anaConst.SrcStateTool, anaConst.UpdateLabelFailed, &dimensions.Values{ + an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateInstall, anaConst.UpdateLabelFailed, &dimensions.Values{ TargetVersion: ptr.To(up.Version), Error: ptr.To(anaConst.UpdateErrorInProgress), }) return false, nil } - an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateInstall, anaConst.SrcStateTool, anaConst.UpdateLabelFailed, &dimensions.Values{ + an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateInstall, anaConst.UpdateLabelFailed, &dimensions.Values{ TargetVersion: ptr.To(up.Version), Error: ptr.To(anaConst.UpdateErrorInstallFailed), }) @@ -108,14 +108,14 @@ func autoUpdate(args []string, cfg *config.Instance, an analytics.Dispatcher, ou } else if errs.Matches(err, &ErrExecuteRelaunch{}) { msg = anaConst.UpdateErrorRelaunch } - an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateRelaunch, anaConst.SrcStateTool, anaConst.UpdateLabelFailed, &dimensions.Values{ + an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateRelaunch, anaConst.UpdateLabelFailed, &dimensions.Values{ TargetVersion: ptr.To(up.Version), Error: ptr.To(msg), }) return true, errs.Silence(errs.WrapExitCode(err, code)) } - an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateRelaunch, anaConst.SrcStateTool, anaConst.UpdateLabelSuccess, &dimensions.Values{ + an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateRelaunch, anaConst.UpdateLabelSuccess, &dimensions.Values{ TargetVersion: ptr.To(up.Version), }) return true, nil @@ -187,7 +187,7 @@ func shouldRunAutoUpdate(args []string, cfg *config.Instance, an analytics.Dispa label = anaConst.UpdateLabelLocked } - an.EventWithLabel(anaConst.CatUpdates, anaConst.ActShouldUpdate, anaConst.SrcStateTool, label) + an.EventWithLabel(anaConst.CatUpdates, anaConst.ActShouldUpdate, label) return shouldUpdate } diff --git a/cmd/state/internal/cmdtree/activate.go b/cmd/state/internal/cmdtree/activate.go index 0202124e30..d675e300b4 100644 --- a/cmd/state/internal/cmdtree/activate.go +++ b/cmd/state/internal/cmdtree/activate.go @@ -66,19 +66,19 @@ func newActivateCommand(prime *primer.Values) *captain.Command { an := prime.Analytics() var serr interface{ Signal() os.Signal } if errors.As(err, &serr) { - an.Event(constants.CatActivationFlow, "user-interrupt-error", constants.SrcStateTool) + an.Event(constants.CatActivationFlow, "user-interrupt-error") } if locale.IsInputError(err) { // Failed due to user input - an.Event(constants.CatActivationFlow, "user-input-error", constants.SrcStateTool) + an.Event(constants.CatActivationFlow, "user-input-error") } else { var exitErr = &exec.ExitError{} if !errors.As(err, &exitErr) { // Failed due to an error we might need to address - an.Event(constants.CatActivationFlow, "error", constants.SrcStateTool) + an.Event(constants.CatActivationFlow, "error") } else { // Failed due to user subshell actions / events - an.Event(constants.CatActivationFlow, "user-exit-error", constants.SrcStateTool) + an.Event(constants.CatActivationFlow, "user-exit-error") } } } diff --git a/cmd/state/internal/cmdtree/tutorial.go b/cmd/state/internal/cmdtree/tutorial.go index 8c669867d9..af69f9a785 100644 --- a/cmd/state/internal/cmdtree/tutorial.go +++ b/cmd/state/internal/cmdtree/tutorial.go @@ -53,9 +53,9 @@ func newTutorialProjectCommand(prime *primer.Values) *captain.Command { func(ccmd *captain.Command, args []string) error { err := runner.RunNewProject(params) if err != nil { - prime.Analytics().EventWithLabel(constants.CatTutorial, "error", constants.SrcStateTool, errs.JoinMessage(err)) + prime.Analytics().EventWithLabel(constants.CatTutorial, "error", errs.JoinMessage(err)) } else { - prime.Analytics().Event(constants.CatTutorial, "completed", constants.SrcStateTool) + prime.Analytics().Event(constants.CatTutorial, "completed") } return err }, diff --git a/cmd/state/main.go b/cmd/state/main.go index c90ac8ad50..696e5b2df8 100644 --- a/cmd/state/main.go +++ b/cmd/state/main.go @@ -11,11 +11,11 @@ import ( "strings" "time" - "github.com/ActiveState/cli/cmd/state/internal/cmdtree/exechandlers/messenger" - "github.com/ActiveState/cli/internal/captain" - "github.com/ActiveState/cli/cmd/state/internal/cmdtree" + "github.com/ActiveState/cli/cmd/state/internal/cmdtree/exechandlers/messenger" anAsync "github.com/ActiveState/cli/internal/analytics/client/async" + anaConst "github.com/ActiveState/cli/internal/analytics/constants" + "github.com/ActiveState/cli/internal/captain" "github.com/ActiveState/cli/internal/config" "github.com/ActiveState/cli/internal/constants" "github.com/ActiveState/cli/internal/constraints" @@ -201,7 +201,7 @@ func run(args []string, isInteractive bool, cfg *config.Instance, out output.Out logging.Warning("Could not sync authenticated state: %s", errs.JoinMessage(err)) } - an := anAsync.New(svcmodel, cfg, auth, out, pjNamespace) + an := anAsync.New(anaConst.SrcStateTool, svcmodel, cfg, auth, out, pjNamespace) defer func() { if err := events.WaitForEvents(time.Second, an.Wait); err != nil { logging.Warning("Failed waiting for events: %v", err) diff --git a/internal/analytics/analytics.go b/internal/analytics/analytics.go index 6f2aaa3aca..9292b954e9 100644 --- a/internal/analytics/analytics.go +++ b/internal/analytics/analytics.go @@ -8,8 +8,9 @@ import ( // Dispatcher describes a struct that can send analytics event in the background type Dispatcher interface { - Event(category, action, source string, dim ...*dimensions.Values) - EventWithLabel(category, action, source, label string, dim ...*dimensions.Values) + Event(category, action string, dim ...*dimensions.Values) + EventWithLabel(category, action, label string, dim ...*dimensions.Values) + EventWithSource(category, action, source string, dim ...*dimensions.Values) Wait() Close() } diff --git a/internal/analytics/client/async/client.go b/internal/analytics/client/async/client.go index c590453c11..4aa4fa2452 100644 --- a/internal/analytics/client/async/client.go +++ b/internal/analytics/client/async/client.go @@ -38,13 +38,15 @@ type Client struct { ci bool interactive bool activestateCI bool + source string } var _ analytics.Dispatcher = &Client{} -func New(svcModel *model.SvcModel, cfg *config.Instance, auth *authentication.Auth, out output.Outputer, projectNameSpace string) *Client { +func New(source string, svcModel *model.SvcModel, cfg *config.Instance, auth *authentication.Auth, out output.Outputer, projectNameSpace string) *Client { a := &Client{ eventWaitGroup: &sync.WaitGroup{}, + source: source, } o := string(output.PlainFormatName) @@ -75,12 +77,23 @@ func New(svcModel *model.SvcModel, cfg *config.Instance, auth *authentication.Au } // Event logs an event to google analytics -func (a *Client) Event(category, action, source string, dims ...*dimensions.Values) { - a.EventWithLabel(category, action, source, "", dims...) +func (a *Client) Event(category, action string, dims ...*dimensions.Values) { + a.EventWithLabel(category, action, "", dims...) } // EventWithLabel logs an event with a label to google analytics -func (a *Client) EventWithLabel(category, action, source, label string, dims ...*dimensions.Values) { +func (a *Client) EventWithLabel(category, action, label string, dims ...*dimensions.Values) { + a.eventWithSourceAndLabel(category, action, a.source, label, dims...) +} + +// EventWithSource logs an event with another source to google analytics. +// For example, log runtime events triggered by executors as coming from an executor instead of from +// State Tool. +func (a *Client) EventWithSource(category, action, source string, dims ...*dimensions.Values) { + a.eventWithSourceAndLabel(category, action, source, "", dims...) +} + +func (a *Client) eventWithSourceAndLabel(category, action, source, label string, dims ...*dimensions.Values) { err := a.sendEvent(category, action, source, label, dims...) if err != nil { multilog.Error("Error during analytics.sendEvent: %v", errs.JoinMessage(err)) diff --git a/internal/analytics/client/sync/client.go b/internal/analytics/client/sync/client.go index 6ffee1f480..751c377149 100644 --- a/internal/analytics/client/sync/client.go +++ b/internal/analytics/client/sync/client.go @@ -45,16 +45,18 @@ type Client struct { reporters []Reporter sequence int auth *authentication.Auth + source string } var _ analytics.Dispatcher = &Client{} // New initializes the analytics instance with all custom dimensions known at this time -func New(cfg *config.Instance, auth *authentication.Auth, out output.Outputer) *Client { +func New(source string, cfg *config.Instance, auth *authentication.Auth, out output.Outputer) *Client { a := &Client{ eventWaitGroup: &sync.WaitGroup{}, sendReports: true, auth: auth, + source: source, } installSource, err := storage.InstallSource() @@ -165,8 +167,8 @@ func (a *Client) report(category, action, source, label string, dimensions *dime } } -func (a *Client) Event(category, action, source string, dims ...*dimensions.Values) { - a.EventWithLabel(category, action, source, "", dims...) +func (a *Client) Event(category, action string, dims ...*dimensions.Values) { + a.EventWithLabel(category, action, "", dims...) } func mergeDimensions(target *dimensions.Values, dims ...*dimensions.Values) *dimensions.Values { @@ -180,7 +182,20 @@ func mergeDimensions(target *dimensions.Values, dims ...*dimensions.Values) *dim return actualDims } -func (a *Client) EventWithLabel(category, action, source, label string, dims ...*dimensions.Values) { +func (a *Client) EventWithLabel(category, action, label string, dims ...*dimensions.Values) { + a.EventWithSourceAndLabel(category, action, a.source, label, dims...) +} + +// EventWithSource should only be used by clients forwarding events on behalf of another source. +// Otherwise, use Event(). +func (a *Client) EventWithSource(category, action, source string, dims ...*dimensions.Values) { + a.EventWithSourceAndLabel(category, action, source, "", dims...) +} + +// EventWithSourceAndLabel should only be used by clients forwarding events on behalf of another +// source (for example, state-svc forwarding events on behalf of State Tool or an executor). +// Otherwise, use EventWithLabel(). +func (a *Client) EventWithSourceAndLabel(category, action, source, label string, dims ...*dimensions.Values) { if a.customDimensions == nil { if condition.InUnitTest() { return diff --git a/internal/analytics/constants/constants.go b/internal/analytics/constants/constants.go index 60202bf803..268000d438 100644 --- a/internal/analytics/constants/constants.go +++ b/internal/analytics/constants/constants.go @@ -31,13 +31,22 @@ const CatInstaller = "installer" // CatInstallerFunnel is the event category used for installer funnel events. const CatInstallerFunnel = "installer-funnel" -// SrcStateTool is the event source for State Tool. +// SrcStateTool is the event source for events sent by state. const SrcStateTool = "State Tool" -// SrcOfflineInstaller is the event source for offline installers. +// SrcStateService is the event source for events sent by state-svc. +const SrcStateService = "State Service" + +// SrcStateInstaller is the event source for events sent by state-installer. +const SrcStateInstaller = "State Installer" + +// SrcStateRemoteInstaller is the event source for events sent by state-remote-installer. +const SrcStateRemoteInstaller = "State Remote Installer" + +// SrcOfflineInstaller is the event source for events sent by offline installers. const SrcOfflineInstaller = "Offline Installer" -// SrcExecutor is the event source for executors. +// SrcExecutor is the event source for events sent by executors. const SrcExecutor = "Executor" // ActRuntimeHeartbeat is the event action sent when a runtime is in use diff --git a/internal/captain/command.go b/internal/captain/command.go index 9708b9da3e..37e1cd4b21 100644 --- a/internal/captain/command.go +++ b/internal/captain/command.go @@ -634,10 +634,10 @@ func (c *Command) cobraExecHandler(cobraCmd *cobra.Command, args []string) error label = append(label, name) }) - c.analytics.EventWithLabel(anaConsts.CatRunCmd, appEventPrefix+subCommandString, anaConsts.SrcStateTool, strings.Join(label, " ")) + c.analytics.EventWithLabel(anaConsts.CatRunCmd, appEventPrefix+subCommandString, strings.Join(label, " ")) if shim, got := os.LookupEnv(constants.ShimEnvVarName); got { - c.analytics.Event(anaConsts.CatShim, shim, anaConsts.SrcStateTool) + c.analytics.Event(anaConsts.CatShim, shim) } } @@ -708,16 +708,16 @@ func (c *Command) cobraExecHandler(cobraCmd *cobra.Command, args []string) error var serr interface{ Signal() os.Signal } if errors.As(err, &serr) { if c.analytics != nil { - c.analytics.EventWithLabel(anaConsts.CatCommandExit, appEventPrefix+subCommandString, anaConsts.SrcStateTool, "interrupt") + c.analytics.EventWithLabel(anaConsts.CatCommandExit, appEventPrefix+subCommandString, "interrupt") } err = locale.WrapInputError(err, "user_interrupt", "User interrupted the State Tool process.") } else { if c.analytics != nil { if err != nil && (subCommandString == "install" || subCommandString == "activate") { // This is a temporary hack; proper implementation: https://activestatef.atlassian.net/browse/DX-495 - c.analytics.EventWithLabel(anaConsts.CatCommandError, appEventPrefix+subCommandString, anaConsts.SrcStateTool, errs.JoinMessage(err)) + c.analytics.EventWithLabel(anaConsts.CatCommandError, appEventPrefix+subCommandString, errs.JoinMessage(err)) } - c.analytics.EventWithLabel(anaConsts.CatCommandExit, appEventPrefix+subCommandString, anaConsts.SrcStateTool, strconv.Itoa(exitCode)) + c.analytics.EventWithLabel(anaConsts.CatCommandExit, appEventPrefix+subCommandString, strconv.Itoa(exitCode)) } } diff --git a/internal/prompt/prompt.go b/internal/prompt/prompt.go index 9e3759dc79..6da18f055c 100644 --- a/internal/prompt/prompt.go +++ b/internal/prompt/prompt.go @@ -15,7 +15,7 @@ import ( ) type EventDispatcher interface { - EventWithLabel(category, action, source string, label string, dim ...*dimensions.Values) + EventWithLabel(category, action string, label string, dim ...*dimensions.Values) } // Prompter is the interface used to run our prompt from, useful for mocking in tests @@ -169,7 +169,7 @@ func (p *Prompt) Confirm(title, message string, defaultChoice *bool) (bool, erro p.out.Notice(output.Emphasize(title)) } - p.analytics.EventWithLabel(constants.CatPrompt, title, constants.SrcStateTool, "present") + p.analytics.EventWithLabel(constants.CatPrompt, title, "present") var defChoice bool if defaultChoice != nil { @@ -183,11 +183,11 @@ func (p *Prompt) Confirm(title, message string, defaultChoice *bool) (bool, erro }}, &resp, nil) if err != nil { if err == terminal.InterruptErr { - p.analytics.EventWithLabel(constants.CatPrompt, title, constants.SrcStateTool, "interrupt") + p.analytics.EventWithLabel(constants.CatPrompt, title, "interrupt") } return false, locale.NewInputError(err.Error()) } - p.analytics.EventWithLabel(constants.CatPrompt, title, constants.SrcStateTool, translateConfirm(resp)) + p.analytics.EventWithLabel(constants.CatPrompt, title, translateConfirm(resp)) return resp, nil } diff --git a/internal/runbits/activation/activation.go b/internal/runbits/activation/activation.go index da23f7b4d7..d6d23740d8 100644 --- a/internal/runbits/activation/activation.go +++ b/internal/runbits/activation/activation.go @@ -80,7 +80,7 @@ func ActivateAndWait( } defer fe.Close() - an.Event(anaConst.CatActivationFlow, "before-subshell", anaConst.SrcStateTool) + an.Event(anaConst.CatActivationFlow, "before-subshell") err = <-ss.Errors() if err != nil { diff --git a/internal/runbits/requirements/requirements.go b/internal/runbits/requirements/requirements.go index 2a0f4b82f3..c3d7d81ac7 100644 --- a/internal/runbits/requirements/requirements.go +++ b/internal/runbits/requirements/requirements.go @@ -204,7 +204,7 @@ func (r *RequirementOperation) ExecuteRequirementOperation(requirementName, requ } r.Analytics.EventWithLabel( - anaConsts.CatPackageOp, fmt.Sprintf("%s-%s", operation, langName), anaConsts.SrcStateTool, requirementName, + anaConsts.CatPackageOp, fmt.Sprintf("%s-%s", operation, langName), requirementName, ) if !hasParentCommit { diff --git a/internal/runners/activate/activate.go b/internal/runners/activate/activate.go index 7366816080..14fd6ba218 100644 --- a/internal/runners/activate/activate.go +++ b/internal/runners/activate/activate.go @@ -151,7 +151,7 @@ func (r *Activate) Run(params *ActivateParams) error { } // Have to call this once the project has been set - r.analytics.Event(anaConsts.CatActivationFlow, "start", anaConsts.SrcStateTool) + r.analytics.Event(anaConsts.CatActivationFlow, "start") proj.Source().Persist() diff --git a/internal/runners/config/set.go b/internal/runners/config/set.go index 8b78072531..dca1705333 100644 --- a/internal/runners/config/set.go +++ b/internal/runners/config/set.go @@ -106,5 +106,5 @@ func (s *Set) sendEvent(key string, value string, option configMediator.Option) } } - s.analytics.EventWithLabel(constants.CatConfig, action, constants.SrcStateTool, key) + s.analytics.EventWithLabel(constants.CatConfig, action, key) } diff --git a/internal/runners/deploy/uninstall/uninstall.go b/internal/runners/deploy/uninstall/uninstall.go index 56f18b693b..2ffde0e656 100644 --- a/internal/runners/deploy/uninstall/uninstall.go +++ b/internal/runners/deploy/uninstall/uninstall.go @@ -99,7 +99,7 @@ func (u *Uninstall) Run(params *Params) error { return locale.WrapError(err, "err_deploy_uninstall", "Unable to remove deployed runtime at '{{.V0}}'", path) } - u.analytics.Event(constants.CatRuntimeUsage, constants.ActRuntimeDelete, constants.SrcStateTool, &dimensions.Values{ + u.analytics.Event(constants.CatRuntimeUsage, constants.ActRuntimeDelete, &dimensions.Values{ Trigger: ptr.To(target.TriggerDeploy.String()), CommitID: ptr.To(commitID), ProjectNameSpace: ptr.To(namespace), diff --git a/internal/runners/ppm/convert.go b/internal/runners/ppm/convert.go index 1220dda201..561130d135 100644 --- a/internal/runners/ppm/convert.go +++ b/internal/runners/ppm/convert.go @@ -53,24 +53,24 @@ func (cf *ConversionFlow) StartIfNecessary() (bool, error) { return false, nil } - cf.analytics.Event(anaConsts.CatPpmConversion, "run", anaConsts.SrcStateTool) + cf.analytics.Event(anaConsts.CatPpmConversion, "run") r, err := cf.runSurvey() if err != nil { - cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "error", anaConsts.SrcStateTool, errs.JoinMessage(err)) + cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "error", errs.JoinMessage(err)) return true, locale.WrapError(err, "ppm_conversion_survey_error", "Conversion flow failed.") } if r != accepted { - cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "completed", anaConsts.SrcStateTool, r.String()) + cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "completed", r.String()) return true, locale.NewInputError("ppm_conversion_rejected", "Virtual environment creation cancelled.") } err = cf.createVirtualEnv() if err != nil { - cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "error", anaConsts.SrcStateTool, errs.JoinMessage(err)) + cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "error", errs.JoinMessage(err)) return true, locale.WrapError(err, "ppm_conversion_venv_error", "Failed to create a project.") } - cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "completed", anaConsts.SrcStateTool, r.String()) + cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "completed", r.String()) return true, nil } @@ -103,7 +103,7 @@ func (cf *ConversionFlow) runSurvey() (conversionResult, error) { choices[0]: "create-virtual-env-1", choices[1]: "asked-why", } - cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "selection", anaConsts.SrcStateTool, eventChoices[choice]) + cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "selection", eventChoices[choice]) if choice == choices[0] { return accepted, nil @@ -141,7 +141,7 @@ func (cf *ConversionFlow) explainVirtualEnv() (conversionResult, error) { convertAnswerCreate: "create-virtual-env-2", no: "still-wants-ppm", } - cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "selection", anaConsts.SrcStateTool, eventChoices[choice]) + cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "selection", eventChoices[choice]) switch choice { case convertAnswerCreate: @@ -179,7 +179,7 @@ func (cf *ConversionFlow) explainAskFeedback() (conversionResult, error) { ok: "create-virtual-env-3", exit: "exit", } - cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "selection", anaConsts.SrcStateTool, eventChoices[choice]) + cf.analytics.EventWithLabel(anaConsts.CatPpmConversion, "selection", eventChoices[choice]) if choice == ok { return accepted, nil diff --git a/internal/runners/ppm/shim.go b/internal/runners/ppm/shim.go index 8164220868..6d375cbcce 100644 --- a/internal/runners/ppm/shim.go +++ b/internal/runners/ppm/shim.go @@ -81,9 +81,9 @@ func (s *Shim) RunList(converted bool, args ...string) error { func (s *Shim) shim(intercepted, replaced string, args ...string) error { err := s.executeShim(intercepted, replaced, args...) if err != nil { - s.analytics.EventWithLabel(constants.CatPPMShimCmd, intercepted, constants.SrcStateTool, fmt.Sprintf("error: %v", errs.JoinMessage(err))) + s.analytics.EventWithLabel(constants.CatPPMShimCmd, intercepted, fmt.Sprintf("error: %v", errs.JoinMessage(err))) } else { - s.analytics.EventWithLabel(constants.CatPPMShimCmd, intercepted, constants.SrcStateTool, "success") + s.analytics.EventWithLabel(constants.CatPPMShimCmd, intercepted, "success") } return err } @@ -91,7 +91,7 @@ func (s *Shim) shim(intercepted, replaced string, args ...string) error { func (s *Shim) executeShim(intercepted, replaced string, args ...string) error { if s.project == nil { // TODO: Replace this function call when conversion flow is complete - s.analytics.Event(constants.CatPPMShimCmd, "tutorial", constants.SrcStateTool) + s.analytics.Event(constants.CatPPMShimCmd, "tutorial") return tutorial() } diff --git a/internal/runners/tutorial/tutorial.go b/internal/runners/tutorial/tutorial.go index 867d273f79..c1f9fb00dc 100644 --- a/internal/runners/tutorial/tutorial.go +++ b/internal/runners/tutorial/tutorial.go @@ -45,7 +45,7 @@ type NewProjectParams struct { } func (t *Tutorial) RunNewProject(params NewProjectParams) error { - t.analytics.EventWithLabel(anaConsts.CatTutorial, "run", anaConsts.SrcStateTool, fmt.Sprintf("skipIntro=%v,language=%v", params.SkipIntro, params.Language.String())) + t.analytics.EventWithLabel(anaConsts.CatTutorial, "run", fmt.Sprintf("skipIntro=%v,language=%v", params.SkipIntro, params.Language.String())) // Print intro if !params.SkipIntro { @@ -75,7 +75,7 @@ func (t *Tutorial) RunNewProject(params NewProjectParams) error { if lang == language.Unknown || lang == language.Unset { return locale.NewError("err_tutorial_language_unknown", "Invalid language selected: {{.V0}}.", choice) } - t.analytics.EventWithLabel(anaConsts.CatTutorial, "choose-language", anaConsts.SrcStateTool, lang.String()) + t.analytics.EventWithLabel(anaConsts.CatTutorial, "choose-language", lang.String()) } // Prompt for project name @@ -125,7 +125,7 @@ func (t *Tutorial) RunNewProject(params NewProjectParams) error { // authFlow is invoked when the user is not authenticated, it will prompt for sign in or sign up func (t *Tutorial) authFlow() error { - t.analytics.Event(anaConsts.CatTutorial, "authentication-flow", anaConsts.SrcStateTool) + t.analytics.Event(anaConsts.CatTutorial, "authentication-flow") // Sign in / Sign up choices signIn := locale.Tl("tutorial_signin", "Sign In") @@ -147,17 +147,17 @@ func (t *Tutorial) authFlow() error { // Evaluate user selection switch choice { case signIn: - t.analytics.EventWithLabel(anaConsts.CatTutorial, "authentication-action", anaConsts.SrcStateTool, "sign-in") + t.analytics.EventWithLabel(anaConsts.CatTutorial, "authentication-action", "sign-in") if err := runbits.Invoke(t.outputer, "auth"); err != nil { return locale.WrapInputError(err, "err_tutorial_signin", "Sign in failed. You could try manually signing in by running `state auth`.") } case signUpCLI: - t.analytics.EventWithLabel(anaConsts.CatTutorial, "authentication-action", anaConsts.SrcStateTool, "sign-up") + t.analytics.EventWithLabel(anaConsts.CatTutorial, "authentication-action", "sign-up") if err := runbits.Invoke(t.outputer, "auth", "signup"); err != nil { return locale.WrapInputError(err, "err_tutorial_signup", "Sign up failed. You could try manually signing up by running `state auth signup`.") } case signUpBrowser: - t.analytics.EventWithLabel(anaConsts.CatTutorial, "authentication-action", anaConsts.SrcStateTool, "sign-up-browser") + t.analytics.EventWithLabel(anaConsts.CatTutorial, "authentication-action", "sign-up-browser") err := open.Run(constants.PlatformSignupURL) if err != nil { return locale.WrapInputError(err, "err_tutorial_browser", "Could not open browser, please manually navigate to {{.V0}}.", constants.PlatformSignupURL) @@ -172,7 +172,7 @@ func (t *Tutorial) authFlow() error { return locale.WrapError(err, "err_tutorial_auth", "Could not authenticate after invoking `state auth ..`.") } - t.analytics.Event(anaConsts.CatTutorial, "authentication-flow-complete", anaConsts.SrcStateTool) + t.analytics.Event(anaConsts.CatTutorial, "authentication-flow-complete") return nil } diff --git a/internal/svcctl/comm.go b/internal/svcctl/comm.go index 0582c2dfae..16e820ae2a 100644 --- a/internal/svcctl/comm.go +++ b/internal/svcctl/comm.go @@ -78,7 +78,7 @@ type Resolver interface { } type AnalyticsReporter interface { - Event(category, action, source string, dims ...*dimensions.Values) + EventWithSource(category, action, source string, dims ...*dimensions.Values) } func HeartbeatHandler(cfg *config.Instance, resolver Resolver, analyticsReporter AnalyticsReporter) ipc.RequestHandler { @@ -138,7 +138,7 @@ func HeartbeatHandler(cfg *config.Instance, resolver Resolver, analyticsReporter } logging.Debug("Firing runtime usage events for %s", metaData.Namespace) - analyticsReporter.Event(constants.CatRuntimeUsage, constants.ActRuntimeAttempt, constants.SrcExecutor, dims) + analyticsReporter.EventWithSource(constants.CatRuntimeUsage, constants.ActRuntimeAttempt, constants.SrcExecutor, dims) _, err = resolver.ReportRuntimeUsage(context.Background(), pidNum, hb.ExecPath, dimsJSON) if err != nil { multilog.Critical("Heartbeat Failure: Failed to report runtime usage in heartbeat handler: %s", errs.JoinMessage(err)) diff --git a/internal/updater/checker.go b/internal/updater/checker.go index b6c3031659..1e2e8de265 100644 --- a/internal/updater/checker.go +++ b/internal/updater/checker.go @@ -143,7 +143,7 @@ func (u *Checker) GetUpdateInfo(desiredChannel, desiredVersion string) (*Availab err = errs.Wrap(err, "Could not fetch update info from %s", infoURL) } - u.an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateCheck, anaConst.SrcStateTool, label, &dimensions.Values{ + u.an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateCheck, label, &dimensions.Values{ Version: ptr.To(desiredVersion), Error: ptr.To(msg), }) @@ -159,6 +159,6 @@ func (u *Checker) GetUpdateInfo(desiredChannel, desiredVersion string) (*Availab info.url = u.fileURL + "/" + info.Path - u.an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateCheck, anaConst.SrcStateTool, anaConst.UpdateLabelAvailable, &dimensions.Values{Version: ptr.To(info.Version)}) + u.an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateCheck, anaConst.UpdateLabelAvailable, &dimensions.Values{Version: ptr.To(info.Version)}) return info, nil } diff --git a/internal/updater/fetcher.go b/internal/updater/fetcher.go index af8d5c41d6..747d75d976 100644 --- a/internal/updater/fetcher.go +++ b/internal/updater/fetcher.go @@ -70,7 +70,7 @@ func (f *Fetcher) Fetch(update *AvailableUpdate, targetDir string) error { } func (f *Fetcher) analyticsEvent(version, msg string) { - f.an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateDownload, anaConst.SrcStateTool, anaConst.UpdateLabelFailed, &dimensions.Values{ + f.an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateDownload, anaConst.UpdateLabelFailed, &dimensions.Values{ TargetVersion: ptr.To(version), Error: ptr.To(msg), }) diff --git a/internal/updater/updater.go b/internal/updater/updater.go index d656dd1ebc..d72bcb7881 100644 --- a/internal/updater/updater.go +++ b/internal/updater/updater.go @@ -207,5 +207,5 @@ func (u *AvailableUpdate) analyticsEvent(action, label, version, msg string) { dims.Error = ptr.To(msg) } - u.an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateDownload, anaConst.SrcStateTool, label, dims) + u.an.EventWithLabel(anaConst.CatUpdates, anaConst.ActUpdateDownload, label, dims) } diff --git a/pkg/cmdlets/errors/errors.go b/pkg/cmdlets/errors/errors.go index 0c0af27b5f..a47b2747c0 100644 --- a/pkg/cmdlets/errors/errors.go +++ b/pkg/cmdlets/errors/errors.go @@ -153,7 +153,7 @@ func ReportError(err error, cmd *captain.Command, an analytics.Dispatcher) { } } - an.EventWithLabel(anaConst.CatDebug, action, anaConst.SrcStateTool, strings.Join(label, " "), &dimensions.Values{ + an.EventWithLabel(anaConst.CatDebug, action, strings.Join(label, " "), &dimensions.Values{ Error: ptr.To(errorMsg), }) diff --git a/pkg/cmdlets/git/git.go b/pkg/cmdlets/git/git.go index 70c7e0e75b..f0e496685a 100644 --- a/pkg/cmdlets/git/git.go +++ b/pkg/cmdlets/git/git.go @@ -122,7 +122,7 @@ func EnsureCorrectProject(owner, name, projectFilePath, repoURL string, out outp if err != nil { return locale.WrapError(err, "err_git_update_mismatch", "Could not update projectfile namespace") } - an.Event(anaConsts.CatMisc, "git-project-mismatch", anaConsts.SrcStateTool) + an.Event(anaConsts.CatMisc, "git-project-mismatch") } return nil diff --git a/pkg/platform/runtime/analytics/analytics.go b/pkg/platform/runtime/analytics/analytics.go new file mode 100644 index 0000000000..91744bf708 --- /dev/null +++ b/pkg/platform/runtime/analytics/analytics.go @@ -0,0 +1,25 @@ +package analytics + +import ( + "github.com/ActiveState/cli/internal/analytics" + anaConsts "github.com/ActiveState/cli/internal/analytics/constants" + "github.com/ActiveState/cli/internal/analytics/dimensions" + "github.com/ActiveState/cli/internal/constants" + "github.com/ActiveState/cli/internal/osutils" +) + +var isExecutor bool + +func init() { + if osutils.Executable() == constants.StateExecutorCmd { + isExecutor = true + } +} + +// Event emits an analytics event with the proper source (State Tool or Executor). +func Event(an analytics.Dispatcher, category, action string, dims ...*dimensions.Values) { + if isExecutor { + an.EventWithSource(category, action, anaConsts.SrcExecutor, dims...) + } + an.Event(category, action, dims...) +} diff --git a/pkg/platform/runtime/runtime.go b/pkg/platform/runtime/runtime.go index 6b3ee7ee29..a06a2108bb 100644 --- a/pkg/platform/runtime/runtime.go +++ b/pkg/platform/runtime/runtime.go @@ -24,6 +24,7 @@ import ( bpModel "github.com/ActiveState/cli/pkg/platform/api/buildplanner/model" "github.com/ActiveState/cli/pkg/platform/authentication" "github.com/ActiveState/cli/pkg/platform/model" + anaRun "github.com/ActiveState/cli/pkg/platform/runtime/analytics" "github.com/ActiveState/cli/pkg/platform/runtime/envdef" "github.com/ActiveState/cli/pkg/platform/runtime/setup" "github.com/ActiveState/cli/pkg/platform/runtime/setup/buildlog" @@ -50,14 +51,6 @@ func IsNeedsUpdateError(err error) bool { return errs.Matches(err, &NeedsUpdateError{}) } -var analyticsSource string = anaConsts.SrcStateTool - -func init() { - if osutils.Executable() == constants.StateExecutorCmd { - analyticsSource = anaConsts.SrcExecutor - } -} - func newRuntime(target setup.Targeter, an analytics.Dispatcher, svcModel *model.SvcModel) (*Runtime, error) { rt := &Runtime{ target: target, @@ -84,7 +77,7 @@ func New(target setup.Targeter, an analytics.Dispatcher, svcm *model.SvcModel) ( return &Runtime{disabled: true, target: target}, nil } recordAttempt(an, target) - an.Event(anaConsts.CatRuntime, anaConsts.ActRuntimeStart, analyticsSource, &dimensions.Values{ + anaRun.Event(an, anaConsts.CatRuntime, anaConsts.ActRuntimeStart, &dimensions.Values{ Trigger: ptr.To(target.Trigger().String()), Headless: ptr.To(strconv.FormatBool(target.Headless())), CommitID: ptr.To(target.CommitUUID().String()), @@ -94,7 +87,7 @@ func New(target setup.Targeter, an analytics.Dispatcher, svcm *model.SvcModel) ( r, err := newRuntime(target, an, svcm) if err == nil { - an.Event(anaConsts.CatRuntime, anaConsts.ActRuntimeCache, analyticsSource, &dimensions.Values{ + anaRun.Event(an, anaConsts.CatRuntime, anaConsts.ActRuntimeCache, &dimensions.Values{ CommitID: ptr.To(target.CommitUUID().String()), }) } @@ -233,7 +226,7 @@ func (r *Runtime) recordCompletion(err error) { message = errs.JoinMessage(err) } - r.analytics.Event(anaConsts.CatRuntime, action, analyticsSource, &dimensions.Values{ + anaRun.Event(r.analytics, anaConsts.CatRuntime, action, &dimensions.Values{ CommitID: ptr.To(r.target.CommitUUID().String()), // Note: ProjectID is set by state-svc since ProjectNameSpace is specified. ProjectNameSpace: ptr.To(ns.String()), @@ -265,7 +258,7 @@ func recordAttempt(an analytics.Dispatcher, target setup.Targeter) { return } - an.Event(anaConsts.CatRuntimeUsage, anaConsts.ActRuntimeAttempt, analyticsSource, usageDims(target)) + anaRun.Event(an, anaConsts.CatRuntimeUsage, anaConsts.ActRuntimeAttempt, usageDims(target)) } func usageDims(target setup.Targeter) *dimensions.Values { diff --git a/pkg/platform/runtime/setup/setup.go b/pkg/platform/runtime/setup/setup.go index 4441bdc5b3..fb2fc33c50 100644 --- a/pkg/platform/runtime/setup/setup.go +++ b/pkg/platform/runtime/setup/setup.go @@ -12,9 +12,6 @@ import ( "sync" "time" - bpModel "github.com/ActiveState/cli/pkg/platform/api/buildplanner/model" - "github.com/ActiveState/cli/pkg/platform/model" - "github.com/ActiveState/cli/internal/analytics" anaConsts "github.com/ActiveState/cli/internal/analytics/constants" "github.com/ActiveState/cli/internal/analytics/dimensions" @@ -26,15 +23,17 @@ import ( "github.com/ActiveState/cli/internal/locale" "github.com/ActiveState/cli/internal/logging" "github.com/ActiveState/cli/internal/multilog" - "github.com/ActiveState/cli/internal/osutils" "github.com/ActiveState/cli/internal/proxyreader" "github.com/ActiveState/cli/internal/rollbar" "github.com/ActiveState/cli/internal/rtutils/ptr" "github.com/ActiveState/cli/internal/svcctl" "github.com/ActiveState/cli/internal/unarchiver" + bpModel "github.com/ActiveState/cli/pkg/platform/api/buildplanner/model" "github.com/ActiveState/cli/pkg/platform/api/inventory/inventory_models" "github.com/ActiveState/cli/pkg/platform/authentication" + "github.com/ActiveState/cli/pkg/platform/model" apimodel "github.com/ActiveState/cli/pkg/platform/model" + anaRun "github.com/ActiveState/cli/pkg/platform/runtime/analytics" "github.com/ActiveState/cli/pkg/platform/runtime/artifact" "github.com/ActiveState/cli/pkg/platform/runtime/artifactcache" "github.com/ActiveState/cli/pkg/platform/runtime/buildplan" @@ -433,12 +432,8 @@ func (s *Setup) fetchAndInstallArtifactsFromBuildPlan(installFunc artifactInstal } // send analytics build event, if a new runtime has to be built in the cloud - analyticsSource := anaConsts.SrcStateTool - if osutils.ExecutableName() == constants.StateExecutorCmd { - analyticsSource = anaConsts.SrcExecutor - } if buildResult.BuildStatus == bpModel.Started { - s.analytics.Event(anaConsts.CatRuntime, anaConsts.ActRuntimeBuild, analyticsSource, dimensions) + anaRun.Event(s.analytics, anaConsts.CatRuntime, anaConsts.ActRuntimeBuild, dimensions) } changedArtifacts, err := buildplan.NewBaseArtifactChangesetByBuildPlan(buildResult.Build, false) @@ -546,8 +541,8 @@ func (s *Setup) fetchAndInstallArtifactsFromBuildPlan(installFunc artifactInstal // only send the download analytics event, if we have to install artifacts that are not yet installed if len(artifactsToInstall) > 0 { - // if we get here, we dowload artifacts - s.analytics.Event(anaConsts.CatRuntime, anaConsts.ActRuntimeDownload, analyticsSource, dimensions) + // if we get here, we download artifacts + anaRun.Event(s.analytics, anaConsts.CatRuntime, anaConsts.ActRuntimeDownload, dimensions) } err = s.installArtifactsFromBuild(buildResult, runtimeArtifacts, artifact.ArtifactIDsToMap(artifactsToInstall), downloadablePrebuiltResults, setup, installFunc, logFilePath)