aic-utils 2.0.7__tar.gz → 2.0.9__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {aic_utils-2.0.7 → aic_utils-2.0.9}/PKG-INFO +1 -1
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils/__init__.py +1 -1
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils/aic.py +53 -10
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils/gitlabmanager.py +44 -23
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils.egg-info/PKG-INFO +1 -1
- {aic_utils-2.0.7 → aic_utils-2.0.9}/setup.py +1 -1
- {aic_utils-2.0.7 → aic_utils-2.0.9}/README.md +0 -0
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils/dataset_converter.py +0 -0
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils/gitlab_init.py +0 -0
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils/slack_logger.py +0 -0
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils.egg-info/SOURCES.txt +0 -0
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils.egg-info/dependency_links.txt +0 -0
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils.egg-info/requires.txt +0 -0
- {aic_utils-2.0.7 → aic_utils-2.0.9}/aic_utils.egg-info/top_level.txt +0 -0
- {aic_utils-2.0.7 → aic_utils-2.0.9}/setup.cfg +0 -0
|
@@ -1,13 +1,48 @@
|
|
|
1
1
|
import requests
|
|
2
|
-
import json
|
|
2
|
+
import json
|
|
3
|
+
import time
|
|
3
4
|
from datetime import datetime
|
|
4
5
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
5
6
|
from datetime import datetime
|
|
6
7
|
import re
|
|
7
8
|
|
|
9
|
+
|
|
10
|
+
def _resilient_get(url, headers, *, timeout=30, max_attempts=4, backoff=1.5):
|
|
11
|
+
"""
|
|
12
|
+
GET wrapper that survives the two failure modes the AIC API hits under
|
|
13
|
+
parallel load: (1) empty response bodies (server returns 200 + ""),
|
|
14
|
+
(2) transient 5xx / connection drops. Retries up to `max_attempts` with
|
|
15
|
+
exponential backoff. Raises the last error on full failure.
|
|
16
|
+
"""
|
|
17
|
+
last_err = None
|
|
18
|
+
for attempt in range(1, max_attempts + 1):
|
|
19
|
+
try:
|
|
20
|
+
resp = requests.get(url, headers=headers, timeout=timeout)
|
|
21
|
+
except requests.exceptions.RequestException as e:
|
|
22
|
+
last_err = e
|
|
23
|
+
if attempt < max_attempts:
|
|
24
|
+
time.sleep(backoff ** attempt)
|
|
25
|
+
continue
|
|
26
|
+
raise
|
|
27
|
+
# Retry on transient server errors
|
|
28
|
+
if resp.status_code >= 500 and attempt < max_attempts:
|
|
29
|
+
time.sleep(backoff ** attempt)
|
|
30
|
+
last_err = RuntimeError(f"HTTP {resp.status_code} from {url}")
|
|
31
|
+
continue
|
|
32
|
+
# Retry if 200 but empty body (json() would explode)
|
|
33
|
+
if resp.status_code == 200 and not (resp.text or '').strip():
|
|
34
|
+
if attempt < max_attempts:
|
|
35
|
+
time.sleep(backoff ** attempt)
|
|
36
|
+
last_err = RuntimeError(f"Empty body from {url}")
|
|
37
|
+
continue
|
|
38
|
+
return resp
|
|
39
|
+
if last_err:
|
|
40
|
+
raise last_err
|
|
41
|
+
|
|
42
|
+
|
|
8
43
|
class AIC():
|
|
9
44
|
timestamp = datetime.today().strftime('%Y%m%d')
|
|
10
|
-
|
|
45
|
+
|
|
11
46
|
def __init__(self, api_key, project, workspace, pipelines=[], qa=False):
|
|
12
47
|
self.base_url = 'https://prod.jdpower.ai/apis/core/v1' if not qa else 'https://aic.qa.jdpower.com/apis/core/v1'
|
|
13
48
|
self.api_key = api_key
|
|
@@ -72,16 +107,16 @@ class AIC():
|
|
|
72
107
|
|
|
73
108
|
def get_project_id(self, project):
|
|
74
109
|
url = f"{self.base_url}/projects"
|
|
75
|
-
response =
|
|
110
|
+
response = _resilient_get(url, headers=self.headers)
|
|
76
111
|
for obj in response.json():
|
|
77
112
|
if obj['name'] == project:
|
|
78
113
|
return obj['$id']
|
|
79
114
|
raise Exception(f'No project with name {project} found')
|
|
80
|
-
|
|
115
|
+
|
|
81
116
|
|
|
82
117
|
def get_workspace_id(self, workspace):
|
|
83
118
|
url = f"{self.base_url}/projects/{self.project_id}/workspaces"
|
|
84
|
-
response =
|
|
119
|
+
response = _resilient_get(url, headers=self.headers)
|
|
85
120
|
for obj in response.json():
|
|
86
121
|
if obj['name'] == workspace:
|
|
87
122
|
return obj['$id']
|
|
@@ -94,7 +129,7 @@ class AIC():
|
|
|
94
129
|
"""
|
|
95
130
|
pipelines = []
|
|
96
131
|
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/jobs"
|
|
97
|
-
response =
|
|
132
|
+
response = _resilient_get(url, headers=self.headers)
|
|
98
133
|
response.raise_for_status() # Check for HTTP errors
|
|
99
134
|
|
|
100
135
|
# Extract pipeline names and IDs
|
|
@@ -125,14 +160,22 @@ class AIC():
|
|
|
125
160
|
|
|
126
161
|
name = pipeline['name']
|
|
127
162
|
url = f"{self.base_url}/projects/{self.project_id}/workspaces/{self.workspace_id}/jobs/{id}"
|
|
128
|
-
print(f'Retrieving config for {name}...')
|
|
163
|
+
print(f'Retrieving config for {name}...', flush=True)
|
|
129
164
|
|
|
130
|
-
|
|
165
|
+
try:
|
|
166
|
+
response = _resilient_get(url, headers=self.headers)
|
|
167
|
+
except Exception as e:
|
|
168
|
+
print(f'Failed to fetch {name} after retries: {e}', flush=True)
|
|
169
|
+
return None
|
|
131
170
|
if response.status_code == 200:
|
|
132
|
-
|
|
171
|
+
try:
|
|
172
|
+
data = response.json()
|
|
173
|
+
except Exception as e:
|
|
174
|
+
print(f'Failed to parse JSON for {name}: {e}', flush=True)
|
|
175
|
+
return None
|
|
133
176
|
return {'name': name, 'jobConfig': data['jobConfig'], 'id': data['jobConfig']['$id']}
|
|
134
177
|
else:
|
|
135
|
-
print(f'Failed to fetch {name}: {response.status_code}')
|
|
178
|
+
print(f'Failed to fetch {name}: {response.status_code}', flush=True)
|
|
136
179
|
return None
|
|
137
180
|
|
|
138
181
|
|
|
@@ -650,7 +650,10 @@ class GitLabManager:
|
|
|
650
650
|
per_pipeline_status[name] = 'Success'
|
|
651
651
|
per_pipeline_changed_files[name] += 1
|
|
652
652
|
|
|
653
|
-
# Compute prune deletions if requested
|
|
653
|
+
# Compute prune deletions if requested.
|
|
654
|
+
# Handles pipeline names containing slashes (e.g. "ford rdd - v2 QA/Test")
|
|
655
|
+
# which become nested directories in code/ — a naïve split on '/' misidentifies
|
|
656
|
+
# those as orphans and triggers a delete/re-push oscillation across runs.
|
|
654
657
|
prune_deletes = []
|
|
655
658
|
if prune:
|
|
656
659
|
allowed = {cfg['name'] for cfg in self.aic.pipeline_configs}
|
|
@@ -661,8 +664,11 @@ class GitLabManager:
|
|
|
661
664
|
if pname not in allowed:
|
|
662
665
|
prune_deletes.append(path)
|
|
663
666
|
elif path.startswith('code/'):
|
|
664
|
-
|
|
665
|
-
|
|
667
|
+
rel = path[len('code/'):]
|
|
668
|
+
# A code path belongs to pipeline P iff rel == P (file at that exact name)
|
|
669
|
+
# or rel starts with P + '/' (file inside the pipeline's subtree).
|
|
670
|
+
# Iterating allowed correctly handles slash-containing pipeline names.
|
|
671
|
+
if not any(rel == name or rel.startswith(name + '/') for name in allowed):
|
|
666
672
|
prune_deletes.append(path)
|
|
667
673
|
|
|
668
674
|
n_changed = len(actions)
|
|
@@ -956,9 +962,14 @@ class GitLabManager:
|
|
|
956
962
|
of `batch_size` and POSTs each as a single commit. Each action is a dict
|
|
957
963
|
like {"action": "create"|"update"|"delete", "file_path": "...", "content": "..."}.
|
|
958
964
|
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
965
|
+
Failure handling: if a batch returns 400 (typically because GitLab's
|
|
966
|
+
`repository/tree?recursive=true` has an undocumented entry cap and
|
|
967
|
+
silently returned partial results, leading us to mislabel some files
|
|
968
|
+
as `create` when they exist), fall back to per-file commits via the
|
|
969
|
+
legacy `_push_file()` / `delete_file()` helpers. Those auto-handle
|
|
970
|
+
create-vs-update at the per-file level and don't depend on the tree
|
|
971
|
+
listing being complete. Slower (one commit per file in the failed
|
|
972
|
+
batch) but reliable; only triggers on the misbehaving batch.
|
|
962
973
|
"""
|
|
963
974
|
if not actions:
|
|
964
975
|
return
|
|
@@ -980,25 +991,35 @@ class GitLabManager:
|
|
|
980
991
|
print(f"Committed batch {batch_idx + 1}/{num_batches} ({len(chunk)} files) on '{branch}'")
|
|
981
992
|
continue
|
|
982
993
|
|
|
983
|
-
# Retry create<->update flip on 400 errors
|
|
984
994
|
if resp.status_code == 400:
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
flipped.append({**a, "action": "update"})
|
|
991
|
-
else:
|
|
992
|
-
flipped.append(a)
|
|
993
|
-
payload["actions"] = flipped
|
|
994
|
-
resp2 = requests.post(url, headers=self.headers, json=payload, timeout=60)
|
|
995
|
-
if resp2.status_code in (200, 201):
|
|
996
|
-
print(f"Committed batch {batch_idx + 1}/{num_batches} ({len(chunk)} files) on '{branch}' [flipped]")
|
|
997
|
-
continue
|
|
998
|
-
raise RuntimeError(
|
|
999
|
-
f"Failed batch {batch_idx + 1}/{num_batches} on '{branch}' even after create/update flip "
|
|
1000
|
-
f"(status {resp2.status_code}): {resp2.text}"
|
|
995
|
+
# Tree listing was probably incomplete (or content drifted). Fall back
|
|
996
|
+
# to per-file create-or-update which doesn't depend on tree state.
|
|
997
|
+
print(
|
|
998
|
+
f"Batch {batch_idx + 1}/{num_batches} returned 400 "
|
|
999
|
+
f"({(resp.text or '')[:120]}); falling back to per-file commits."
|
|
1001
1000
|
)
|
|
1001
|
+
for action in chunk:
|
|
1002
|
+
fpath = action.get('file_path')
|
|
1003
|
+
act = action.get('action')
|
|
1004
|
+
try:
|
|
1005
|
+
if act == 'delete':
|
|
1006
|
+
self.delete_file(fpath, branch=branch)
|
|
1007
|
+
else:
|
|
1008
|
+
# _push_file POSTs (create) and falls back to PUT (update)
|
|
1009
|
+
# on 400/409 — handles both cases regardless of current
|
|
1010
|
+
# state in the repo.
|
|
1011
|
+
self._push_file(proj, fpath, action.get('content', ''), branch=branch)
|
|
1012
|
+
except Exception as fe:
|
|
1013
|
+
raise RuntimeError(
|
|
1014
|
+
f"Per-file fallback failed on '{fpath}' "
|
|
1015
|
+
f"(action={act}, batch {batch_idx + 1}/{num_batches}): {fe}"
|
|
1016
|
+
)
|
|
1017
|
+
print(
|
|
1018
|
+
f" ✓ batch {batch_idx + 1}/{num_batches} recovered via per-file fallback "
|
|
1019
|
+
f"({len(chunk)} files)"
|
|
1020
|
+
)
|
|
1021
|
+
continue
|
|
1022
|
+
|
|
1002
1023
|
raise RuntimeError(
|
|
1003
1024
|
f"Failed batch {batch_idx + 1}/{num_batches} on '{branch}' "
|
|
1004
1025
|
f"(status {resp.status_code}): {resp.text}"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|