dashboard.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import os
  2. import json
  3. import logging
  4. import asyncio
  5. import aiohttp
  6. import pandas as pd
  7. import plotly.express as px
  8. from typing import List, Dict, Optional
  9. from pathlib import Path
  10. class AsyncCircleCIClient:
  11. def __init__(self, token: str, project_slug: str):
  12. self.token = token
  13. self.project_slug = project_slug
  14. self.base_url = "https://circleci.com/api/v2"
  15. self.headers = {
  16. "Circle-Token": token,
  17. "Accept": "application/json"
  18. }
  19. self.logger = logging.getLogger("CircleCI")
  20. async def get_json(self, session: aiohttp.ClientSession, url: str, params: Dict = None) -> Dict:
  21. async with session.get(url, params=params) as response:
  22. response.raise_for_status()
  23. return await response.json()
  24. async def get_recent_pipelines(self, session: aiohttp.ClientSession, limit: int = 50) -> List[Dict]:
  25. self.logger.info(f"Fetching {limit} recent pipelines...")
  26. url = f"{self.base_url}/project/{self.project_slug}/pipeline"
  27. params = {"limit": limit * 2}
  28. data = await self.get_json(session, url, params)
  29. pipelines = [
  30. p for p in data["items"]
  31. if p["state"] == "created"
  32. and p.get("trigger_parameters", {}).get("git", {}).get("branch") == "main"
  33. ][:limit]
  34. self.logger.info(f"Found {len(pipelines)} successful main branch pipelines")
  35. return pipelines
  36. async def get_workflow_jobs(self, session: aiohttp.ClientSession, pipeline_id: str) -> List[Dict]:
  37. self.logger.debug(f"Fetching workflows for pipeline {pipeline_id}")
  38. url = f"{self.base_url}/pipeline/{pipeline_id}/workflow"
  39. workflows_data = await self.get_json(session, url)
  40. workflows = workflows_data["items"]
  41. # Fetch all jobs for all workflows in parallel
  42. jobs_tasks = []
  43. for workflow in workflows:
  44. url = f"{self.base_url}/workflow/{workflow['id']}/job"
  45. jobs_tasks.append(self.get_json(session, url))
  46. jobs_responses = await asyncio.gather(*jobs_tasks, return_exceptions=True)
  47. all_jobs = []
  48. for jobs_data in jobs_responses:
  49. if isinstance(jobs_data, Exception):
  50. continue
  51. all_jobs.extend(jobs_data["items"])
  52. return all_jobs
  53. async def get_artifacts(self, session: aiohttp.ClientSession, job_number: str) -> List[Dict]:
  54. url = f"{self.base_url}/project/{self.project_slug}/{job_number}/artifacts"
  55. data = await self.get_json(session, url)
  56. return data["items"]
  57. class PackageSizeTracker:
  58. def __init__(self, token: str, project_slug: str, debug: bool = False):
  59. self.setup_logging(debug)
  60. self.client = AsyncCircleCIClient(token, project_slug)
  61. self.logger = logging.getLogger("PackageSizeTracker")
  62. def setup_logging(self, debug: bool):
  63. level = logging.DEBUG if debug else logging.INFO
  64. logging.basicConfig(
  65. level=level,
  66. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  67. datefmt='%H:%M:%S'
  68. )
  69. def extract_commit_info(self, pipeline: Dict) -> Optional[Dict]:
  70. try:
  71. if 'trigger_parameters' in pipeline:
  72. github_app = pipeline['trigger_parameters'].get('github_app', {})
  73. if github_app:
  74. return {
  75. 'commit_hash': github_app.get('checkout_sha'),
  76. 'web_url': f"{github_app.get('repo_url')}/commit/{github_app.get('checkout_sha')}"
  77. }
  78. git_params = pipeline['trigger_parameters'].get('git', {})
  79. if git_params:
  80. return {
  81. 'commit_hash': git_params.get('checkout_sha'),
  82. 'web_url': f"{git_params.get('repo_url')}/commit/{git_params.get('checkout_sha')}"
  83. }
  84. self.logger.warning(f"Could not find commit info in pipeline {pipeline['id']}")
  85. return None
  86. except Exception as e:
  87. self.logger.error(f"Error extracting commit info: {str(e)}")
  88. return None
  89. async def process_pipeline(self, session: aiohttp.ClientSession, pipeline: Dict) -> Optional[Dict]:
  90. try:
  91. commit_info = self.extract_commit_info(pipeline)
  92. if not commit_info:
  93. return None
  94. jobs = await self.client.get_workflow_jobs(session, pipeline["id"])
  95. size_job = next(
  96. (j for j in jobs if j["name"] == "measure_pip_sizes" and j["status"] == "success"),
  97. None
  98. )
  99. if not size_job:
  100. self.logger.debug(f"No measure_pip_sizes job found for pipeline {pipeline['id']}")
  101. return None
  102. artifacts = await self.client.get_artifacts(session, size_job["job_number"])
  103. size_report = next(
  104. (a for a in artifacts if a["path"].endswith("pip-sizes.json")),
  105. None
  106. )
  107. if not size_report:
  108. self.logger.debug(f"No pip-sizes.json artifact found for job {size_job['job_number']}")
  109. return None
  110. json_data = await self.client.get_json(session, size_report["url"])
  111. data_point = {
  112. "commit_hash": commit_info['commit_hash'],
  113. "commit_url": commit_info['web_url'],
  114. "timestamp": pipeline.get("created_at", pipeline.get("updated_at")),
  115. "total_size_mb": json_data["total_size_mb"],
  116. "packages": json_data["packages"]
  117. }
  118. self.logger.info(
  119. f"Processed pipeline {pipeline['id']}: "
  120. f"commit {commit_info['commit_hash'][:7]}, "
  121. f"size {json_data['total_size_mb']:.2f}MB"
  122. )
  123. return data_point
  124. except Exception as e:
  125. self.logger.error(f"Error processing pipeline {pipeline['id']}: {str(e)}")
  126. return None
  127. async def collect_data(self) -> List[Dict]:
  128. self.logger.info("Starting data collection...")
  129. async with aiohttp.ClientSession(headers=self.client.headers) as session:
  130. # Get pipelines
  131. pipelines = await self.client.get_recent_pipelines(session, 50)
  132. # Process all pipelines in parallel
  133. tasks = [self.process_pipeline(session, pipeline) for pipeline in pipelines]
  134. results = await asyncio.gather(*tasks)
  135. # Filter out None results
  136. data_points = [r for r in results if r is not None]
  137. return data_points
  138. def generate_report(self, data: List[Dict], output_dir: str = "reports") -> Optional[str]:
  139. self.logger.info("Generating report...")
  140. if not data:
  141. self.logger.error("No data to generate report from!")
  142. return None
  143. df = pd.DataFrame(data)
  144. df['timestamp'] = pd.to_datetime(df['timestamp'])
  145. df = df.sort_values('timestamp')
  146. # commit_url is already in the data from process_pipeline
  147. # Create trend plot with updated styling
  148. fig = px.line(
  149. df,
  150. x='timestamp',
  151. y='total_size_mb',
  152. title='Package Size Trend',
  153. markers=True,
  154. hover_data={'commit_hash': True, 'timestamp': True, 'total_size_mb': ':.2f'},
  155. custom_data=['commit_hash', 'commit_url']
  156. )
  157. fig.update_layout(
  158. xaxis_title="Date",
  159. yaxis_title="Total Size (MB)",
  160. hovermode='x unified',
  161. plot_bgcolor='white',
  162. paper_bgcolor='white',
  163. font=dict(size=12),
  164. title_x=0.5,
  165. )
  166. fig.update_traces(
  167. line=dict(width=2),
  168. marker=dict(size=8),
  169. hovertemplate="<br>".join([
  170. "Commit: %{customdata[0]}",
  171. "Size: %{y:.2f}MB",
  172. "Date: %{x}",
  173. "<extra>Click to view commit</extra>"
  174. ])
  175. )
  176. # Add JavaScript for click handling
  177. fig.update_layout(
  178. clickmode='event',
  179. annotations=[
  180. dict(
  181. text="Click any point to view the commit on GitHub",
  182. xref="paper", yref="paper",
  183. x=0, y=1.05,
  184. showarrow=False
  185. )
  186. ]
  187. )
  188. # Ensure output directory exists
  189. output_dir = Path(output_dir)
  190. output_dir.mkdir(parents=True, exist_ok=True)
  191. # Save plot
  192. plot_path = output_dir / "package_size_trend.html"
  193. fig.write_html(
  194. str(plot_path),
  195. include_plotlyjs=True,
  196. full_html=True,
  197. post_script="""
  198. const plot = document.getElementsByClassName('plotly-graph-div')[0];
  199. plot.on('plotly_click', function(data) {
  200. const point = data.points[0];
  201. const commitUrl = point.customdata[1];
  202. window.open(commitUrl, '_blank');
  203. });
  204. """
  205. )
  206. # Generate summary
  207. latest = df.iloc[-1]
  208. previous = df.iloc[-2] if len(df) > 1 else latest
  209. size_change = latest['total_size_mb'] - previous['total_size_mb']
  210. latest_data = {
  211. 'timestamp': latest['timestamp'].isoformat(),
  212. 'commit_hash': latest['commit_hash'],
  213. 'total_size_mb': latest['total_size_mb'],
  214. 'size_change_mb': size_change,
  215. 'packages': latest['packages']
  216. }
  217. with open(output_dir / 'latest_data.json', 'w') as f:
  218. json.dump(latest_data, f, indent=2)
  219. self._print_summary(latest_data)
  220. self.logger.info(f"Report generated in {output_dir}")
  221. return str(plot_path)
  222. def _print_summary(self, latest_data: Dict):
  223. print("\n=== Package Size Summary ===")
  224. print(f"Timestamp: {latest_data['timestamp']}")
  225. print(f"Commit: {latest_data['commit_hash'][:7]}")
  226. print(f"Total Size: {latest_data['total_size_mb']:.2f}MB")
  227. change = latest_data['size_change_mb']
  228. change_symbol = "↓" if change <= 0 else "↑"
  229. print(f"Change: {change_symbol} {abs(change):.2f}MB")
  230. print("\nTop 5 Largest Packages:")
  231. sorted_packages = sorted(latest_data['packages'], key=lambda x: x['size_mb'], reverse=True)
  232. for pkg in sorted_packages[:5]:
  233. print(f"- {pkg['name']}: {pkg['size_mb']:.2f}MB")
  234. print("\n")
  235. async def main():
  236. token = os.getenv("CIRCLECI_TOKEN")
  237. project_slug = os.getenv("CIRCLECI_PROJECT_SLUG")
  238. debug = os.getenv("DEBUG", "").lower() in ("true", "1", "yes")
  239. if not token or not project_slug:
  240. print("Error: Please set CIRCLECI_TOKEN and CIRCLECI_PROJECT_SLUG environment variables")
  241. return
  242. tracker = PackageSizeTracker(token, project_slug, debug)
  243. try:
  244. data = await tracker.collect_data()
  245. if not data:
  246. print("No data found!")
  247. return
  248. report_path = tracker.generate_report(data)
  249. if report_path:
  250. print(f"\nDetailed report available at: {report_path}")
  251. except Exception as e:
  252. logging.error(f"Error: {str(e)}")
  253. if debug:
  254. raise
  255. if __name__ == "__main__":
  256. asyncio.run(main())