aic-utils 2.0.0__tar.gz → 2.0.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aic_utils
3
- Version: 2.0.0
3
+ Version: 2.0.2
4
4
  Summary: AIC API wrapper and GitLab integration framework for pipeline management
5
5
  Home-page: https://github.com/dylandoyle11/aic_utils
6
6
  Author: Dylan D
@@ -8,7 +8,7 @@ from .gitlab_init import GitLabRepositoryInitializer
8
8
  from .dataset_converter import DatasetConverter
9
9
  from .slack_logger import SlackLogger
10
10
 
11
- __version__ = '2.0.0'
11
+ __version__ = '2.0.1'
12
12
  __author__ = 'Dylan D'
13
13
 
14
14
  __all__ = [
@@ -1066,7 +1066,7 @@ class GitLabManager:
1066
1066
  )
1067
1067
 
1068
1068
  # Run the initialization
1069
- from gitlab_init import GitLabRepositoryInitializer
1069
+ from aic_utils.gitlab_init import GitLabRepositoryInitializer
1070
1070
  initializer = GitLabRepositoryInitializer(temp_mgr)
1071
1071
  result = initializer.initialize_repository()
1072
1072
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aic_utils
3
- Version: 2.0.0
3
+ Version: 2.0.2
4
4
  Summary: AIC API wrapper and GitLab integration framework for pipeline management
5
5
  Home-page: https://github.com/dylandoyle11/aic_utils
6
6
  Author: Dylan D
@@ -4,7 +4,6 @@ aic_utils/__init__.py
4
4
  aic_utils/aic.py
5
5
  aic_utils/dataset_converter.py
6
6
  aic_utils/gitlab_init.py
7
- aic_utils/gitlab_manager.py
8
7
  aic_utils/gitlabmanager.py
9
8
  aic_utils/slack_logger.py
10
9
  aic_utils.egg-info/PKG-INFO
@@ -7,7 +7,7 @@ with open('README.md', 'r', encoding='utf-8') as fh:
7
7
 
8
8
  setup(
9
9
  name='aic_utils',
10
- version='2.0.0',
10
+ version='2.0.2',
11
11
  packages=find_packages(),
12
12
  install_requires=[
13
13
  'requests>=2.25.0',
@@ -1,263 +0,0 @@
1
- #!/usr/bin/env python3
2
- import hashlib
3
- import base64
4
- import requests
5
- import json
6
- from datetime import datetime
7
-
8
- class GitLabManager:
9
- """
10
- Manage a single GitLab project where each branch represents an environment
11
- and each pipeline config is stored as a separate JSON file.
12
- Includes GitLab token checks, file hash comparisons, subgroup handling,
13
- per-pipeline repo support, and deploy-from-git functionality.
14
- """
15
- def __init__(
16
- self,
17
- aic_instance,
18
- gitlab_token,
19
- gitlab_namespace,
20
- project_name="jobs",
21
- environment="production",
22
- gitlab_base_url="https://git.autodatacorp.org/api/v4",
23
- use_hash_comparison=True
24
- ):
25
- # AIC client to fetch pipeline_configs
26
- self.aic = aic_instance
27
- # GitLab API settings
28
- self.gitlab_base = gitlab_base_url.rstrip('/')
29
- self.gitlab_token = gitlab_token
30
- self.use_hash_comparison = use_hash_comparison
31
- self.headers = {
32
- 'Private-Token': self.gitlab_token,
33
- 'Content-Type': 'application/json'
34
- }
35
- # Namespace and project path
36
- self.gitlab_namespace = gitlab_namespace.rstrip('/')
37
- self.project_name = project_name
38
- # Environment branch name
39
- self.branch = environment.lower()
40
- # e.g. 'pin/pin-analytics/pin-fusion-2.0/jobs'
41
- self.project_path = f"{self.gitlab_namespace}/{self.project_name}"
42
- # Determine subgroup for legacy flows
43
- self.workspace_name = self.aic.workspace
44
- self.subgroup_id = self._ensure_correct_subgroup(self.workspace_name)
45
-
46
- # --- Token expiration checks ---
47
- def get_token_expiration_date(self):
48
- """Retrieves the expiration date of the GitLab token."""
49
- url = f"{self.gitlab_base}/personal_access_tokens"
50
- try:
51
- response = requests.get(
52
- url,
53
- headers=self.headers,
54
- params={'name': 'fusion-push', 'revoked': 'false'}
55
- )
56
- response.raise_for_status()
57
- tokens = response.json()
58
- for t in tokens:
59
- if t.get('name') == 'fusion-push' and not t.get('revoked', True):
60
- exp = t.get('expires_at')
61
- fmt = '%Y-%m-%dT%H:%M:%S.%fZ' if 'T' in exp else '%Y-%m-%d'
62
- return datetime.strptime(exp, fmt)
63
- except requests.exceptions.HTTPError as err:
64
- print(f"Error checking token expiration: {err}")
65
- return None
66
-
67
- def check_token_expiration(self):
68
- """Checks and prints days until the token expires."""
69
- exp = self.get_token_expiration_date()
70
- if exp:
71
- days_left = (exp - datetime.now()).days
72
- print(f"GitLab Token expires in {days_left} days.")
73
- if days_left < 7:
74
- print("Token is expiring soon. Consider updating it.")
75
- else:
76
- print("Could not retrieve token expiration date.")
77
-
78
- # --- Utility: hashing ---
79
- def generate_hash(self, content):
80
- """MD5 hash of normalized content."""
81
- norm = content.strip().replace('\r\n', '\n').replace('\r', '\n')
82
- return hashlib.md5(norm.encode('utf-8')).hexdigest()
83
-
84
- # --- Legacy subgroup/repo handling ---
85
- def _ensure_correct_subgroup(self, workspace):
86
- ns = self.gitlab_namespace
87
- if ns.endswith('/pipelines'):
88
- if workspace.lower().endswith('qa'):
89
- return f"{ns}/qa"
90
- return f"{ns}/production"
91
- return ns
92
-
93
- def get_subgroup_id(self):
94
- url = f"{self.gitlab_base}/groups/{self.subgroup_id.replace('/', '%2F')}"
95
- resp = requests.get(url, headers=self.headers)
96
- resp.raise_for_status()
97
- return resp.json()['id']
98
-
99
- def get_namespace_id(self):
100
- url = f"{self.gitlab_base}/namespaces?search={self.gitlab_namespace}"
101
- r = requests.get(url, headers=self.headers)
102
- if r.status_code == 200:
103
- for ns in r.json():
104
- if ns.get('full_path') == self.gitlab_namespace:
105
- return ns['id']
106
- return None
107
-
108
- # --- Per-pipeline repo support (legacy) ---
109
- def repository_exists(self, repo_path):
110
- url = f"{self.gitlab_base}/projects/{repo_path.replace('/', '%2F')}"
111
- r = requests.get(url, headers=self.headers)
112
- return r.status_code == 200
113
-
114
- def create_repository(self, repo_name):
115
- url = f"{self.gitlab_base}/projects"
116
- data = {
117
- 'name': repo_name,
118
- 'namespace_id': self.get_subgroup_id(),
119
- 'visibility': 'private'
120
- }
121
- r = requests.post(url, headers=self.headers, json=data)
122
- if r.status_code == 201:
123
- return r.json()
124
- print(f"Failed to create repo {repo_name}: {r.status_code} {r.text}")
125
- return None
126
-
127
- def get_existing_file_content(self, repo_name, file_name):
128
- url = (f"{self.gitlab_base}/projects/"
129
- f"{repo_name.replace('/', '%2F')}/repository/files/{file_name}?ref=main")
130
- r = requests.get(url, headers=self.headers)
131
- if r.status_code == 200:
132
- enc = r.json().get('content')
133
- return base64.b64decode(enc).decode('utf-8') if enc else None
134
- return None
135
-
136
- def push_file_to_repo(self, repo_name, file_name, file_content):
137
- repo_path = f"{self.subgroup_id}/{repo_name.replace(' ', '_')}"
138
- if not self.repository_exists(repo_path):
139
- if not self.create_repository(repo_name):
140
- return
141
- self.push_new_file(repo_path, file_name, file_content)
142
- return
143
- if self.use_hash_comparison:
144
- old = self.get_existing_file_content(repo_path, file_name)
145
- if old and self.generate_hash(old) == self.generate_hash(file_content):
146
- print(f"No change for {file_name}")
147
- return
148
- self.push_new_file(repo_path, file_name, file_content)
149
-
150
- def push_new_file(self, repo_path, file_name, file_content):
151
- url = (f"{self.gitlab_base}/projects/"
152
- f"{repo_path.replace('/', '%2F')}/repository/files/{file_name}")
153
- data = {
154
- 'branch': 'main',
155
- 'content': file_content,
156
- 'commit_message': f"Update {file_name} – {datetime.now():%Y-%m-%d}"
157
- }
158
- resp = requests.post(url, headers=self.headers, json=data)
159
- if resp.status_code == 201:
160
- print(f"Created {file_name} in {repo_path}")
161
- elif resp.status_code in (400, 409):
162
- r2 = requests.put(url, headers=self.headers, json=data)
163
- print(f"Updated {file_name}" if r2.status_code == 200 else r2.text)
164
-
165
- # --- Unified single-project flow ---
166
- def ensure_branch_exists(self, branch_name=None, ref="main"):
167
- branch = branch_name or self.branch
168
- proj = self.project_path.replace('/', '%2F')
169
- r = requests.get(
170
- f"{self.gitlab_base}/projects/{proj}/repository/branches/{branch}",
171
- headers=self.headers
172
- )
173
- if r.status_code == 404:
174
- c = requests.post(
175
- f"{self.gitlab_base}/projects/{proj}/repository/branches"
176
- f"?branch={branch}&ref={ref}",
177
- headers=self.headers
178
- )
179
- if c.status_code != 201:
180
- raise RuntimeError(f"Could not create branch: {c.text}")
181
- print(f"Created branch '{branch}'")
182
-
183
- def push_pipelines(self):
184
- """Serialize each AIC pipeline as JSON into the env branch."""
185
- self.ensure_branch_exists()
186
- proj = self.project_path.replace('/', '%2F')
187
- for cfg in self.aic.pipeline_configs:
188
- fn = f"{cfg['name']}.json"
189
- content = json.dumps(cfg['jobConfig'], indent=2)
190
- self._push_file(proj, fn, content, branch=self.branch)
191
-
192
- def _push_file(self, proj_encoded, file_name, file_content, branch):
193
- url = (
194
- f"{self.gitlab_base}/projects/{proj_encoded}"
195
- f"/repository/files/{file_name}"
196
- )
197
- payload = {
198
- 'branch': branch,
199
- 'content': file_content,
200
- 'commit_message': f"Sync {file_name} – {datetime.now():%Y-%m-%d}"
201
- }
202
- r = requests.post(url, headers=self.headers, json=payload)
203
- if r.status_code == 201:
204
- print(f"Created {file_name} on branch '{branch}'")
205
- return
206
- if r.status_code in (400, 409):
207
- r2 = requests.put(url, headers=self.headers, json=payload)
208
- if r2.status_code == 200:
209
- print(f"Updated {file_name} on branch '{branch}'")
210
- return
211
- raise RuntimeError(f"Write failed: {r.status_code} {r.text}")
212
-
213
- def delete_file(self, file_name, branch=None):
214
- """Remove a file from the environment branch."""
215
- branch = branch or self.branch
216
- proj = self.project_path.replace('/', '%2F')
217
- r = requests.delete(
218
- f"{self.gitlab_base}/projects/{proj}/repository/files/{file_name}",
219
- headers=self.headers,
220
- params={
221
- 'branch': branch,
222
- 'commit_message': f"Remove {file_name} – {datetime.now():%Y-%m-%d}"
223
- }
224
- )
225
- if r.status_code == 204:
226
- print(f"Deleted {file_name}")
227
- else:
228
- raise RuntimeError(f"Delete failed: {r.status_code} {r.text}")
229
-
230
- # --- Deploy from GitLab to AIC ---
231
- def list_pipeline_files(self):
232
- """List all .json files in the current env branch."""
233
- proj = self.project_path.replace('/', '%2F')
234
- url = f"{self.gitlab_base}/projects/{proj}/repository/tree"
235
- resp = requests.get(
236
- url, headers={'PRIVATE-TOKEN': self.gitlab_token},
237
- params={'ref': self.branch}
238
- )
239
- resp.raise_for_status()
240
- return [item['name'] for item in resp.json()
241
- if item['type']=='blob' and item['name'].endswith('.json')]
242
-
243
- def fetch_pipeline_file(self, filename):
244
- """Fetch raw JSON content for a single pipeline file."""
245
- proj = self.project_path.replace('/', '%2F')
246
- url = (f"{self.gitlab_base}/projects/{proj}"
247
- f"/repository/files/{filename.replace('/', '%2F')}/raw")
248
- resp = requests.get(
249
- url, headers={'PRIVATE-TOKEN': self.gitlab_token},
250
- params={'ref': self.branch}
251
- )
252
- resp.raise_for_status()
253
- return resp.text
254
-
255
- def deploy_pipelines(self):
256
- """Read each JSON in git and create/update pipelines in AIC."""
257
- for fname in self.list_pipeline_files():
258
- print(f"Deploying {fname} to AIC...")
259
- raw = self.fetch_pipeline_file(fname)
260
- cfg = json.loads(raw)
261
- name = fname.rsplit('.json',1)[0]
262
- pipeline_conf = {'name': name, 'jobConfig': cfg, 'id': cfg.get('$id')}
263
- self.aic.create_or_update_pipeline(self.aic.workspace_id, pipeline_conf)
File without changes
File without changes
File without changes