Skip to content

Commit 2a232b8

Browse files
committed
Move more cache functions over
1 parent 0258597 commit 2a232b8

File tree

2 files changed

+81
-79
lines changed

2 files changed

+81
-79
lines changed

tools/analytics/org/analyze_runner_usage.py

Lines changed: 1 addition & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@
5555
"""
5656

5757
import argparse
58-
import json
5958
import logging
6059
import os
6160
from collections import defaultdict
@@ -65,10 +64,9 @@
6564

6665
import requests
6766
import yaml
67+
from cache_manager import get_cache_stats, make_cached_request
6868
from dotenv import load_dotenv
6969

70-
from cache_manager import CACHE_DIR, CacheManager
71-
7270

7371
load_dotenv()
7472

@@ -141,58 +139,9 @@
141139
"linux.g5.4xlarge.nvidia.cpu", # a nonexistent label used by a repo
142140
]
143141

144-
HEADERS = {
145-
"Authorization": f"Bearer {GITHUB_TOKEN}",
146-
"Accept": "application/vnd.github+json",
147-
}
148-
149142
BASE_URL = "https://api.github.com"
150143
WORKFLOW_RUN_LOOKBACK = (datetime.utcnow() - timedelta(days=180)).isoformat() + "Z"
151144

152-
# Global cache manager instance
153-
cache_manager = CacheManager()
154-
155-
156-
def make_cached_request(
157-
url: str, headers: Optional[Dict[str, str]] = None
158-
) -> Optional[Dict]:
159-
"""
160-
Make an HTTP request with caching. Returns the JSON response if successful.
161-
162-
Args:
163-
url: The URL to request
164-
headers: Optional headers for the request
165-
166-
Returns:
167-
JSON response data if successful, None if failed
168-
"""
169-
# Check cache first
170-
cached_response = cache_manager.get(url)
171-
if cached_response:
172-
logging.info(f"[make_cached_request] Using cached response for: {url}")
173-
return cached_response
174-
175-
# Make actual HTTP request
176-
logging.info(f"[make_cached_request] Making HTTP request to: {url}")
177-
try:
178-
response = requests.get(url, headers=headers or HEADERS)
179-
response.raise_for_status()
180-
data = response.json()
181-
182-
# Cache successful response
183-
cache_manager.set(url, data)
184-
logging.info(f"[make_cached_request] Successfully cached response for: {url}")
185-
return data
186-
187-
except requests.exceptions.RequestException as e:
188-
logging.error(f"[make_cached_request] HTTP request failed for {url}: {e}")
189-
return None
190-
except json.JSONDecodeError as e:
191-
logging.error(
192-
f"[make_cached_request] Failed to parse JSON response for {url}: {e}"
193-
)
194-
return None
195-
196145

197146
def get_repos(org: str) -> List[str]:
198147
logging.info(f"[get_repos] Start fetching repositories for org: {org}")
@@ -445,32 +394,6 @@ def save_to_yaml(data: Dict, filename: str = "runner_labels_summary.yml"):
445394
logging.info(f"[save_to_yaml] Data successfully saved to {filename}")
446395

447396

448-
def clear_cache():
449-
"""Clear all cached data."""
450-
import shutil
451-
452-
if CACHE_DIR.exists():
453-
shutil.rmtree(CACHE_DIR)
454-
CACHE_DIR.mkdir(exist_ok=True)
455-
logging.info(f"[clear_cache] Cleared cache directory: {CACHE_DIR}")
456-
else:
457-
logging.info(f"[clear_cache] Cache directory does not exist: {CACHE_DIR}")
458-
459-
460-
def get_cache_stats():
461-
"""Get statistics about the cache."""
462-
if not CACHE_DIR.exists():
463-
return {"total_files": 0, "total_size_mb": 0}
464-
465-
cache_files = list(CACHE_DIR.glob("*.json"))
466-
total_size = sum(f.stat().st_size for f in cache_files)
467-
468-
return {
469-
"total_files": len(cache_files),
470-
"total_size_mb": round(total_size / (1024 * 1024), 2),
471-
}
472-
473-
474397
def download_scale_config(url: str, dest: str = "scale-config.yml") -> bool:
475398
"""Download scale-config.yml from the given URL if it does not exist locally."""
476399
if os.path.exists(dest):

tools/analytics/org/cache_manager.py

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
from pathlib import Path
55
from typing import Dict, Optional
66

7+
import requests
8+
79

810
# Cache configuration
911
CACHE_DIR = Path("cache")
@@ -95,4 +97,81 @@ def set(self, url: str, data: Dict) -> None:
9597
json.dump(data, f, indent=2)
9698
logging.debug(f"[CacheManager] Cached response for URL: {url}")
9799
except IOError as e:
98-
logging.error(f"[CacheManager] Failed to write cache for {url}: {e}")
100+
logging.error(f"[CacheManager] Failed to write cache for {url}: {e}")
101+
102+
103+
# Global cache manager instance
104+
cache_manager = CacheManager()
105+
106+
107+
def get_cache_stats():
108+
"""Get statistics about the cache."""
109+
if not CACHE_DIR.exists():
110+
return {"total_files": 0, "total_size_mb": 0}
111+
112+
cache_files = list(CACHE_DIR.glob("*.json"))
113+
total_size = sum(f.stat().st_size for f in cache_files)
114+
115+
return {
116+
"total_files": len(cache_files),
117+
"total_size_mb": round(total_size / (1024 * 1024), 2),
118+
}
119+
120+
121+
def clear_cache():
122+
"""Clear all cached data."""
123+
import shutil
124+
125+
if CACHE_DIR.exists():
126+
shutil.rmtree(CACHE_DIR)
127+
CACHE_DIR.mkdir(exist_ok=True)
128+
logging.info(f"[clear_cache] Cleared cache directory: {CACHE_DIR}")
129+
else:
130+
logging.info(f"[clear_cache] Cache directory does not exist: {CACHE_DIR}")
131+
132+
133+
HEADERS = {
134+
"Authorization": f"Bearer {GITHUB_TOKEN}",
135+
"Accept": "application/vnd.github+json",
136+
}
137+
138+
139+
def make_cached_request(
140+
url: str, headers: Optional[Dict[str, str]] = None
141+
) -> Optional[Dict]:
142+
"""
143+
Make an HTTP request with caching. Returns the JSON response if successful.
144+
145+
Args:
146+
url: The URL to request
147+
headers: Optional headers for the request
148+
149+
Returns:
150+
JSON response data if successful, None if failed
151+
"""
152+
# Check cache first
153+
cached_response = cache_manager.get(url)
154+
if cached_response:
155+
logging.info(f"[make_cached_request] Using cached response for: {url}")
156+
return cached_response
157+
158+
# Make actual HTTP request
159+
logging.info(f"[make_cached_request] Making HTTP request to: {url}")
160+
try:
161+
response = requests.get(url, headers=headers or HEADERS)
162+
response.raise_for_status()
163+
data = response.json()
164+
165+
# Cache successful response
166+
cache_manager.set(url, data)
167+
logging.info(f"[make_cached_request] Successfully cached response for: {url}")
168+
return data
169+
170+
except requests.exceptions.RequestException as e:
171+
logging.error(f"[make_cached_request] HTTP request failed for {url}: {e}")
172+
return None
173+
except json.JSONDecodeError as e:
174+
logging.error(
175+
f"[make_cached_request] Failed to parse JSON response for {url}: {e}"
176+
)
177+
return None

0 commit comments

Comments
 (0)