aic-utils 2.0.2__tar.gz → 2.0.4__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.4/PKG-INFO +680 -0
- aic_utils-2.0.4/README.md +645 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils/__init__.py +1 -1
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils/gitlab_init.py +9 -54
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils/gitlabmanager.py +203 -85
- aic_utils-2.0.4/aic_utils.egg-info/PKG-INFO +680 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/setup.py +1 -1
- aic_utils-2.0.2/PKG-INFO +0 -593
- aic_utils-2.0.2/README.md +0 -568
- aic_utils-2.0.2/aic_utils.egg-info/PKG-INFO +0 -593
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils/aic.py +0 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils/dataset_converter.py +0 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils/slack_logger.py +0 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils.egg-info/SOURCES.txt +0 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils.egg-info/dependency_links.txt +0 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils.egg-info/requires.txt +0 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/aic_utils.egg-info/top_level.txt +0 -0
- {aic_utils-2.0.2 → aic_utils-2.0.4}/setup.cfg +0 -0
aic_utils-2.0.4/PKG-INFO
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: aic_utils
|
|
3
|
+
Version: 2.0.4
|
|
4
|
+
Summary: AIC API wrapper and GitLab integration framework for pipeline management
|
|
5
|
+
Home-page: https://github.com/dylandoyle11/aic_utils
|
|
6
|
+
Author: Dylan D
|
|
7
|
+
Author-email: dylan.doyle@jdpa.com
|
|
8
|
+
Keywords: aic gitlab pipeline automation devops
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Requires-Dist: requests>=2.25.0
|
|
22
|
+
Requires-Dist: PyYAML>=5.4.0
|
|
23
|
+
Requires-Dist: pandas>=1.3.0
|
|
24
|
+
Requires-Dist: slack_sdk>=3.0.0
|
|
25
|
+
Dynamic: author
|
|
26
|
+
Dynamic: author-email
|
|
27
|
+
Dynamic: classifier
|
|
28
|
+
Dynamic: description
|
|
29
|
+
Dynamic: description-content-type
|
|
30
|
+
Dynamic: home-page
|
|
31
|
+
Dynamic: keywords
|
|
32
|
+
Dynamic: requires-dist
|
|
33
|
+
Dynamic: requires-python
|
|
34
|
+
Dynamic: summary
|
|
35
|
+
|
|
36
|
+
# aic_utils
|
|
37
|
+
|
|
38
|
+
`aic_utils` is a Python toolkit for managing JD Power **AIC** (Analytics Insights Console) pipelines and synchronizing them with **GitLab** under a strict, audit-friendly Git flow. It also bundles a few supporting utilities (dataset placeholder conversion, Slack logging, repository bootstrapping).
|
|
39
|
+
|
|
40
|
+
- **PyPI:** https://pypi.org/project/aic-utils/
|
|
41
|
+
- **Source:** https://github.com/dylandoyle11/aic_utils
|
|
42
|
+
- **Current version (source tree):** `2.0.2`
|
|
43
|
+
- **Author:** Dylan Doyle
|
|
44
|
+
|
|
45
|
+
> ⚠️ The PyPI release may lag this repository. This README documents the **current source tree**. If a method described here is not present in the version you `pip install`-ed, install from source (`pip install git+https://github.com/dylandoyle11/aic_utils`) or pin to the version that matches.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Table of Contents
|
|
50
|
+
|
|
51
|
+
1. [Installation](#1-installation)
|
|
52
|
+
2. [Package Overview](#2-package-overview)
|
|
53
|
+
3. [`AIC` — AIC REST API wrapper](#3-aic--aic-rest-api-wrapper)
|
|
54
|
+
4. [`GitLabManager` — Git ↔ AIC sync engine](#4-gitlabmanager--git--aic-sync-engine)
|
|
55
|
+
5. [`BranchWorkspaceMapper` — branch ↔ workspace mapping](#5-branchworkspacemapper--branch--workspace-mapping)
|
|
56
|
+
6. [`GitLabRepositoryInitializer` — bootstrap a new repo](#6-gitlabrepositoryinitializer--bootstrap-a-new-repo)
|
|
57
|
+
7. [`DatasetConverter` — placeholder rewriting](#7-datasetconverter--placeholder-rewriting)
|
|
58
|
+
8. [`SlackLogger` — Slack-backed Python logger](#8-slacklogger--slack-backed-python-logger)
|
|
59
|
+
9. [Day-to-day workflows](#9-day-to-day-workflows)
|
|
60
|
+
10. [Best practices & troubleshooting](#10-best-practices--troubleshooting)
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 1. Installation
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pip install aic_utils
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Or pin to the latest source:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pip install git+https://github.com/dylandoyle11/aic_utils.git
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
**Runtime dependencies** (from `setup.py`):
|
|
77
|
+
|
|
78
|
+
- `requests >= 2.25.0`
|
|
79
|
+
- `PyYAML >= 5.4.0`
|
|
80
|
+
- `pandas >= 1.3.0`
|
|
81
|
+
- `slack_sdk >= 3.0.0`
|
|
82
|
+
|
|
83
|
+
**Python:** 3.8+
|
|
84
|
+
|
|
85
|
+
> The `GitLabManager._send_email` helper imports `pyspark_utils` lazily; that package is optional and only required when `email_recipients` is configured.
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 2. Package Overview
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from aic_utils import (
|
|
93
|
+
AIC, # AIC REST wrapper
|
|
94
|
+
GitLabManager, # GitLab sync / Git-flow enforcement
|
|
95
|
+
GitLabRepositoryInitializer, # One-time repo bootstrap
|
|
96
|
+
DatasetConverter, # Rewrite SQL/JSON placeholders → dataset:table refs
|
|
97
|
+
SlackLogger, # Pipe Python logging / print() to Slack
|
|
98
|
+
)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The package is organized so that one `AIC` instance + one `GitLabManager` instance together represent **one workspace ↔ one branch** at a time. Each environment (Prod / QA / Dev / sandbox) uses its own pair.
|
|
102
|
+
|
|
103
|
+
### High-level architecture
|
|
104
|
+
|
|
105
|
+
```
|
|
106
|
+
┌──────────────┐ ┌────────────────────┐ ┌──────────────┐
|
|
107
|
+
│ AIC workspace│ ←──── │ AIC (REST wrapper)│ ────→ │ pipeline JSON│
|
|
108
|
+
│ (cloud) │ └─────────┬──────────┘ │ in memory │
|
|
109
|
+
└──────────────┘ │ └──────┬───────┘
|
|
110
|
+
▼ ▼
|
|
111
|
+
┌────────────────────┐ ┌──────────────────┐
|
|
112
|
+
│ GitLabManager │ ────→ │ GitLab repo │
|
|
113
|
+
│ (push / deploy / │ │ config/*.json │
|
|
114
|
+
│ branch / MR) │ │ code/<pipe>/* │
|
|
115
|
+
└─────────┬──────────┘ └──────────────────┘
|
|
116
|
+
│
|
|
117
|
+
▼
|
|
118
|
+
┌────────────────────┐
|
|
119
|
+
│ BranchWorkspace- │ ← branch_to_workspace.yaml
|
|
120
|
+
│ Mapper │
|
|
121
|
+
└────────────────────┘
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## 3. `AIC` — AIC REST API wrapper
|
|
127
|
+
|
|
128
|
+
`aic_utils/aic.py` — class `AIC`
|
|
129
|
+
|
|
130
|
+
A thin REST client around the AIC core API (`/apis/core/v1`). Resolves project + workspace, lists pipelines, fetches/upserts pipeline configs, manages datasets and backups.
|
|
131
|
+
|
|
132
|
+
### 3.1 Constructor
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
AIC(api_key: str,
|
|
136
|
+
project: str,
|
|
137
|
+
workspace: str,
|
|
138
|
+
pipelines: list[str] = [],
|
|
139
|
+
qa: bool = False)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
| Arg | Description |
|
|
143
|
+
|-----|-------------|
|
|
144
|
+
| `api_key` | AIC API key (`User Profile → Manage API Keys` in AIC UI). |
|
|
145
|
+
| `project` | Exact project name (matched against `name` from `GET /projects`). |
|
|
146
|
+
| `workspace` | Exact workspace name within the project. |
|
|
147
|
+
| `pipelines` | List of pipeline names to load configs for. `['*']` loads **all** pipelines in the workspace. Names not found are added as **dummy configs** with empty stages — useful for creating new pipelines on first deploy. |
|
|
148
|
+
| `qa` | If `True`, points to `https://aic.qa.jdpower.com/apis/core/v1`; otherwise prod (`https://prod.jdpower.ai/apis/core/v1`). |
|
|
149
|
+
|
|
150
|
+
**Resolved attributes**
|
|
151
|
+
|
|
152
|
+
| Attribute | Type | Meaning |
|
|
153
|
+
|-----------|------|---------|
|
|
154
|
+
| `base_url` | `str` | Endpoint root, prod or QA. |
|
|
155
|
+
| `headers` | `dict` | `accept`, `api-key`, `Content-Type`. |
|
|
156
|
+
| `project_id` | `str` | Resolved via `get_project_id`. |
|
|
157
|
+
| `workspace` | `str` | Original workspace name. |
|
|
158
|
+
| `workspace_id` | `str` | Resolved via `get_workspace_id`. |
|
|
159
|
+
| `pipelines` | `list[{'name','id'}]` | All pipelines in the workspace (populated by `pop_pipelines`). |
|
|
160
|
+
| `pipeline_configs` | `list[{'name','jobConfig','id'}]` | Configs for the requested subset (populated by `pop_pipeline_config`, parallelized via `ThreadPoolExecutor`). |
|
|
161
|
+
| `timestamp` | class attr | `YYYYMMDD` of instantiation date. |
|
|
162
|
+
|
|
163
|
+
### 3.2 Discovery
|
|
164
|
+
|
|
165
|
+
| Method | Returns | Notes |
|
|
166
|
+
|--------|---------|-------|
|
|
167
|
+
| `get_project_id(project)` | `str` | Raises if project not found. |
|
|
168
|
+
| `get_workspace_id(workspace)` | `str` | Raises if workspace not found. |
|
|
169
|
+
| `pop_pipelines()` | `list[{'name','id'}]` | `GET /jobs`; refreshes `self.pipelines`. |
|
|
170
|
+
| `get_pipelines(workspace_id)` | `list[{'name','id'}]` | Same shape as above, but for an arbitrary workspace ID. |
|
|
171
|
+
| `pop_pipeline_config(pipelines)` | `list[dict]` | Parallel fetch. Pass `['*']` for all. Missing names produce dummy configs. |
|
|
172
|
+
| `fetch_pipeline_config(pipeline, direct=False)` | `dict` | `pipeline` is a `{'name', 'id'/'$id'}` dict. `direct=True` skips name lookup. |
|
|
173
|
+
| `get_config()` | `list[dict]` | Returns `self.pipeline_configs`. |
|
|
174
|
+
|
|
175
|
+
### 3.3 Pipeline upsert (CRUD)
|
|
176
|
+
|
|
177
|
+
| Method | Effect |
|
|
178
|
+
|--------|--------|
|
|
179
|
+
| `write_config_to_pipeline(config)` | `POST /jobs` upsert. If `config['id']` is set it’s included as `$id` to update; otherwise creates. |
|
|
180
|
+
| `create_or_update_pipeline(workspace_id, pipeline_config)` | Same idea but for an arbitrary workspace; on `409 Conflict` falls through to `update_pipeline`. |
|
|
181
|
+
| `update_pipeline(workspace_id, pipeline_id, pipeline_config)` | `PUT /jobs/{id}`. |
|
|
182
|
+
| `create_pipeline_branch(config)` | `PUT /interactive-pipeline/{jobId}/branches` with auto-generated name `PUSH_<YYYYMMDDHHMMSS>`. |
|
|
183
|
+
| `copy_pipelines(target_workspace_name, pipelines_to_copy)` | Copies the named pipelines from the current workspace into another (resolving target workspace by name). |
|
|
184
|
+
|
|
185
|
+
`config` shape:
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
{
|
|
189
|
+
'name': '<pipeline title>',
|
|
190
|
+
'jobConfig': { 'stages': [...], 'variables': [...], 'sourceStage': {...}, 'sinkStage': {...}, ... },
|
|
191
|
+
'id': '<existing $id, or None for create>',
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### 3.4 Workspace artifacts
|
|
196
|
+
|
|
197
|
+
| Method | Effect |
|
|
198
|
+
|--------|--------|
|
|
199
|
+
| `get_datasets()` | `GET /datasets`. |
|
|
200
|
+
| `get_tables(dataset_id)` | `GET /datasets/{id}/tables`. |
|
|
201
|
+
| `delete_branches(job_names)` | Deletes every interactive branch on each named job. |
|
|
202
|
+
| `backup_pipelines(pipelines, base_folder='.', drive_name='backups')` | Creates a `YYYYMMDD/` folder on the named drive and uploads each pipeline’s config JSON via `POST /upload-file`. `pipelines` may be names or full configs. |
|
|
203
|
+
| `get_drive_id_by_name(drive_name)` | Resolves drive by name (case-insensitive). Returns `None` if absent. |
|
|
204
|
+
|
|
205
|
+
### 3.5 Under the hood
|
|
206
|
+
|
|
207
|
+
- **Concurrency:** `pop_pipeline_config` uses `ThreadPoolExecutor`.
|
|
208
|
+
- **Error handling:** HTTP errors print status + body and continue where reasonable.
|
|
209
|
+
- **Logging:** `print()` for visibility (you can redirect to a logger via `SlackLogger`).
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
## 4. `GitLabManager` — Git ↔ AIC sync engine
|
|
214
|
+
|
|
215
|
+
`aic_utils/gitlabmanager.py` — class `GitLabManager`
|
|
216
|
+
|
|
217
|
+
Wraps the GitLab v4 REST API and binds it to an `AIC` instance. Enforces a strict 1:1 branch ↔ workspace contract, drives push/deploy passes, manages feature/release/hotfix Git flow, and can bootstrap a brand-new repo.
|
|
218
|
+
|
|
219
|
+
### 4.1 Branch role configuration
|
|
220
|
+
|
|
221
|
+
Class-level constants control which branches play which Git-flow role:
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
GitLabManager.branch_roles = {
|
|
225
|
+
"production": "main",
|
|
226
|
+
"staging": "staging",
|
|
227
|
+
"development": "dev",
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
If your repo uses different names (e.g. `develop` instead of `dev`), set this **before** instantiating any managers:
|
|
232
|
+
|
|
233
|
+
```python
|
|
234
|
+
GitLabManager.branch_roles = {"production": "main", "staging": "qa", "development": "develop"}
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
> The defaults — `main` / `staging` / `dev` — are what `GitLabRepositoryInitializer` will scaffold.
|
|
238
|
+
|
|
239
|
+
### 4.2 Constructor
|
|
240
|
+
|
|
241
|
+
```python
|
|
242
|
+
GitLabManager(
|
|
243
|
+
aic_instance, # AIC
|
|
244
|
+
gitlab_token, # str
|
|
245
|
+
gitlab_namespace, # e.g. "pin/pin-analytics"
|
|
246
|
+
repo_folder, # e.g. "pin-fusion-2.0"
|
|
247
|
+
gitlab_base_url: str = "https://git.autodatacorp.org/api/v4",
|
|
248
|
+
use_hash_comparison: bool = True,
|
|
249
|
+
email_recipients: list = None,
|
|
250
|
+
email_sender: str = None,
|
|
251
|
+
mapping_file: str = "branch_to_workspace.yaml",
|
|
252
|
+
)
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
**What `__init__` does, in order**
|
|
256
|
+
|
|
257
|
+
1. Builds GitLab auth headers (`Private-Token`).
|
|
258
|
+
2. Resolves the project (`{namespace}/{repo_folder}`); raises a clear `RuntimeError` on 404.
|
|
259
|
+
3. Caches the repo's `default_branch`.
|
|
260
|
+
4. Loads the `branch_to_workspace.yaml` from the default branch into a `BranchWorkspaceMapper`.
|
|
261
|
+
5. Picks the working branch by reverse-mapping `aic.workspace`. If no mapping exists, slugs the workspace name (`PIN FUSION 2.0` → `pin-fusion-2-0`).
|
|
262
|
+
6. Calls `ensure_branch_exists` on that branch (off `default_branch`).
|
|
263
|
+
7. Records `_allowed_push = {slug, mapped_branch}` plus `_hotfix_prefixes = ['hotfix/']`.
|
|
264
|
+
8. Calls `check_token_expiration()` (warns if ≤ 30 days).
|
|
265
|
+
9. **Locks the instance** — see §4.3.
|
|
266
|
+
|
|
267
|
+
### 4.3 Attribute lock (important)
|
|
268
|
+
|
|
269
|
+
After construction, `__setattr__` raises if you try to mutate an attribute. The only sanctioned way to change `_branch` is via:
|
|
270
|
+
|
|
271
|
+
- `create_feature_branch(name)`
|
|
272
|
+
- `create_release_branch(name)`
|
|
273
|
+
- `create_hotfix_branch(name)`
|
|
274
|
+
|
|
275
|
+
…all of which use the internal `_set_branch()` helper. `mgr.branch` is exposed as a **read-only property**.
|
|
276
|
+
|
|
277
|
+
> Practical implication: don’t reuse a `GitLabManager` across workspaces. Build a new one per environment.
|
|
278
|
+
|
|
279
|
+
### 4.4 Repository & branch utilities
|
|
280
|
+
|
|
281
|
+
| Method | Effect |
|
|
282
|
+
|--------|--------|
|
|
283
|
+
| `repository_exists(repo_path)` | `GET /projects/{path}` → 200? |
|
|
284
|
+
| `create_repository(repo_name)` | `POST /projects` under `get_subgroup_id()`, visibility `private`. |
|
|
285
|
+
| `get_subgroup_id()` | Resolves namespace path to a numeric group id. |
|
|
286
|
+
| `ensure_branch_exists(branch_name=None, ref=None)` | Creates `branch_name` off `ref` if missing. Idempotent. |
|
|
287
|
+
| `_slugify(text)` | URL-safe slug (`[^a-z0-9]+` → `-`). |
|
|
288
|
+
| `get_token_expiration_date()` | Hits `/personal_access_tokens`, returns the soonest-expiring active token's `datetime`. |
|
|
289
|
+
| `check_token_expiration(warning_threshold_days=30)` | Logs OK / warning / expired. Called automatically at init. |
|
|
290
|
+
| `generate_hash(content)` | MD5 of newline-normalized content (used by `deploy_pipelines`). |
|
|
291
|
+
|
|
292
|
+
### 4.5 File operations
|
|
293
|
+
|
|
294
|
+
| Method | Effect |
|
|
295
|
+
|--------|--------|
|
|
296
|
+
| `get_existing_file_content(repo_name, file_name)` | Tries current branch then default; base64-decodes. |
|
|
297
|
+
| `fetch_pipeline_file(full_path, ref=None)` | Raw content via `/raw?ref=...`. Falls back current → default. Raises `FileNotFoundError`. |
|
|
298
|
+
| `list_pipeline_files(subpath=None)` | Paginated `.json` list under `subpath` on current branch. Empty on 404. |
|
|
299
|
+
| `list_all_blobs(subpath)` | Recursive list of every file path under `subpath` on current branch. |
|
|
300
|
+
| `delete_file(file_name, branch=None)` | `DELETE /repository/files/...`. |
|
|
301
|
+
| `_commit_deletion_actions(paths, branch, msg_prefix)` | Batches up to **50 deletions per commit** via `POST /repository/commits`. |
|
|
302
|
+
| `_push_file(proj_encoded, file_name, file_content, branch)` | Tries `POST` (create); on 400/409 falls back to `PUT` (update). |
|
|
303
|
+
|
|
304
|
+
### 4.6 Pushing AIC → Git
|
|
305
|
+
|
|
306
|
+
```python
|
|
307
|
+
mgr.push_to_git()
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
- **Production guard:** if the current branch equals `default_branch`, prompts `(y/n)` before continuing.
|
|
311
|
+
- **Branch guard:** branch must be in `_allowed_push` or start with `hotfix/`.
|
|
312
|
+
- **Pass 1:** writes `config/{name}.json` for every entry in `aic.pipeline_configs`.
|
|
313
|
+
- **Pass 2:** for each successful pipeline, calls `_extract_and_push_code` to:
|
|
314
|
+
- dump `PYSPARK` task scripts to `code/{pipeline}/{task_id}.py`,
|
|
315
|
+
- find triple-quoted SQL blocks inside those scripts (heuristic: first word ∈ `select|insert|update|delete|with|create|drop|alter|merge`) and write each as `code/{pipeline}/{task_id}_{n}.sql`,
|
|
316
|
+
- dump `SQL` task `query`/`script`/`sql` text to `code/{pipeline}/{task_id}.sql`.
|
|
317
|
+
- **Email:** if `email_recipients` is set, sends an HTML push summary via `pyspark_utils.send_email`.
|
|
318
|
+
|
|
319
|
+
### 4.7 Deploying Git → AIC
|
|
320
|
+
|
|
321
|
+
```python
|
|
322
|
+
mgr.deploy_pipelines()
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
- Reverse-maps the current branch to a workspace and **refuses** to deploy if it doesn’t match `aic.workspace`.
|
|
326
|
+
- For each pipeline in `aic.pipeline_configs`:
|
|
327
|
+
- Fetches `config/{name}.json` from the current branch.
|
|
328
|
+
- Compares MD5 of normalized JSON (when `use_hash_comparison=True`); skips unchanged.
|
|
329
|
+
- Calls `aic.write_config_to_pipeline(...)` for changed pipelines.
|
|
330
|
+
- Emails an HTML deploy summary if configured.
|
|
331
|
+
|
|
332
|
+
> The earlier `force_sync=True` flag is no longer present — current behavior is hash-compare or always-write controlled by `use_hash_comparison` at construction time.
|
|
333
|
+
|
|
334
|
+
### 4.8 Git-flow branch creation
|
|
335
|
+
|
|
336
|
+
| Method | Source branch | Target | Notes |
|
|
337
|
+
|--------|---------------|--------|-------|
|
|
338
|
+
| `create_feature_branch(feature_name)` | `branch_roles["development"]` | `feature/{name}` | Refuses if not currently on dev. Switches `_branch` to the feature. |
|
|
339
|
+
| `create_release_branch(branch_name)` | `branch_roles["staging"]` | `release/{name}` | After cut, **prunes** any `config/*.json` and `code/<pipeline>/...` files for pipelines NOT in `aic.pipeline_configs`. |
|
|
340
|
+
| `create_hotfix_branch(branch_name)` | production (resolved via mapper, falls back to `default_branch`) | `hotfix/{name}` | Same prune behavior as release. |
|
|
341
|
+
|
|
342
|
+
All three slugify the input (replace anything outside `[A-Za-z0-9\-_/]` with `-`) and switch the manager's branch on success.
|
|
343
|
+
|
|
344
|
+
### 4.9 Merge requests
|
|
345
|
+
|
|
346
|
+
```python
|
|
347
|
+
mgr.create_merge_request(
|
|
348
|
+
title: str,
|
|
349
|
+
description: str,
|
|
350
|
+
target_branch: str | None = None, # auto-detected if omitted
|
|
351
|
+
assignee_ids: list | None = None,
|
|
352
|
+
)
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
- Refuses unless the current branch starts with `feature/`, `release/`, or `hotfix/`.
|
|
356
|
+
- Auto-target rules when `target_branch` is omitted:
|
|
357
|
+
- `feature/*` → `staging`
|
|
358
|
+
- `release/*`, `hotfix/*`, or `staging` → `main`
|
|
359
|
+
- else → `main`
|
|
360
|
+
- After opening the MR, **switches the manager back to the original branch** so the workflow stays predictable. The MR `iid` is logged.
|
|
361
|
+
|
|
362
|
+
> Note: the auto-target string literals are hardcoded to `"main"` / `"staging"` — if you customize `branch_roles`, pass `target_branch` explicitly.
|
|
363
|
+
|
|
364
|
+
### 4.10 Repo bootstrap & wipe (classmethods)
|
|
365
|
+
|
|
366
|
+
```python
|
|
367
|
+
GitLabManager.initialize_repository(
|
|
368
|
+
gitlab_token, gitlab_namespace, repo_folder,
|
|
369
|
+
gitlab_base_url="https://git.autodatacorp.org/api/v4",
|
|
370
|
+
)
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
Builds a minimally-initialized manager via `_setup_for_initialization` and hands off to `GitLabRepositoryInitializer` (see §6). Returns `True/False`.
|
|
374
|
+
|
|
375
|
+
```python
|
|
376
|
+
GitLabManager.wipe_repository(
|
|
377
|
+
gitlab_token, gitlab_namespace, repo_folder,
|
|
378
|
+
gitlab_base_url="https://git.autodatacorp.org/api/v4",
|
|
379
|
+
keep_branches=None, # default ['main']
|
|
380
|
+
)
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
**Destructive.** Prompts `(y/n)` first, then:
|
|
384
|
+
|
|
385
|
+
1. Lists every branch.
|
|
386
|
+
2. For each kept branch, deletes every blob via per-file `DELETE`.
|
|
387
|
+
3. Deletes every other branch (skips `main`/`master` defensively, removes branch protections first).
|
|
388
|
+
|
|
389
|
+
### 4.11 Email helpers
|
|
390
|
+
|
|
391
|
+
`_send_email(subject, body, cc=None, bcc=None, attachments=None, testing=True)`
|
|
392
|
+
`_format_push_summary(branch, results)` → `(subject, html_body)`
|
|
393
|
+
`_format_deploy_summary(branch, results)` → `(subject, html_body)`
|
|
394
|
+
|
|
395
|
+
`results` is a list of `(pipeline_name, status, message)` tuples, rendered as an HTML table.
|
|
396
|
+
|
|
397
|
+
---
|
|
398
|
+
|
|
399
|
+
## 5. `BranchWorkspaceMapper` — branch ↔ workspace mapping
|
|
400
|
+
|
|
401
|
+
Defined in `gitlabmanager.py`. Constructed automatically by `GitLabManager.__init__` from `branch_to_workspace.yaml` on the default branch.
|
|
402
|
+
|
|
403
|
+
**YAML format:**
|
|
404
|
+
|
|
405
|
+
```yaml
|
|
406
|
+
mapping:
|
|
407
|
+
main: PIN FUSION 2.0
|
|
408
|
+
staging: PIN FUSION 2.0 QA
|
|
409
|
+
dev: PIN FUSION 2.0 DEV
|
|
410
|
+
intg/*: PIN FUSION 2.0 INTG # wildcard prefix
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
**API:**
|
|
414
|
+
|
|
415
|
+
| Method | Behavior |
|
|
416
|
+
|--------|----------|
|
|
417
|
+
| `lookup(branch)` | Exact match → prefix match (keys ending in `/*`) → built-ins (`feature/*` → `develop` mapping; `release/*`, `hotfix/*` → `main` mapping). Raises `KeyError` if nothing matches. |
|
|
418
|
+
| `workspace_to_branch(workspace)` | Reverse lookup; falls back to the workspace name slugified to `lowercase-with-dashes`. |
|
|
419
|
+
|
|
420
|
+
> `lookup` looks up the **mapping keys** literally — its built-in `feature/*` fallback is keyed off `develop` (not `dev`). If you renamed the dev branch, add an explicit mapping for the dev branch and rely on exact/prefix rules rather than the built-in.
|
|
421
|
+
|
|
422
|
+
---
|
|
423
|
+
|
|
424
|
+
## 6. `GitLabRepositoryInitializer` — bootstrap a new repo
|
|
425
|
+
|
|
426
|
+
`aic_utils/gitlab_init.py` — class `GitLabRepositoryInitializer`
|
|
427
|
+
|
|
428
|
+
Usually invoked indirectly via `GitLabManager.initialize_repository(...)`. It performs a one-time setup of a freshly-created empty GitLab project.
|
|
429
|
+
|
|
430
|
+
**`initialize_repository()` runs, in order:**
|
|
431
|
+
|
|
432
|
+
1. **`_enforce_main_branch()`** — if the default branch isn’t `branch_roles["production"]` (default `main`), creates it from the existing default, sets it as default, protects it (push/merge level 30 = maintainer), and deletes the original.
|
|
433
|
+
2. **`_create_initial_branches()`** — creates `staging` and `dev` (or whatever `branch_roles` specifies) off the default branch.
|
|
434
|
+
3. **`_create_initial_files()`** — pushes onto the default branch:
|
|
435
|
+
- `branch_to_workspace.yaml` with placeholder workspace names,
|
|
436
|
+
- `SECURITY.md` documenting JDP scanners and remediation timelines,
|
|
437
|
+
- `config/.gitkeep`,
|
|
438
|
+
- `code/.gitkeep`.
|
|
439
|
+
4. **`_setup_security_scanning()`** — writes a `.gitlab-ci.yml` that includes the corporate templates for the matching group (`alg` / `pin` / `ucg` → otherwise `corp`) and wires SAST, dependency scanning, secret detection, code quality, plus a manual `deploy_pipelines` job.
|
|
440
|
+
5. **`_enable_cicd_features()`** — `PUT /projects/{id}` to enable builds/MRs/security & compliance and disable wiki/snippets/registry.
|
|
441
|
+
6. **`_setup_branch_protection()`** — protects production, staging, and development (push/merge level 30).
|
|
442
|
+
7. **`_generate_readme()`** — derives project + company names from the namespace and writes a tailored `README.md` (the same one you’re reading describes how to use it).
|
|
443
|
+
|
|
444
|
+
All steps are idempotent enough to re-run safely (existing branches, files, and protections return 409 and are logged as warnings).
|
|
445
|
+
|
|
446
|
+
---
|
|
447
|
+
|
|
448
|
+
## 7. `DatasetConverter` — placeholder rewriting
|
|
449
|
+
|
|
450
|
+
`aic_utils/dataset_converter.py` — class `DatasetConverter`
|
|
451
|
+
|
|
452
|
+
Purpose: rewrite **bare table names** in pipeline configs into AIC dataset-aware placeholders (`${DATASET.TABLE}`), then push the rewritten config to a new interactive AIC branch named `CONVERTED_<YYYYMMDDHHMMSS>`. Intended for one-shot migration of legacy pipelines that hard-coded table names.
|
|
453
|
+
|
|
454
|
+
### 7.1 Constructor
|
|
455
|
+
|
|
456
|
+
```python
|
|
457
|
+
DatasetConverter(api_key, project, workspace,
|
|
458
|
+
target_workspace=None, qa=False)
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
- Resolves project and workspace exactly like `AIC`.
|
|
462
|
+
- If `target_workspace` is supplied, the **table catalog** (used as the lookup dictionary) is built from that workspace; otherwise from the source workspace.
|
|
463
|
+
- Loads `self.tables` as a `pandas.DataFrame` of `{dataset_name, dataset_id, table_name}` (parallel fetch via `ThreadPoolExecutor`).
|
|
464
|
+
|
|
465
|
+
### 7.2 Methods
|
|
466
|
+
|
|
467
|
+
| Method | Behavior |
|
|
468
|
+
|--------|----------|
|
|
469
|
+
| `pop_tables(workspace_id)` | Populates `self.tables`. |
|
|
470
|
+
| `get_datasets(workspace_id)` | `GET /datasets`. |
|
|
471
|
+
| `get_tables(dataset, workspace_id)` | `GET /datasets/{id}/tables`. |
|
|
472
|
+
| `get_pipelines()` | List of `{name,id}` for the source workspace. |
|
|
473
|
+
| `fetch_pipeline_config(pipeline_name)` | Returns `{name, jobConfig, id}` or `None`. |
|
|
474
|
+
| `convert(pipelines)` | For each name: fetch → `replace_placeholders` → `replace_source_stages_with_documentation` → `create_pipeline_branch`. |
|
|
475
|
+
| `replace_placeholders(config)` | Recursively walks the config; if any string equals a known table name, rewrites it as `${DATASET.TABLE}` and appends a markdown bullet to `self.audit_log`. |
|
|
476
|
+
| `replace_source_stages_with_documentation(config)` | Strips out `DATASET`-typed source tasks and inserts a `DOCUMENTATION` task containing the audit log markdown. |
|
|
477
|
+
| `create_pipeline_branch(config)` | Pushes the rewritten jobConfig to `interactive-pipeline/{job_id}/branches` as `CONVERTED_<timestamp>`. |
|
|
478
|
+
|
|
479
|
+
---
|
|
480
|
+
|
|
481
|
+
## 8. `SlackLogger` — Slack-backed Python logger
|
|
482
|
+
|
|
483
|
+
`aic_utils/slack_logger.py` — class `SlackLogger`
|
|
484
|
+
|
|
485
|
+
Bridges Python’s `logging` (and optionally `print`) to a Slack channel via `slack_sdk`. Includes a re-entrancy guard so messages emitted while sending don’t loop.
|
|
486
|
+
|
|
487
|
+
### 8.1 API
|
|
488
|
+
|
|
489
|
+
```python
|
|
490
|
+
SlackLogger(token: str, channel: str)
|
|
491
|
+
.send_message(text) # post a single message
|
|
492
|
+
.SlackLoggerHandler # nested logging.Handler
|
|
493
|
+
|
|
494
|
+
SlackLogger.redirect_print_to_logger(logger) # monkey-patches builtins.print
|
|
495
|
+
SlackLogger.create_logger(slack_token,
|
|
496
|
+
slack_channel='C07DYFK5SE8',
|
|
497
|
+
redirect_print=True) # returns a configured logging.Logger
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
`create_logger`:
|
|
501
|
+
|
|
502
|
+
1. Instantiates `SlackLogger`.
|
|
503
|
+
2. Builds a `SlackLoggerHandler` wired to it.
|
|
504
|
+
3. Returns a `logging.Logger` named `'SlackLogger'` at INFO level with format `%(asctime)s - %(levelname)s - %(message)s`.
|
|
505
|
+
4. If `redirect_print=True`, re-points `builtins.print` at `logger.info`.
|
|
506
|
+
|
|
507
|
+
The default channel ID `'C07DYFK5SE8'` is JDP-internal — pass your own.
|
|
508
|
+
|
|
509
|
+
### 8.2 Example
|
|
510
|
+
|
|
511
|
+
```python
|
|
512
|
+
from aic_utils import SlackLogger
|
|
513
|
+
|
|
514
|
+
logger = SlackLogger.create_logger(
|
|
515
|
+
slack_token="xoxb-…",
|
|
516
|
+
slack_channel="C0123456789",
|
|
517
|
+
redirect_print=True, # any subsequent print() lands in Slack
|
|
518
|
+
)
|
|
519
|
+
logger.info("Pipeline run started")
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
---
|
|
523
|
+
|
|
524
|
+
## 9. Day-to-day workflows
|
|
525
|
+
|
|
526
|
+
The branch role names below assume the defaults `production="main"`, `staging="staging"`, `development="dev"`. Substitute as needed.
|
|
527
|
+
|
|
528
|
+
### 9.1 First-time repository setup
|
|
529
|
+
|
|
530
|
+
```python
|
|
531
|
+
from aic_utils import GitLabManager
|
|
532
|
+
|
|
533
|
+
GitLabManager.initialize_repository(
|
|
534
|
+
gitlab_token="<GIT_TOKEN>",
|
|
535
|
+
gitlab_namespace="pin/pin-analytics",
|
|
536
|
+
repo_folder="pin-fusion-2.0",
|
|
537
|
+
)
|
|
538
|
+
# Then edit branch_to_workspace.yaml with real workspace names.
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
### 9.2 Build the manager pair
|
|
542
|
+
|
|
543
|
+
```python
|
|
544
|
+
from aic_utils import AIC, GitLabManager
|
|
545
|
+
|
|
546
|
+
aic_prod = AIC(
|
|
547
|
+
api_key="<API_KEY>",
|
|
548
|
+
project="dylan.doyle@jdpa.com",
|
|
549
|
+
workspace="PIN FUSION 2.0",
|
|
550
|
+
pipelines=["*"], # or a curated list
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
mgr = GitLabManager(
|
|
554
|
+
aic_instance=aic_prod,
|
|
555
|
+
gitlab_token="<GIT_TOKEN>",
|
|
556
|
+
gitlab_namespace="pin/pin-analytics",
|
|
557
|
+
repo_folder="pin-fusion-2.0",
|
|
558
|
+
)
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
### 9.3 Sync AIC → Git on the dev environment
|
|
562
|
+
|
|
563
|
+
```python
|
|
564
|
+
aic_dev = AIC(api_key=..., project=..., workspace="PIN FUSION 2.0 DEV", pipelines=[...])
|
|
565
|
+
mgr_dev = GitLabManager(aic_instance=aic_dev, ...)
|
|
566
|
+
mgr_dev.push_to_git()
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
Restrictions:
|
|
570
|
+
|
|
571
|
+
- `push_to_git` on `main` requires interactive `y` confirmation.
|
|
572
|
+
- Push is rejected if the current branch isn’t in `_allowed_push` (slug + mapped branch) and isn't a `hotfix/*`.
|
|
573
|
+
|
|
574
|
+
### 9.4 Promote dev → staging via a feature MR
|
|
575
|
+
|
|
576
|
+
```python
|
|
577
|
+
mgr_dev.create_feature_branch("PINOPS-1831") # cuts feature/PINOPS-1831 from dev
|
|
578
|
+
mgr_dev.create_merge_request(
|
|
579
|
+
title="Demographics module",
|
|
580
|
+
description="QA push",
|
|
581
|
+
target_branch="staging", # pass explicitly if you customized roles
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
# After the MR is merged, deploy on the QA workspace:
|
|
585
|
+
aic_qa = AIC(api_key=..., workspace="PIN FUSION 2.0 QA", pipelines=[...])
|
|
586
|
+
mgr_qa = GitLabManager(aic_instance=aic_qa, ...)
|
|
587
|
+
mgr_qa.deploy_pipelines()
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
### 9.5 Promote staging → prod via a release MR
|
|
591
|
+
|
|
592
|
+
```python
|
|
593
|
+
mgr_qa.push_to_git() # capture latest QA state
|
|
594
|
+
mgr_qa.create_release_branch("v2.1.0") # cuts release/v2.1.0 from staging,
|
|
595
|
+
# prunes pipelines not in aic.pipeline_configs
|
|
596
|
+
mgr_qa.create_merge_request(
|
|
597
|
+
title="Release v2.1.0",
|
|
598
|
+
description="QA-approved",
|
|
599
|
+
target_branch="main",
|
|
600
|
+
)
|
|
601
|
+
|
|
602
|
+
# After merge:
|
|
603
|
+
mgr_prod = GitLabManager(aic_instance=aic_prod, ...)
|
|
604
|
+
mgr_prod.deploy_pipelines()
|
|
605
|
+
```
|
|
606
|
+
|
|
607
|
+
### 9.6 Production hotfix
|
|
608
|
+
|
|
609
|
+
The order is **inverted** from feature/release: the fix is applied **in AIC prod first**, then captured in Git.
|
|
610
|
+
|
|
611
|
+
```python
|
|
612
|
+
# 1. Apply the fix manually in AIC prod workspace.
|
|
613
|
+
|
|
614
|
+
# 2. Build a fresh prod AIC + manager (so it sees the new config).
|
|
615
|
+
aic_prod = AIC(api_key=..., workspace="PIN FUSION 2.0", pipelines=["BROKEN_PIPELINE"])
|
|
616
|
+
mgr_prod = GitLabManager(aic_instance=aic_prod, ...)
|
|
617
|
+
|
|
618
|
+
# 3. Cut hotfix off main and push the AIC state into the hotfix branch.
|
|
619
|
+
mgr_prod.create_hotfix_branch("PINOPS-1831")
|
|
620
|
+
mgr_prod.push_to_git()
|
|
621
|
+
|
|
622
|
+
# 4. Open MR back into main for the audit trail.
|
|
623
|
+
mgr_prod.create_merge_request(
|
|
624
|
+
title="Hotfix PINOPS-1831",
|
|
625
|
+
description="Emergency fix for streaming timeout",
|
|
626
|
+
target_branch="main",
|
|
627
|
+
)
|
|
628
|
+
```
|
|
629
|
+
|
|
630
|
+
### 9.7 Convert legacy placeholders
|
|
631
|
+
|
|
632
|
+
```python
|
|
633
|
+
from aic_utils import DatasetConverter
|
|
634
|
+
|
|
635
|
+
dc = DatasetConverter(
|
|
636
|
+
api_key="<API_KEY>",
|
|
637
|
+
project="dylan.doyle@jdpa.com",
|
|
638
|
+
workspace="LEGACY",
|
|
639
|
+
target_workspace="PIN FUSION 2.0", # use this workspace's catalog as the lookup
|
|
640
|
+
)
|
|
641
|
+
dc.convert(["LEGACY_PIPELINE_A", "LEGACY_PIPELINE_B"])
|
|
642
|
+
# Each pipeline now has a CONVERTED_<timestamp> AIC branch with rewritten placeholders.
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
### 9.8 Stream logs/print to Slack
|
|
646
|
+
|
|
647
|
+
```python
|
|
648
|
+
from aic_utils import SlackLogger
|
|
649
|
+
SlackLogger.create_logger("<SLACK_TOKEN>", "<CHANNEL_ID>", redirect_print=True)
|
|
650
|
+
print("from now on, this lands in Slack")
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
---
|
|
654
|
+
|
|
655
|
+
## 10. Best practices & troubleshooting
|
|
656
|
+
|
|
657
|
+
**Operating principles**
|
|
658
|
+
|
|
659
|
+
1. **One AIC + one GitLabManager per environment.** The manager locks itself after init.
|
|
660
|
+
2. **Promotions go through MRs.** `main` / `staging` / `dev` should be protected; only `feature/*`, `release/*`, `hotfix/*` cut from them.
|
|
661
|
+
3. **Hash compare is on by default.** Set `use_hash_comparison=False` if you want every deploy to write regardless of diff.
|
|
662
|
+
4. **Keep `branch_to_workspace.yaml` truthful.** The mapper reads it from the **default branch only**.
|
|
663
|
+
5. **`branch_roles` is class-level.** Setting it after construction does not retroactively rebuild allowed-push sets.
|
|
664
|
+
|
|
665
|
+
**Common errors**
|
|
666
|
+
|
|
667
|
+
| Symptom | Likely cause | Fix |
|
|
668
|
+
|---------|--------------|-----|
|
|
669
|
+
| `RuntimeError: ❌ GitLab project ... not found` | `gitlab_namespace` or `repo_folder` typo | Verify in GitLab UI. |
|
|
670
|
+
| `❌ Cannot modify attribute 'X' after initialization` | Trying to mutate manager state directly | Use `create_*_branch` helpers; build a new manager for a new workspace. |
|
|
671
|
+
| `❌ Cannot push to branch '...'` | Current branch isn’t in `_allowed_push` and isn’t `hotfix/*` | You probably checked out a feature branch — push, then MR; don’t push features directly. |
|
|
672
|
+
| `❌ Branch '...' maps to workspace '...', not '...'` (on deploy) | Mismatched branch ↔ AIC workspace | Use the correct AIC workspace for the branch you’re deploying. |
|
|
673
|
+
| `FileNotFoundError: 'branch_to_workspace.yaml' not found ...` | Missing/renamed mapping file on default branch | Add it on `main` (or whatever your default branch is). |
|
|
674
|
+
| `pyspark_utils` import error | `email_recipients` was set but the package isn’t installed | Either `pip install pyspark_utils` or unset `email_recipients`. |
|
|
675
|
+
| Token nearing expiry warning at init | <30 days remaining | Rotate the GitLab token. |
|
|
676
|
+
|
|
677
|
+
**Contact**
|
|
678
|
+
|
|
679
|
+
- GitHub: https://github.com/dylandoyle11/aic_utils
|
|
680
|
+
- Maintainer: Dylan Doyle
|