|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import time |
| 4 | +from functools import wraps |
| 5 | +from importlib.metadata import version |
| 6 | +from typing import Any, Callable, Dict, Optional |
| 7 | + |
| 8 | +from uipath._cli._utils._common import get_claim_from_token |
| 9 | +from uipath.telemetry._track import ( |
| 10 | + _get_project_key, |
| 11 | + is_telemetry_enabled, |
| 12 | + track_cli_event, |
| 13 | +) |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +# Telemetry event name template for Application Insights |
| 18 | +CLI_COMMAND_EVENT = "Cli.{command}" |
| 19 | + |
| 20 | + |
| 21 | +class CliTelemetryTracker: |
| 22 | + """Tracks CLI command execution and sends telemetry to Application Insights. |
| 23 | +
|
| 24 | + Sends a single event per command execution at completion with: |
| 25 | + - Status: "Completed" or "Failed" |
| 26 | + - Success: Boolean indicating success/failure |
| 27 | + - Error details (if failed) |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__(self) -> None: |
| 31 | + self._start_times: Dict[str, float] = {} |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def _get_event_name(command: str) -> str: |
| 35 | + return f"Cli.{command.capitalize()}" |
| 36 | + |
| 37 | + def _enrich_properties(self, properties: Dict[str, Any]) -> None: |
| 38 | + """Enrich properties with common context information. |
| 39 | +
|
| 40 | + Args: |
| 41 | + properties: The properties dictionary to enrich. |
| 42 | + """ |
| 43 | + # Add UiPath context |
| 44 | + project_key = _get_project_key() |
| 45 | + if project_key: |
| 46 | + properties["AgentId"] = project_key |
| 47 | + |
| 48 | + # Get organization ID |
| 49 | + organization_id = os.getenv("UIPATH_ORGANIZATION_ID") |
| 50 | + if organization_id: |
| 51 | + properties["CloudOrganizationId"] = organization_id |
| 52 | + |
| 53 | + # Get tenant ID |
| 54 | + tenant_id = os.getenv("UIPATH_TENANT_ID") |
| 55 | + if tenant_id: |
| 56 | + properties["CloudTenantId"] = tenant_id |
| 57 | + |
| 58 | + # Get CloudUserId from JWT token |
| 59 | + try: |
| 60 | + cloud_user_id = get_claim_from_token("sub") |
| 61 | + if cloud_user_id: |
| 62 | + properties["CloudUserId"] = cloud_user_id |
| 63 | + except Exception: |
| 64 | + pass |
| 65 | + |
| 66 | + properties["SessionId"] = "nosession" # Placeholder for session ID |
| 67 | + |
| 68 | + try: |
| 69 | + properties["SDKVersion"] = version("uipath") |
| 70 | + except Exception: |
| 71 | + pass |
| 72 | + |
| 73 | + properties["IsGithubCI"] = bool(os.getenv("GITHUB_ACTIONS")) |
| 74 | + |
| 75 | + # Add source identifier |
| 76 | + properties["Source"] = "uipath-python-cli" |
| 77 | + properties["ApplicationName"] = "UiPath.AgentCli" |
| 78 | + |
| 79 | + def track_command_start(self, command: str) -> None: |
| 80 | + """Record the start time for duration calculation.""" |
| 81 | + try: |
| 82 | + self._start_times[command] = time.time() |
| 83 | + logger.debug(f"Started tracking CLI command: {command}") |
| 84 | + |
| 85 | + except Exception as e: |
| 86 | + logger.debug(f"Error recording CLI command start time: {e}") |
| 87 | + |
| 88 | + def track_command_end( |
| 89 | + self, |
| 90 | + command: str, |
| 91 | + duration_ms: Optional[int] = None, |
| 92 | + ) -> None: |
| 93 | + try: |
| 94 | + if duration_ms is None: |
| 95 | + start_time = self._start_times.pop(command, None) |
| 96 | + if start_time: |
| 97 | + duration_ms = int((time.time() - start_time) * 1000) |
| 98 | + |
| 99 | + properties: Dict[str, Any] = { |
| 100 | + "Command": command, |
| 101 | + "Status": "Completed", |
| 102 | + "Success": True, |
| 103 | + } |
| 104 | + |
| 105 | + if duration_ms is not None: |
| 106 | + properties["DurationMs"] = duration_ms |
| 107 | + |
| 108 | + self._enrich_properties(properties) |
| 109 | + |
| 110 | + track_cli_event(self._get_event_name(command), properties) |
| 111 | + logger.debug(f"Tracked CLI command completed: {command}") |
| 112 | + |
| 113 | + except Exception as e: |
| 114 | + logger.debug(f"Error tracking CLI command end: {e}") |
| 115 | + |
| 116 | + def track_command_failed( |
| 117 | + self, |
| 118 | + command: str, |
| 119 | + duration_ms: Optional[int] = None, |
| 120 | + exception: Optional[Exception] = None, |
| 121 | + ) -> None: |
| 122 | + try: |
| 123 | + if duration_ms is None: |
| 124 | + start_time = self._start_times.pop(command, None) |
| 125 | + if start_time: |
| 126 | + duration_ms = int((time.time() - start_time) * 1000) |
| 127 | + |
| 128 | + properties: Dict[str, Any] = { |
| 129 | + "Command": command, |
| 130 | + "Status": "Failed", |
| 131 | + "Success": False, |
| 132 | + } |
| 133 | + |
| 134 | + if duration_ms is not None: |
| 135 | + properties["DurationMs"] = duration_ms |
| 136 | + |
| 137 | + if exception is not None: |
| 138 | + properties["ErrorType"] = type(exception).__name__ |
| 139 | + properties["ErrorMessage"] = str(exception)[:500] |
| 140 | + |
| 141 | + self._enrich_properties(properties) |
| 142 | + |
| 143 | + track_cli_event(self._get_event_name(command), properties) |
| 144 | + logger.debug(f"Tracked CLI command failed: {command}") |
| 145 | + |
| 146 | + except Exception as e: |
| 147 | + logger.debug(f"Error tracking CLI command failed: {e}") |
| 148 | + |
| 149 | + |
| 150 | +def track_command(command: str) -> Callable[..., Any]: |
| 151 | + """Decorator to track CLI command execution. |
| 152 | +
|
| 153 | + Sends an event (Cli.<Command>) to Application Insights at command |
| 154 | + completion with the execution outcome. |
| 155 | +
|
| 156 | + Properties tracked include: |
| 157 | + - Command: The command name |
| 158 | + - Status: Execution outcome ("Completed" or "Failed") |
| 159 | + - Success: Whether the command succeeded (true/false) |
| 160 | + - DurationMs: Execution time in milliseconds |
| 161 | + - ErrorType: Exception type name (on failure) |
| 162 | + - ErrorMessage: Exception message (on failure, truncated to 500 chars) |
| 163 | + - AgentId: Project key from .uipath/.telemetry.json (GUID) |
| 164 | + - Version: Package version (uipath package) |
| 165 | + - ProjectId, CloudOrganizationId, etc. (if available) |
| 166 | +
|
| 167 | + Telemetry failures are silently ignored to ensure CLI execution |
| 168 | + is never blocked by telemetry issues. |
| 169 | +
|
| 170 | + Args: |
| 171 | + command: The CLI command name (e.g., "pack", "publish", "run"). |
| 172 | +
|
| 173 | + Returns: |
| 174 | + A decorator function that wraps the CLI command. |
| 175 | +
|
| 176 | + Example: |
| 177 | + @click.command() |
| 178 | + @track_command("pack") |
| 179 | + def pack(root, nolock): |
| 180 | + ... |
| 181 | + """ |
| 182 | + |
| 183 | + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: |
| 184 | + @wraps(func) |
| 185 | + def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 186 | + if not is_telemetry_enabled() or os.getenv("UIPATH_JOB_KEY"): |
| 187 | + return func(*args, **kwargs) |
| 188 | + |
| 189 | + tracker = CliTelemetryTracker() |
| 190 | + tracker.track_command_start(command) |
| 191 | + |
| 192 | + try: |
| 193 | + result = func(*args, **kwargs) |
| 194 | + tracker.track_command_end(command) |
| 195 | + return result |
| 196 | + |
| 197 | + except Exception as e: |
| 198 | + tracker.track_command_failed(command, exception=e) |
| 199 | + raise |
| 200 | + |
| 201 | + return wrapper |
| 202 | + |
| 203 | + return decorator |
0 commit comments