|
| 1 | +""" |
| 2 | +Parca Agent integration for the self-contained coordinator. |
| 3 | +
|
| 4 | +This module provides functions to check if parca-agent snap is available |
| 5 | +and to update its external labels with benchmark metadata for profiling correlation. |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +import shutil |
| 10 | +import subprocess |
| 11 | +from typing import Dict |
| 12 | + |
| 13 | + |
| 14 | +def check_parca_agent_available() -> bool: |
| 15 | + """ |
| 16 | + Check if snap and parca-agent are available on the system. |
| 17 | +
|
| 18 | + Returns True only if: |
| 19 | + 1. snap command exists |
| 20 | + 2. parca-agent snap is installed |
| 21 | + 3. parca-agent service is running |
| 22 | + """ |
| 23 | + # Step 1: Check if snap command exists |
| 24 | + if shutil.which("snap") is None: |
| 25 | + logging.info("snap command not found - parca-agent integration disabled") |
| 26 | + return False |
| 27 | + |
| 28 | + # Step 2: Check if parca-agent snap is installed |
| 29 | + try: |
| 30 | + result = subprocess.run( |
| 31 | + ["snap", "list", "parca-agent"], |
| 32 | + capture_output=True, |
| 33 | + text=True, |
| 34 | + timeout=10, |
| 35 | + ) |
| 36 | + if result.returncode != 0: |
| 37 | + logging.info( |
| 38 | + "parca-agent snap not installed - parca-agent integration disabled" |
| 39 | + ) |
| 40 | + return False |
| 41 | + except subprocess.TimeoutExpired: |
| 42 | + logging.warning("Timeout checking parca-agent snap installation") |
| 43 | + return False |
| 44 | + except Exception as e: |
| 45 | + logging.warning(f"Failed to check parca-agent snap: {e}") |
| 46 | + return False |
| 47 | + |
| 48 | + # Step 3: Check if parca-agent service is running |
| 49 | + try: |
| 50 | + result = subprocess.run( |
| 51 | + ["snap", "services", "parca-agent"], |
| 52 | + capture_output=True, |
| 53 | + text=True, |
| 54 | + timeout=10, |
| 55 | + ) |
| 56 | + if "active" in result.stdout: |
| 57 | + logging.info( |
| 58 | + "parca-agent snap is available and running - integration enabled" |
| 59 | + ) |
| 60 | + return True |
| 61 | + else: |
| 62 | + logging.info( |
| 63 | + "parca-agent snap is installed but not running - integration disabled" |
| 64 | + ) |
| 65 | + return False |
| 66 | + except subprocess.TimeoutExpired: |
| 67 | + logging.warning("Timeout checking parca-agent service status") |
| 68 | + return False |
| 69 | + except Exception as e: |
| 70 | + logging.warning(f"Failed to check parca-agent service status: {e}") |
| 71 | + return False |
| 72 | + |
| 73 | + |
| 74 | +def sanitize_label_value(value: str, max_length: int = 64) -> str: |
| 75 | + """ |
| 76 | + Sanitize a label value for use in parca-agent external labels. |
| 77 | +
|
| 78 | + - Replaces '=' and ',' with '_' (these are delimiters in the label format) |
| 79 | + - Replaces ':' with '-' (common in build variants) |
| 80 | + - Truncates to max_length |
| 81 | + - Returns 'unknown' for empty/None values |
| 82 | + """ |
| 83 | + if not value: |
| 84 | + return "unknown" |
| 85 | + |
| 86 | + # Convert to string if needed |
| 87 | + value = str(value) |
| 88 | + |
| 89 | + # Replace problematic characters |
| 90 | + value = value.replace("=", "_") |
| 91 | + value = value.replace(",", "_") |
| 92 | + value = value.replace(":", "-") |
| 93 | + value = value.replace("'", "") |
| 94 | + value = value.replace('"', "") |
| 95 | + |
| 96 | + # Truncate if too long |
| 97 | + if len(value) > max_length: |
| 98 | + value = value[:max_length] |
| 99 | + |
| 100 | + return value |
| 101 | + |
| 102 | + |
| 103 | +def build_labels_string(labels: Dict[str, str]) -> str: |
| 104 | + """ |
| 105 | + Build the labels string for the snap set command. |
| 106 | +
|
| 107 | + Format: key1=value1,key2=value2,... |
| 108 | + """ |
| 109 | + parts = [] |
| 110 | + for key, value in labels.items(): |
| 111 | + if value is not None: |
| 112 | + sanitized_value = sanitize_label_value(value) |
| 113 | + parts.append(f"{key}={sanitized_value}") |
| 114 | + return ",".join(parts) |
| 115 | + |
| 116 | + |
| 117 | +def update_parca_agent_labels(labels: Dict[str, str], timeout: int = 30) -> bool: |
| 118 | + """ |
| 119 | + Update parca-agent external labels and restart the agent. |
| 120 | +
|
| 121 | + Args: |
| 122 | + labels: Dictionary of label key-value pairs |
| 123 | + timeout: Timeout in seconds for each subprocess call |
| 124 | +
|
| 125 | + Returns: |
| 126 | + True if successful, False otherwise |
| 127 | + """ |
| 128 | + labels_string = build_labels_string(labels) |
| 129 | + |
| 130 | + # Set the external labels |
| 131 | + try: |
| 132 | + logging.info(f"Setting parca-agent external labels: {labels_string}") |
| 133 | + result = subprocess.run( |
| 134 | + [ |
| 135 | + "sudo", |
| 136 | + "snap", |
| 137 | + "set", |
| 138 | + "parca-agent", |
| 139 | + f"metadata-external-labels={labels_string}", |
| 140 | + ], |
| 141 | + capture_output=True, |
| 142 | + text=True, |
| 143 | + timeout=timeout, |
| 144 | + ) |
| 145 | + if result.returncode != 0: |
| 146 | + logging.warning(f"Failed to set parca-agent labels: {result.stderr}") |
| 147 | + return False |
| 148 | + except subprocess.TimeoutExpired: |
| 149 | + logging.warning("Timeout setting parca-agent labels") |
| 150 | + return False |
| 151 | + except Exception as e: |
| 152 | + logging.warning(f"Failed to set parca-agent labels: {e}") |
| 153 | + return False |
| 154 | + |
| 155 | + # Restart parca-agent to apply the new labels |
| 156 | + try: |
| 157 | + logging.info("Restarting parca-agent to apply new labels") |
| 158 | + result = subprocess.run( |
| 159 | + ["sudo", "snap", "restart", "parca-agent"], |
| 160 | + capture_output=True, |
| 161 | + text=True, |
| 162 | + timeout=timeout, |
| 163 | + ) |
| 164 | + if result.returncode != 0: |
| 165 | + logging.warning(f"Failed to restart parca-agent: {result.stderr}") |
| 166 | + return False |
| 167 | + except subprocess.TimeoutExpired: |
| 168 | + logging.warning("Timeout restarting parca-agent") |
| 169 | + return False |
| 170 | + except Exception as e: |
| 171 | + logging.warning(f"Failed to restart parca-agent: {e}") |
| 172 | + return False |
| 173 | + |
| 174 | + logging.info("Successfully updated parca-agent labels") |
| 175 | + return True |
| 176 | + |
| 177 | + |
| 178 | +def extract_test_labels_from_benchmark_config(benchmark_config: dict) -> Dict[str, str]: |
| 179 | + """ |
| 180 | + Extract test-level labels from a benchmark configuration YAML. |
| 181 | +
|
| 182 | + Extracts: |
| 183 | + - test_name: from 'name' field |
| 184 | + - topology: from 'redis-topologies' (first one) |
| 185 | + - client_tool: from 'clientconfig.tool' |
| 186 | + - tested_commands: from 'tested-commands' (joined with '+') |
| 187 | + - tested_groups: from 'tested-groups' (joined with '+') |
| 188 | + - dataset_name: from 'dbconfig.dataset_name' (if present) |
| 189 | + """ |
| 190 | + labels = {} |
| 191 | + |
| 192 | + # Test name |
| 193 | + if "name" in benchmark_config: |
| 194 | + labels["test_name"] = benchmark_config["name"] |
| 195 | + |
| 196 | + # Topology (take first one if list) |
| 197 | + if "redis-topologies" in benchmark_config: |
| 198 | + topologies = benchmark_config["redis-topologies"] |
| 199 | + if isinstance(topologies, list) and len(topologies) > 0: |
| 200 | + labels["topology"] = topologies[0] |
| 201 | + elif isinstance(topologies, str): |
| 202 | + labels["topology"] = topologies |
| 203 | + |
| 204 | + # Client tool |
| 205 | + if "clientconfig" in benchmark_config: |
| 206 | + clientconfig = benchmark_config["clientconfig"] |
| 207 | + if isinstance(clientconfig, dict) and "tool" in clientconfig: |
| 208 | + labels["client_tool"] = clientconfig["tool"] |
| 209 | + |
| 210 | + # Tested commands (join multiple with '+') |
| 211 | + if "tested-commands" in benchmark_config: |
| 212 | + commands = benchmark_config["tested-commands"] |
| 213 | + if isinstance(commands, list): |
| 214 | + labels["tested_commands"] = "+".join(str(cmd) for cmd in commands) |
| 215 | + elif isinstance(commands, str): |
| 216 | + labels["tested_commands"] = commands |
| 217 | + |
| 218 | + # Tested groups (join multiple with '+') |
| 219 | + if "tested-groups" in benchmark_config: |
| 220 | + groups = benchmark_config["tested-groups"] |
| 221 | + if isinstance(groups, list): |
| 222 | + labels["tested_groups"] = "+".join(str(grp) for grp in groups) |
| 223 | + elif isinstance(groups, str): |
| 224 | + labels["tested_groups"] = groups |
| 225 | + |
| 226 | + # Dataset name (from dbconfig) |
| 227 | + if "dbconfig" in benchmark_config: |
| 228 | + dbconfig = benchmark_config["dbconfig"] |
| 229 | + if isinstance(dbconfig, dict) and "dataset_name" in dbconfig: |
| 230 | + labels["dataset_name"] = dbconfig["dataset_name"] |
| 231 | + elif isinstance(dbconfig, list): |
| 232 | + for item in dbconfig: |
| 233 | + if isinstance(item, dict) and "dataset_name" in item: |
| 234 | + labels["dataset_name"] = item["dataset_name"] |
| 235 | + break |
| 236 | + |
| 237 | + return labels |
0 commit comments