Добавить обзор решений Aurora и скрипты сбора снимков
This commit is contained in:
185
scripts/export_gitlab_repos.py
Normal file
185
scripts/export_gitlab_repos.py
Normal file
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Download repository ZIP snapshots through the GitLab API."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
from zipfile import BadZipFile, ZipFile
|
||||
|
||||
import gitlab
|
||||
from gitlab.exceptions import GitlabAuthenticationError, GitlabError
|
||||
from requests.exceptions import RequestException
|
||||
|
||||
|
||||
DEFAULT_OUTPUT = Path(__file__).resolve().parents[1] / "gitlab_exports"
|
||||
PATH_COMPONENT = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]*")
|
||||
|
||||
|
||||
def https_origin(url):
|
||||
if url.scheme != "https" or not url.hostname or url.username is not None:
|
||||
raise ValueError("use an HTTPS URL without embedded credentials")
|
||||
return url.hostname, url.port or 443
|
||||
|
||||
|
||||
def resource_id(value, base_url, *, group=False):
|
||||
if value.isascii() and value.isdecimal():
|
||||
return int(value)
|
||||
url = urlsplit(value)
|
||||
path = unquote(url.path).strip("/")
|
||||
if url.scheme or url.netloc:
|
||||
if https_origin(url) != https_origin(base_url):
|
||||
raise ValueError("the URL must belong to GITLAB_URL")
|
||||
base_path = unquote(base_url.path).strip("/")
|
||||
if base_path:
|
||||
if not path.startswith(base_path + "/"):
|
||||
raise ValueError("the URL must be under the path in GITLAB_URL")
|
||||
path = path[len(base_path) + 1 :]
|
||||
if group:
|
||||
path = path.removeprefix("groups/")
|
||||
path = path.split("/-/", 1)[0].removesuffix("/-")
|
||||
if not group:
|
||||
path = path.removesuffix(".git")
|
||||
parts = path.split("/")
|
||||
if (not group and len(parts) < 2) or not all(
|
||||
PATH_COMPONENT.fullmatch(part) for part in parts
|
||||
):
|
||||
raise ValueError("use a GitLab URL, namespace path, or numeric ID")
|
||||
return path
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
source = parser.add_mutually_exclusive_group(required=True)
|
||||
source.add_argument("--group", help="Group URL, namespace path, or numeric ID")
|
||||
source.add_argument("--project", action="append", help="Project URL, path, or ID; repeatable")
|
||||
source.add_argument("--projects-file", type=Path, help="One project URL, path, or ID per line")
|
||||
parser.add_argument("--include-subgroups", action="store_true", help="Include nested groups")
|
||||
parser.add_argument("--list", action="store_true", help="List projects without downloading")
|
||||
parser.add_argument("--ref", help="Branch, tag, or commit SHA; defaults to each default branch")
|
||||
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT, help="Parent for run directories")
|
||||
args = parser.parse_args()
|
||||
if args.include_subgroups and args.group is None:
|
||||
parser.error("--include-subgroups requires --group")
|
||||
|
||||
server = os.environ.get("GITLAB_URL", "").strip().rstrip("/")
|
||||
token = os.environ.get("GITLAB_TOKEN", "").strip()
|
||||
if not server or not token:
|
||||
parser.error("set GITLAB_URL and GITLAB_TOKEN")
|
||||
try:
|
||||
base_url = urlsplit(server)
|
||||
https_origin(base_url)
|
||||
if base_url.query or base_url.fragment:
|
||||
raise ValueError("GITLAB_URL must be the instance base URL")
|
||||
if args.group is not None:
|
||||
selection = resource_id(args.group, base_url, group=True)
|
||||
else:
|
||||
values = args.project
|
||||
if args.projects_file is not None:
|
||||
lines = args.projects_file.read_text(encoding="utf-8-sig").splitlines()
|
||||
values = [line.strip() for line in lines if line.strip() and not line.lstrip().startswith("#")]
|
||||
if not values:
|
||||
raise ValueError("the project list is empty")
|
||||
selection = list(dict.fromkeys(resource_id(value, base_url) for value in values))
|
||||
except (OSError, ValueError) as error:
|
||||
parser.error(str(error))
|
||||
return args, server, token, selection
|
||||
|
||||
|
||||
def download(project, output, ref):
|
||||
slug = re.sub(r"[^A-Za-z0-9_.-]+", "-", project.path_with_namespace)[:160]
|
||||
destination = output / f"{project.id}-{slug}.zip"
|
||||
partial = destination.with_suffix(".zip.part")
|
||||
try:
|
||||
with partial.open("xb") as file:
|
||||
project.repository_archive(
|
||||
sha=ref, format="zip", streamed=True, action=file.write, chunk_size=1024 * 1024
|
||||
)
|
||||
with ZipFile(partial) as archive:
|
||||
bad_member = archive.testzip()
|
||||
if bad_member is not None:
|
||||
raise ValueError("invalid ZIP member checksum")
|
||||
partial.replace(destination)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
return destination
|
||||
|
||||
|
||||
def report_error(target, error):
|
||||
status = getattr(error, "response_code", None)
|
||||
detail = f"HTTP {status}" if status else f"{type(error).__name__}: {error}"
|
||||
print(f"ERROR {target}: {detail}", file=sys.stderr)
|
||||
|
||||
|
||||
def run(client, args, selection):
|
||||
output = None
|
||||
completed = set()
|
||||
failed = 0
|
||||
|
||||
if args.group is not None:
|
||||
print(f"Loading group {selection}...", file=sys.stderr, flush=True)
|
||||
group = client.groups.get(selection)
|
||||
print("Loading project list...", file=sys.stderr, flush=True)
|
||||
candidates = (
|
||||
project.id for project in group.projects.list(
|
||||
iterator=True, include_subgroups=args.include_subgroups, with_shared=False
|
||||
)
|
||||
)
|
||||
else:
|
||||
candidates = iter(selection)
|
||||
|
||||
for candidate in candidates:
|
||||
try:
|
||||
print(f"Loading project {candidate}...", file=sys.stderr, flush=True)
|
||||
project = client.projects.get(candidate)
|
||||
if project.id in completed:
|
||||
continue
|
||||
if args.list:
|
||||
print(project.path_with_namespace)
|
||||
else:
|
||||
if output is None:
|
||||
args.output.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
output = Path(tempfile.mkdtemp(prefix="run-", dir=args.output))
|
||||
print(download(project, output, args.ref), flush=True)
|
||||
completed.add(project.id)
|
||||
except GitlabAuthenticationError:
|
||||
raise
|
||||
except (GitlabError, RequestException, OSError, BadZipFile, ValueError) as error:
|
||||
report_error(candidate, error)
|
||||
failed += 1
|
||||
print(f"{'Listed' if args.list else 'Saved'}: {len(completed)}; failed: {failed}")
|
||||
if not completed and not failed:
|
||||
print("No visible projects found.", file=sys.stderr)
|
||||
return int(bool(failed) or not completed)
|
||||
|
||||
|
||||
def main():
|
||||
args, server, token, selection = parse_args()
|
||||
ssl_verify = os.environ.get("GITLAB_SSL_VERIFY", "true").strip().lower() not in {
|
||||
"false", "0", "no", "off"
|
||||
}
|
||||
try:
|
||||
print(f"Connecting to GitLab at {server}...", file=sys.stderr, flush=True)
|
||||
if not ssl_verify:
|
||||
print("WARNING: TLS certificate verification is disabled.", file=sys.stderr, flush=True)
|
||||
with gitlab.Gitlab(
|
||||
server,
|
||||
private_token=token,
|
||||
ssl_verify=ssl_verify,
|
||||
timeout=120,
|
||||
retry_transient_errors=True,
|
||||
) as client:
|
||||
print("Authenticating...", file=sys.stderr, flush=True)
|
||||
client.auth()
|
||||
print("Authentication succeeded.", file=sys.stderr, flush=True)
|
||||
return run(client, args, selection)
|
||||
except (GitlabError, RequestException) as error:
|
||||
report_error("GitLab API", error)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
118
scripts/inventory_aurora.ps1
Normal file
118
scripts/inventory_aurora.ps1
Normal file
@@ -0,0 +1,118 @@
|
||||
# Requires PowerShell 7. Reads ZIP snapshots without extracting or running their contents.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Priority,
|
||||
[Parameter(Mandatory)][string]$Bulk,
|
||||
[Parameter(Mandatory)][string]$Output
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
|
||||
function Get-ArchiveProfile($File, $Tier) {
|
||||
$name = $File.BaseName -replace '^\d+-instance-aurora-', '' -replace '-(master|main)$', ''
|
||||
$row = [ordered]@{
|
||||
archive = $File.Name; name = $name; tier = $Tier; status = 'ok'
|
||||
root = ''; revision = ''; signature = ''; bytes = $File.Length
|
||||
files = 0; source_files = 0; entrypoints = @(); stack = @(); signals = @(); evidence = @()
|
||||
}
|
||||
try {
|
||||
$zip = [IO.Compression.ZipFile]::OpenRead($File.FullName)
|
||||
try {
|
||||
$files = @($zip.Entries | Where-Object Name)
|
||||
$row.files = $files.Count
|
||||
$roots = @($files | ForEach-Object { ($_.FullName -split '/', 2)[0] } | Sort-Object -Unique)
|
||||
$stripRoot = $roots.Count -eq 1 -and $files.Count -gt 0 -and $files[0].FullName.Contains('/')
|
||||
if ($stripRoot) {
|
||||
$row.root = $roots[0]
|
||||
if ($row.root -match '-([a-f0-9]{7,40})$') { $row.revision = $Matches[1] }
|
||||
}
|
||||
$entries = foreach ($entry in $files) {
|
||||
$path = $entry.FullName
|
||||
if ($stripRoot) { $path = $path.Substring($row.root.Length + 1) }
|
||||
[pscustomobject]@{ path = $path; entry = $entry }
|
||||
}
|
||||
$sha = [Security.Cryptography.SHA256]::Create()
|
||||
try {
|
||||
$manifest = foreach ($item in ($entries | Sort-Object path -CaseSensitive)) {
|
||||
$stream = $item.entry.Open()
|
||||
try { $hash = [Convert]::ToHexString($sha.ComputeHash($stream)) }
|
||||
finally { $stream.Dispose() }
|
||||
"$($item.path)`t$hash"
|
||||
}
|
||||
$row.signature = [Convert]::ToHexString($sha.ComputeHash(
|
||||
[Text.Encoding]::UTF8.GetBytes(($manifest -join "`n"))
|
||||
))
|
||||
} finally { $sha.Dispose() }
|
||||
$sources = @($entries | Where-Object {
|
||||
$_.path -match '\.(py|tsx?|jsx?|sql|vue)$' -and
|
||||
$_.path -notmatch '(^|/)(tests?|node_modules|vendor|dist|build|static|migrations|alembic|fixtures)(/|$)|(^|/)test_'
|
||||
})
|
||||
$row.source_files = $sources.Count
|
||||
$row.entrypoints = @($sources | Where-Object {
|
||||
$_.path -match '(^|/)(main|app|router|routes|pipeline)\.(py|tsx?|jsx?)$|(^|/)dags/[^/]+\.py$'
|
||||
} | Select-Object -First 4 -ExpandProperty path)
|
||||
if (-not $row.entrypoints.Count) {
|
||||
$row.entrypoints = @($sources | Select-Object -First 2 -ExpandProperty path)
|
||||
}
|
||||
$stackPatterns = [ordered]@{
|
||||
FastAPI = '\bfastapi\b'; React = '["'']react["'']'; Streamlit = '\bstreamlit\b'
|
||||
Airflow = '\b(?:apache-airflow|airflow)\b'; SQLAlchemy = '\bsqlalchemy\b'
|
||||
Greenplum = '\bgreenplum\b'; PostgreSQL = '\b(?:psycopg2?|asyncpg|postgresql)\b'
|
||||
}
|
||||
$signalPatterns = [ordered]@{
|
||||
Airflow = '\b(?:ExternalTaskSensor|PythonOperator|BranchPythonOperator|BaseSensorOperator|TriggerDagRunOperator|DagRun|DAG)\b'
|
||||
'S3/MinIO' = '\b(?:boto3|aioboto3|Minio|S3Hook|presigned_url)\b'
|
||||
'Файлы и Excel' = '\b(?:openpyxl|xlsxwriter|read_excel|UploadFile|StreamingResponse)\b'
|
||||
'PDF' = '\b(?:pdfplumber|pypdf|PyPDF2|fitz)\b'
|
||||
'SOAP' = '\b(?:zeep|suds|soapaction)\b'
|
||||
'LDAP/Kerberos' = '\b(?:ldap3|requests_kerberos|gssapi)\b'
|
||||
'Очереди и фоновые задачи' = '\b(?:Celery|BackgroundTasks|BackgroundTask|TaskiqScheduler|KafkaConsumer|RedisBroker)\b'
|
||||
'Пакетная запись в БД' = '\b(?:execute_values|copy_expert|copy_from|to_sql)\b'
|
||||
'UI-таблицы' = '\b(?:AgGrid|AgGridReact|useReactTable|Handsontable|st\.data_editor)\b'
|
||||
'Версии и блокировки' = '(version_compare|compare_versions|directory.lock|with_for_update|advisory_lock|undo.manager)'
|
||||
'Прикладной аудит' = '(audit_log|audit_journal|auditlog)'
|
||||
}
|
||||
$stack = [Collections.Generic.HashSet[string]]::new()
|
||||
$hits = [ordered]@{}
|
||||
$sourcePaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
|
||||
foreach ($source in $sources) { [void]$sourcePaths.Add($source.path) }
|
||||
$review = $entries | Where-Object {
|
||||
$sourcePaths.Contains($_.path) -or $_.path -match '(^|/)(requirements[^/]*\.txt|pyproject\.toml|package\.json)$'
|
||||
}
|
||||
foreach ($item in $review) {
|
||||
if ($item.entry.Length -gt 256KB) { continue }
|
||||
$reader = [IO.StreamReader]::new($item.entry.Open())
|
||||
try { $body = $reader.ReadToEnd() } finally { $reader.Dispose() }
|
||||
foreach ($key in $stackPatterns.Keys) {
|
||||
if ($body -match $stackPatterns[$key]) { [void]$stack.Add($key) }
|
||||
}
|
||||
foreach ($key in $signalPatterns.Keys) {
|
||||
if ($item.path -notmatch $signalPatterns[$key] -and $body -notmatch $signalPatterns[$key]) { continue }
|
||||
if (-not $hits.Contains($key)) { $hits[$key] = @() }
|
||||
if ($hits[$key].Count -lt 3) { $hits[$key] += $item.path }
|
||||
}
|
||||
}
|
||||
$row.stack = @($stack | Sort-Object)
|
||||
$row.signals = @($hits.Keys)
|
||||
$row.evidence = @($hits.GetEnumerator() | ForEach-Object {
|
||||
@{ signal = $_.Key; paths = @($_.Value) }
|
||||
})
|
||||
} finally { $zip.Dispose() }
|
||||
} catch {
|
||||
$row.status = 'unreadable'
|
||||
}
|
||||
[pscustomobject]$row
|
||||
}
|
||||
|
||||
$rows = @(
|
||||
foreach ($pair in @(@{root = $Priority; tier = 'priority'}, @{root = $Bulk; tier = 'bulk'})) {
|
||||
foreach ($file in (Get-ChildItem -LiteralPath $pair.root -File -Filter '*.zip' | Sort-Object Name)) {
|
||||
if ($file.Extension -ne '.zip') { continue }
|
||||
Get-ArchiveProfile $file $pair.tier
|
||||
}
|
||||
}
|
||||
)
|
||||
if ($rows.Count -eq 0) { throw 'No ZIP files found in either input directory.' }
|
||||
ConvertTo-Json -InputObject $rows -Depth 7 | Set-Content -LiteralPath $Output -Encoding utf8
|
||||
$rows | Group-Object tier,status | Select-Object Name,Count
|
||||
Reference in New Issue
Block a user