@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.1.r1
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.
- package/README.md +30 -0
- package/entry.py +16 -0
- package/package.json +1 -0
- package/plugin_cli.py +14 -0
- package/runtime/cli.ps1 +4 -0
- package/runtime/cli.sh +5 -0
- package/tedbrain_plugin_runtime/__init__.py +2 -0
- package/tedbrain_plugin_runtime/admission.py +39 -0
- package/tedbrain_plugin_runtime/bootstrap.py +108 -0
- package/tedbrain_plugin_runtime/cli.py +165 -0
- package/tedbrain_plugin_runtime/engine.py +102 -0
- package/tedbrain_plugin_runtime/executor.py +108 -0
- package/tedbrain_plugin_runtime/installer.py +400 -0
- package/tedbrain_plugin_runtime/jobs.py +199 -0
- package/tedbrain_plugin_runtime/launcher.py +120 -0
- package/tedbrain_plugin_runtime/publication.py +45 -0
- package/tedbrain_plugin_runtime/request_contract.py +226 -0
- package/tedbrain_plugin_runtime/service.py +233 -0
- package/tedbrain_plugin_runtime/ssh_workstation.py +40 -0
- package/tedbrain_plugin_runtime/worker.py +104 -0
- package/tedbrain_plugin_runtime/workstations.py +170 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Called by the online thin entry under a sealed bootstrap interpreter."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import shlex
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
from .installer import Installer, ContractError, Unavailable, atomic
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def shell_quote(value):
|
|
14
|
+
return shlex.quote(str(value))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def ps_quote(value):
|
|
18
|
+
return "'" + str(value).replace("'", "''") + "'"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def local_entry(root, origin, python, module_root):
|
|
22
|
+
"""Persist a refresh wrapper; fallback invokes the verifier, never unchecked code."""
|
|
23
|
+
shell = '''#!/bin/sh
|
|
24
|
+
set -eu
|
|
25
|
+
umask 077
|
|
26
|
+
DPV2_ROOT=@ROOT@
|
|
27
|
+
mkdir -p "$DPV2_ROOT"
|
|
28
|
+
DPV2_TMP=$(mktemp "$DPV2_ROOT/.entry-XXXXXX")
|
|
29
|
+
trap 'rm -f "$DPV2_TMP"' EXIT HUP INT TERM
|
|
30
|
+
DPV2_CURL=0
|
|
31
|
+
DPV2_STATUS=$(curl --proto '=https' -sS --connect-timeout 10 --max-time 30 -w '%{http_code}' @URL@ -o "$DPV2_TMP") || DPV2_CURL=$?
|
|
32
|
+
if [ "$DPV2_CURL:$DPV2_STATUS" = '0:200' ]; then
|
|
33
|
+
sh "$DPV2_TMP" "$@"
|
|
34
|
+
else
|
|
35
|
+
case "$DPV2_CURL:$DPV2_STATUS" in
|
|
36
|
+
5:*|6:*|7:*|18:*|28:*|52:*|55:*|56:*|0:408|0:429|0:500|0:502|0:503|0:504) ;;
|
|
37
|
+
*) printf '%s\\n' 'Online entry rejected or TLS verification failed; no cache downgrade.' >&2; exit 2 ;;
|
|
38
|
+
esac
|
|
39
|
+
printf '%s\\n' 'Warning: online entry unavailable; using locally verified plugin.' >&2
|
|
40
|
+
@PYTHON@ -E -s -B @MAIN@ --root "$DPV2_ROOT" --origin @ORIGIN@ --cached -- "$@"
|
|
41
|
+
fi
|
|
42
|
+
'''
|
|
43
|
+
values = {'ROOT': root, 'URL': origin+'/pkg/pdkadapt/cli.sh', 'PYTHON':python,
|
|
44
|
+
'MAIN':module_root/'entry.py','ORIGIN':origin}
|
|
45
|
+
for key,value in values.items():
|
|
46
|
+
shell=shell.replace('@'+key+'@',shell_quote(value))
|
|
47
|
+
atomic(root/'cli.sh',shell.encode()); (root/'cli.sh').chmod(0o700)
|
|
48
|
+
powershell = '''$ErrorActionPreference = 'Stop'
|
|
49
|
+
$PluginRoot = @ROOT@
|
|
50
|
+
$Temporary = Join-Path $PluginRoot ('.entry-' + [Guid]::NewGuid().ToString('N') + '.ps1')
|
|
51
|
+
$Fetched = $false
|
|
52
|
+
try {
|
|
53
|
+
try { Invoke-WebRequest -UseBasicParsing -MaximumRedirection 0 -Uri @URL@ -OutFile $Temporary -TimeoutSec 30 | Out-Null; $Fetched = $true }
|
|
54
|
+
catch {
|
|
55
|
+
$Response = $_.Exception.Response
|
|
56
|
+
$Transient = $false
|
|
57
|
+
if ($null -ne $Response) { $Transient = [int]$Response.StatusCode -in @(408,429,500,502,503,504) }
|
|
58
|
+
else { $Transient = [string]$_.Exception.Status -in @('ConnectFailure','NameResolutionFailure','Timeout','ConnectionClosed','ReceiveFailure','SendFailure') }
|
|
59
|
+
if (-not $Transient) { throw 'Online entry rejected or TLS verification failed; no cache downgrade.' }
|
|
60
|
+
Write-Warning 'Online entry unavailable; using locally verified plugin.'
|
|
61
|
+
}
|
|
62
|
+
if ($Fetched) { & $Temporary @args; exit $LASTEXITCODE }
|
|
63
|
+
else { & @PYTHON@ -E -s -B @MAIN@ --root $PluginRoot --origin @ORIGIN@ --cached -- @args; exit $LASTEXITCODE }
|
|
64
|
+
} finally { Remove-Item -LiteralPath $Temporary -Force -ErrorAction SilentlyContinue }
|
|
65
|
+
'''
|
|
66
|
+
values['URL']=origin+'/pkg/pdkadapt/cli.ps1'
|
|
67
|
+
for key,value in values.items():
|
|
68
|
+
powershell=powershell.replace('@'+key+'@',ps_quote(value))
|
|
69
|
+
atomic(root/'cli.ps1',powershell.encode('utf-8'))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def main(argv=None):
|
|
73
|
+
argv=list(sys.argv[1:] if argv is None else argv)
|
|
74
|
+
boundary=argv.index('--') if '--' in argv else len(argv)
|
|
75
|
+
business=argv[boundary+1:] if boundary<len(argv) else []
|
|
76
|
+
p=argparse.ArgumentParser()
|
|
77
|
+
p.add_argument('--root',type=Path,default=Path.home()/'.ted/tedbrain/plugins/pdkadapt')
|
|
78
|
+
p.add_argument('--origin',default='https://tedbrain.com')
|
|
79
|
+
p.add_argument('--cached',action='store_true')
|
|
80
|
+
p.add_argument('--test-registry',help=argparse.SUPPRESS)
|
|
81
|
+
args=p.parse_args(argv[:boundary])
|
|
82
|
+
from urllib.parse import urlsplit
|
|
83
|
+
origin=urlsplit(args.origin)
|
|
84
|
+
if origin.path not in ('','/') or origin.query or origin.fragment or origin.username or origin.password:
|
|
85
|
+
raise ContractError('origin must not include credentials, path, query or fragment')
|
|
86
|
+
origin=args.origin.rstrip('/')
|
|
87
|
+
install=Installer(args.root,local_registry=args.test_registry)
|
|
88
|
+
if args.cached:
|
|
89
|
+
result={'meta':install.cached(),'warning':'ONLINE_ENTRY_UNAVAILABLE_USING_VERIFIED_CACHE'}
|
|
90
|
+
else:
|
|
91
|
+
result=install.sync(origin+'/api/dpv2/plugins/pdkadapt/versions/recommended?target='+install.target)
|
|
92
|
+
if result['warning']:
|
|
93
|
+
print('Warning: '+result['warning'],file=sys.stderr)
|
|
94
|
+
# Capture this exact graph before another invocation can update meta.json.
|
|
95
|
+
meta=result['meta']; entries=install.entries(meta)
|
|
96
|
+
local_entry(install.root,origin,Path(sys.executable),Path(__file__).resolve().parent.parent)
|
|
97
|
+
env=dict(os.environ,DPV2_VLINK=str(entries['vlink']),DPV2_PYTHON=str(entries['python']),
|
|
98
|
+
DPV2_ORIGIN=origin,DPV2_PLUGIN_ROOT=str(install.root),
|
|
99
|
+
DPV2_RELEASE_VERSION=meta['release']['version'],
|
|
100
|
+
DPV2_SELECTION_SHA256=meta['selection_sha256'],PYTHONDONTWRITEBYTECODE='1')
|
|
101
|
+
# A user's existing Python installation cannot inject modules into this runtime.
|
|
102
|
+
for key in ('PYTHONPATH','PYTHONHOME','PYTHONSTARTUP','PYTHONUSERBASE'):
|
|
103
|
+
env.pop(key,None)
|
|
104
|
+
env['PYTHONNOUSERSITE']='1'
|
|
105
|
+
env['PATH']=str(entries['vlink'].parent)+os.pathsep+str(entries['python'].parent)+os.pathsep+env.get('PATH','')
|
|
106
|
+
# No arguments means help, never an accidental default-start from legacy CLI.
|
|
107
|
+
business=business or ['--help']
|
|
108
|
+
if install.target.startswith('win32'):
|
|
109
|
+
command=['powershell.exe','-NoProfile','-ExecutionPolicy','Bypass','-File',str(entries['cli']),*business]
|
|
110
|
+
else:
|
|
111
|
+
command=['sh',str(entries['cli']),*business]
|
|
112
|
+
return subprocess.call(command,env=env)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
if __name__=='__main__':
|
|
116
|
+
try:
|
|
117
|
+
raise SystemExit(main())
|
|
118
|
+
except (ContractError,Unavailable) as error:
|
|
119
|
+
print(json.dumps({'ok':False,'error':{'code':'PLUGIN_INSTALL_FAILED','message':str(error)}}),file=sys.stderr)
|
|
120
|
+
raise SystemExit(2)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Build npm-format immutable payloads from explicit inputs; never publish."""
|
|
2
|
+
import base64
|
|
3
|
+
import hashlib
|
|
4
|
+
import io
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import tarfile
|
|
8
|
+
from .installer import ContractError, relative, package_identity
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def pack(directory, output, package, version, registry='https://registry.npmjs.org'):
|
|
12
|
+
directory=Path(directory);output=Path(output)
|
|
13
|
+
if not directory.is_dir() or directory.is_symlink():
|
|
14
|
+
raise ContractError('explicit regular package input directory required')
|
|
15
|
+
if not package_identity(package,version):
|
|
16
|
+
raise ContractError('DPV2 npm package name required')
|
|
17
|
+
# Output cannot recursively enter its own input closure.
|
|
18
|
+
if directory.resolve() in output.resolve().parents:
|
|
19
|
+
raise ContractError('package output must be outside source directory')
|
|
20
|
+
payload={'package.json':json.dumps({'name':package,'version':version,'private':False},sort_keys=True).encode()}
|
|
21
|
+
executables=set()
|
|
22
|
+
for path in sorted(directory.rglob('*')):
|
|
23
|
+
if path.is_symlink():
|
|
24
|
+
raise ContractError('package sources must materialize symlinks before packaging')
|
|
25
|
+
if path.is_dir():continue
|
|
26
|
+
if not path.is_file():raise ContractError('package inputs must be regular files')
|
|
27
|
+
name=relative(path.relative_to(directory).as_posix())
|
|
28
|
+
if name=='package.json':raise ContractError('package.json identity is generated by the packer')
|
|
29
|
+
if name in payload:raise ContractError('duplicate package member')
|
|
30
|
+
payload[name]=path.read_bytes()
|
|
31
|
+
if path.stat().st_mode & 0o100:executables.add(name)
|
|
32
|
+
output.parent.mkdir(parents=True,exist_ok=True)
|
|
33
|
+
# Fixed tar/gzip timestamps make the artifact content reproducible.
|
|
34
|
+
import gzip
|
|
35
|
+
with output.open('wb') as stream, gzip.GzipFile(fileobj=stream,mode='wb',mtime=0,filename='') as zipped:
|
|
36
|
+
with tarfile.open(fileobj=zipped,mode='w|') as tar:
|
|
37
|
+
for name,data in sorted(payload.items()):
|
|
38
|
+
member=tarfile.TarInfo('package/'+name);member.size=len(data);member.mtime=0
|
|
39
|
+
member.mode=0o755 if name in executables else 0o644
|
|
40
|
+
tar.addfile(member,io.BytesIO(data))
|
|
41
|
+
raw=output.read_bytes()
|
|
42
|
+
leaf=package.split('/')[-1]
|
|
43
|
+
return {'package':package,'version':version,'url':registry.rstrip('/')+'/'+package+'/-/'+leaf+'-'+version+'.tgz',
|
|
44
|
+
'sha256':hashlib.sha256(raw).hexdigest(),'integrity':'sha512-'+base64.b64encode(hashlib.sha512(raw).digest()).decode(),
|
|
45
|
+
'size':len(raw),'files':{name:{'sha256':hashlib.sha256(data).hexdigest(),'size':len(data),'executable':name in executables} for name,data in payload.items()}}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
# Frozen pure CLI validation from DPV1; no MCP/runtime imports.
|
|
2
|
+
# Source SHA256: 2b08efa695c01c32fc9cb7a6a2d03aedcae0cd7b19b66372ddded30aa31d88e5
|
|
3
|
+
"""Shared PDK request inference and validation for Gateway and MCP."""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import PurePosixPath
|
|
9
|
+
from typing import Dict
|
|
10
|
+
|
|
11
|
+
PUBLIC_FIELDS = (
|
|
12
|
+
"ok",
|
|
13
|
+
"event",
|
|
14
|
+
"job_status",
|
|
15
|
+
"run_id",
|
|
16
|
+
"execution_task_id",
|
|
17
|
+
"replayed",
|
|
18
|
+
"parameters",
|
|
19
|
+
"step",
|
|
20
|
+
"phase",
|
|
21
|
+
"elapsed_seconds",
|
|
22
|
+
"accepted",
|
|
23
|
+
"extraction_progress",
|
|
24
|
+
"workflow",
|
|
25
|
+
"client_result_dir",
|
|
26
|
+
"delivery",
|
|
27
|
+
"error",
|
|
28
|
+
"pending_decision",
|
|
29
|
+
"attempt",
|
|
30
|
+
"attempts",
|
|
31
|
+
"current_attempt",
|
|
32
|
+
"from_step_plan",
|
|
33
|
+
"last_successful_delivery",
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def infer_pdk_parameters(
|
|
38
|
+
vendor_dir: str, *, alias="", foundry="", arch=""
|
|
39
|
+
) -> Dict[str, str]:
|
|
40
|
+
"""Infer adapter parameters when the model omits optional tool arguments."""
|
|
41
|
+
|
|
42
|
+
parts = [
|
|
43
|
+
part.lower()
|
|
44
|
+
for part in PurePosixPath(vendor_dir.rstrip("/")).parts
|
|
45
|
+
if part not in {"/", ""}
|
|
46
|
+
]
|
|
47
|
+
joined = "/".join(parts)
|
|
48
|
+
|
|
49
|
+
if not alias:
|
|
50
|
+
for part in parts:
|
|
51
|
+
if re.fullmatch(r"[st]\d+[a-z0-9]*", part):
|
|
52
|
+
alias = part
|
|
53
|
+
break
|
|
54
|
+
if not alias:
|
|
55
|
+
alias = re.sub(r"[^a-z0-9_.-]+", "-", parts[-1] if parts else "pdk")
|
|
56
|
+
alias = alias.strip("._-")[:64]
|
|
57
|
+
if not alias:
|
|
58
|
+
raise ValueError("无法从 vendor_dir 推断 alias,请在调用时明确指定。")
|
|
59
|
+
|
|
60
|
+
if not foundry:
|
|
61
|
+
if "smic" in joined:
|
|
62
|
+
foundry = "SMIC"
|
|
63
|
+
elif "tsmc" in joined:
|
|
64
|
+
foundry = "TSMC"
|
|
65
|
+
elif "globalfoundries" in joined or "gf180" in joined:
|
|
66
|
+
foundry = "GLOBALFOUNDRIES"
|
|
67
|
+
else:
|
|
68
|
+
raise ValueError("无法从 vendor_dir 推断 foundry,请在调用时明确指定。")
|
|
69
|
+
|
|
70
|
+
arch = arch or (
|
|
71
|
+
"finfet" if re.search(r"(^|[/_-])fin(?:fet)?([/_-]|$)", joined) else "planar"
|
|
72
|
+
)
|
|
73
|
+
return {"alias": alias, "foundry": foundry, "arch": arch}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def valid_from_steps(mode: str) -> list:
|
|
77
|
+
"""服务执行计划内的合法重跑起点(内部 step_id;11 是最终交付)。"""
|
|
78
|
+
|
|
79
|
+
planned = {1, 2, 3, 4, 5, 7, 9} if mode == "pre" else set(range(1, 10))
|
|
80
|
+
return sorted(planned)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def validate_request(request):
|
|
84
|
+
allowed = {
|
|
85
|
+
"action",
|
|
86
|
+
"vendor_dir",
|
|
87
|
+
"alias",
|
|
88
|
+
"foundry",
|
|
89
|
+
"arch",
|
|
90
|
+
"run_id",
|
|
91
|
+
"cells",
|
|
92
|
+
"mode",
|
|
93
|
+
"from_step",
|
|
94
|
+
"layer_decision",
|
|
95
|
+
"layer_rule_decision",
|
|
96
|
+
"use_client_revision",
|
|
97
|
+
"source_package",
|
|
98
|
+
}
|
|
99
|
+
if (
|
|
100
|
+
not isinstance(request, dict)
|
|
101
|
+
or set(request) - allowed
|
|
102
|
+
or any(not isinstance(value, str) for value in request.values())
|
|
103
|
+
):
|
|
104
|
+
raise ValueError("只接受工艺适配的字符串业务参数。")
|
|
105
|
+
action = request.get("action", "start")
|
|
106
|
+
source_package = request.get("source_package", "")
|
|
107
|
+
if source_package:
|
|
108
|
+
if action != "start":
|
|
109
|
+
raise ValueError("source_package 仅供 start 使用。")
|
|
110
|
+
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}", source_package):
|
|
111
|
+
raise ValueError(
|
|
112
|
+
"source_package 必须是候选 PDK 包目录名(字母数字开头,"
|
|
113
|
+
"可含 . _ -,最长128)。"
|
|
114
|
+
)
|
|
115
|
+
layer_rule_decision = request.get("layer_rule_decision", "")
|
|
116
|
+
if layer_rule_decision:
|
|
117
|
+
if action != "resume" or len(layer_rule_decision) > 16384:
|
|
118
|
+
raise ValueError("layer_rule_decision 仅供 resume 使用,且不超过16KB")
|
|
119
|
+
decision = json.loads(layer_rule_decision)
|
|
120
|
+
if (
|
|
121
|
+
not isinstance(decision, dict)
|
|
122
|
+
or set(decision) != {"decision_id", "values"}
|
|
123
|
+
or not isinstance(decision["decision_id"], str)
|
|
124
|
+
or not re.fullmatch(r"[a-f0-9]{64}", decision["decision_id"])
|
|
125
|
+
or not isinstance(decision["values"], dict)
|
|
126
|
+
or not decision["values"]
|
|
127
|
+
):
|
|
128
|
+
raise ValueError("layer_rule_decision 必须包含有效 decision_id 和 values")
|
|
129
|
+
layer_decision = request.get("layer_decision", "")
|
|
130
|
+
if layer_decision:
|
|
131
|
+
if action != "resume" or len(layer_decision) > 16384:
|
|
132
|
+
raise ValueError("layer_decision 只能用于 resume,且不能超过 16KB。")
|
|
133
|
+
decision = json.loads(layer_decision)
|
|
134
|
+
if (
|
|
135
|
+
not isinstance(decision, dict)
|
|
136
|
+
or set(decision) != {"decision_id", "mapping"}
|
|
137
|
+
or not isinstance(decision["decision_id"], str)
|
|
138
|
+
or not re.fullmatch(r"[a-f0-9]{64}", decision["decision_id"])
|
|
139
|
+
or not isinstance(decision["mapping"], dict)
|
|
140
|
+
or not decision["mapping"]
|
|
141
|
+
or any(
|
|
142
|
+
not isinstance(k, str) or not isinstance(v, str)
|
|
143
|
+
for k, v in decision["mapping"].items()
|
|
144
|
+
)
|
|
145
|
+
):
|
|
146
|
+
raise ValueError("layer_decision 必须包含有效 decision_id 和 mapping。")
|
|
147
|
+
mode = request.get("mode", "")
|
|
148
|
+
mode = "pre" if mode == "pcell" else mode
|
|
149
|
+
if mode and mode not in {"pre", "full"}:
|
|
150
|
+
raise ValueError("mode 必须是 pre 或 full。")
|
|
151
|
+
if not mode:
|
|
152
|
+
# 新适配统一执行 full;check/status 省略 mode 仍按 pre 复用历史交付。
|
|
153
|
+
mode = "full" if action in {"start", "resume"} else "pre"
|
|
154
|
+
if action == "resume" and mode != "full":
|
|
155
|
+
raise ValueError(
|
|
156
|
+
"新适配统一执行 full:resume 不能以 pre 续跑。请以 action=start、mode=full"
|
|
157
|
+
"(或省略 mode)换新别名重新适配;已有 pre 交付仍可用 action=check、"
|
|
158
|
+
"mode=pre 复用。"
|
|
159
|
+
)
|
|
160
|
+
if action not in {"start", "status", "resume", "check"}:
|
|
161
|
+
raise ValueError("action 必须是 check、start、status 或 resume。")
|
|
162
|
+
revision = request.get("use_client_revision", "")
|
|
163
|
+
if revision and (action != "check" or not re.fullmatch(r"[0-9a-f]{64}", revision)):
|
|
164
|
+
raise ValueError(
|
|
165
|
+
"use_client_revision 仅供 check 使用,必须是用户确认的当前 SHA-256。"
|
|
166
|
+
)
|
|
167
|
+
vendor = request.get("vendor_dir", "")
|
|
168
|
+
if action not in {"status", "check"} and (
|
|
169
|
+
not os.path.isabs(vendor) or "\x00" in vendor
|
|
170
|
+
):
|
|
171
|
+
raise ValueError("vendor_dir 必须是客户端厂商 PDK 的绝对路径。")
|
|
172
|
+
values = {key: request.get(key, "") for key in ("alias", "foundry", "arch")}
|
|
173
|
+
if action not in {"status", "check"} and not all(values.values()):
|
|
174
|
+
inferred = infer_pdk_parameters(vendor, **values)
|
|
175
|
+
values = {key: value or inferred[key] for key, value in values.items()}
|
|
176
|
+
for key, value in (
|
|
177
|
+
("alias", values["alias"]),
|
|
178
|
+
("run_id", request.get("run_id", "")),
|
|
179
|
+
):
|
|
180
|
+
if value and not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", value):
|
|
181
|
+
raise ValueError(f"{key} 格式无效。")
|
|
182
|
+
if action in {"status", "resume"} and (
|
|
183
|
+
not values["alias"] or not request.get("run_id")
|
|
184
|
+
):
|
|
185
|
+
raise ValueError("status/resume 必须指定 alias 和 run_id。")
|
|
186
|
+
if action == "check" and not values["alias"]:
|
|
187
|
+
raise ValueError("check 必须指定工艺 alias。")
|
|
188
|
+
if action == "check" and vendor and (not os.path.isabs(vendor) or "\x00" in vendor):
|
|
189
|
+
raise ValueError("vendor_dir 必须是客户端厂商 PDK 的绝对路径。")
|
|
190
|
+
if action not in {"status", "check"} and values["arch"] not in {"planar", "finfet"}:
|
|
191
|
+
raise ValueError("arch 必须是 planar 或 finfet。")
|
|
192
|
+
cells = request.get("cells", "")
|
|
193
|
+
if cells and any(
|
|
194
|
+
not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", cell)
|
|
195
|
+
for cell in cells.split(",")
|
|
196
|
+
):
|
|
197
|
+
raise ValueError("cells 必须是逗号分隔的 cell 名称。")
|
|
198
|
+
from_step = request.get("from_step", "")
|
|
199
|
+
if from_step:
|
|
200
|
+
# 指定起点重跑只面向 resume;start/status/check 携带时直接拒绝,
|
|
201
|
+
# 未传时不改变旧请求与幂等语义。
|
|
202
|
+
if action != "resume":
|
|
203
|
+
raise ValueError("from_step 仅供 resume 使用。")
|
|
204
|
+
if not re.fullmatch(r"[1-9][0-9]{0,2}", from_step) or not (
|
|
205
|
+
1 <= int(from_step) <= 10
|
|
206
|
+
):
|
|
207
|
+
raise ValueError("from_step 必须是 1~10 的内部步骤编号。")
|
|
208
|
+
planned = valid_from_steps(mode)
|
|
209
|
+
if int(from_step) not in planned:
|
|
210
|
+
raise ValueError(
|
|
211
|
+
f"from_step 必须属于该模式的执行计划 {planned};"
|
|
212
|
+
"10(适配报告)与 11(最终交付)不作为重跑起点。"
|
|
213
|
+
)
|
|
214
|
+
return {
|
|
215
|
+
**values,
|
|
216
|
+
"vendor_dir": vendor,
|
|
217
|
+
"action": action,
|
|
218
|
+
"run_id": request.get("run_id", ""),
|
|
219
|
+
"cells": cells,
|
|
220
|
+
"mode": mode,
|
|
221
|
+
**({"from_step": from_step} if from_step else {}),
|
|
222
|
+
**({"layer_decision": layer_decision} if layer_decision else {}),
|
|
223
|
+
**({"layer_rule_decision": layer_rule_decision} if layer_rule_decision else {}),
|
|
224
|
+
**({"use_client_revision": revision} if revision else {}),
|
|
225
|
+
**({"source_package": source_package} if source_package else {}),
|
|
226
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Independent DPV2 HTTP control plane. No MCP or DPV1 process dependency.
|
|
2
|
+
|
|
3
|
+
The service serves small metadata/entry files, never client runtime archives.
|
|
4
|
+
Business submission requires a registered workstation and a fixed worker release.
|
|
5
|
+
"""
|
|
6
|
+
import argparse
|
|
7
|
+
import hashlib
|
|
8
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import re
|
|
14
|
+
import secrets
|
|
15
|
+
import sqlite3
|
|
16
|
+
import time
|
|
17
|
+
import urllib.error
|
|
18
|
+
import urllib.parse
|
|
19
|
+
import urllib.request
|
|
20
|
+
from .installer import ContractError, NoRedirect, canonical, endpoint, loads, manifest, TARGETS,tls_context
|
|
21
|
+
from .jobs import Jobs, Conflict, NotFound
|
|
22
|
+
from .workstations import Workstations, EnrollmentReader, Unavailable
|
|
23
|
+
|
|
24
|
+
PREFIX='/api/dpv2/pdkadapt/v1'
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Denied(ContractError):pass
|
|
28
|
+
class DependencyUnavailable(ContractError):pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Auth:
|
|
32
|
+
def __init__(self,path,account):
|
|
33
|
+
self.path=Path(path);self.account=account
|
|
34
|
+
self.path.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
35
|
+
if self.path.is_symlink():raise ContractError('auth database symlink refused')
|
|
36
|
+
with sqlite3.connect(self.path) as db:
|
|
37
|
+
db.execute('CREATE TABLE IF NOT EXISTS tokens(digest TEXT PRIMARY KEY,subject TEXT NOT NULL,audience TEXT NOT NULL,expires REAL NOT NULL)')
|
|
38
|
+
self.path.chmod(0o600)
|
|
39
|
+
|
|
40
|
+
def exchange(self,credential):
|
|
41
|
+
if not isinstance(credential,str) or not 1<=len(credential)<=4096 or any(ord(c)<32 for c in credential):
|
|
42
|
+
raise Denied('invalid account credential')
|
|
43
|
+
config=self.account
|
|
44
|
+
endpoint(config['endpoint'],local_registry=config.get('test_registry'))
|
|
45
|
+
secret=Path(config['secret_file'])
|
|
46
|
+
if not secret.is_file() or secret.is_symlink():raise DependencyUnavailable('account service credential unavailable')
|
|
47
|
+
if os.name!='nt' and secret.stat().st_mode & 0o077:raise DependencyUnavailable('account credential must be private')
|
|
48
|
+
body=canonical({'appid':config['appid'],'app_secret':secret.read_text().strip(),'code':credential})
|
|
49
|
+
request=urllib.request.Request(config['endpoint'],data=body,headers={'Content-Type':'application/json'},method='POST')
|
|
50
|
+
try:
|
|
51
|
+
with urllib.request.build_opener(NoRedirect(),urllib.request.HTTPSHandler(context=tls_context())).open(request,timeout=10) as response:
|
|
52
|
+
raw=response.read(16385)
|
|
53
|
+
if response.status!=200 or len(raw)>16384:raise DependencyUnavailable('account service response invalid')
|
|
54
|
+
except (OSError,urllib.error.URLError):
|
|
55
|
+
raise DependencyUnavailable('account service unavailable') from None
|
|
56
|
+
value=loads(raw)
|
|
57
|
+
if not isinstance(value,dict) or value.get('valid') is not True:raise Denied('account credential rejected')
|
|
58
|
+
identifiers=[('user',value.get('user_id')),('invite',value.get('invite_id'))]
|
|
59
|
+
present=[(kind,value) for kind,value in identifiers if value is not None]
|
|
60
|
+
if len(present)!=1 or not isinstance(present[0][1],str) or not re.fullmatch('[a-fA-F0-9]{24}',present[0][1]):
|
|
61
|
+
raise DependencyUnavailable('account service identity invalid')
|
|
62
|
+
kind,identifier=present[0];subject='tedbrain-'+kind+'-'+identifier.lower()
|
|
63
|
+
token='dpv2_'+secrets.token_urlsafe(32);expires=time.time()+86400
|
|
64
|
+
with sqlite3.connect(self.path) as db:
|
|
65
|
+
db.execute('DELETE FROM tokens WHERE expires<?',(time.time(),))
|
|
66
|
+
db.execute('INSERT INTO tokens VALUES(?,?,?,?)',(hashlib.sha256(token.encode()).hexdigest(),subject,'dpv2',expires))
|
|
67
|
+
return {'access_token':token,'token_type':'Bearer','audience':'dpv2','expires_at':expires,'subject':subject}
|
|
68
|
+
|
|
69
|
+
def subject(self,header):
|
|
70
|
+
if not isinstance(header,str) or not header.startswith('Bearer dpv2_') or len(header)>8192:
|
|
71
|
+
raise Denied('DPV2 authentication required')
|
|
72
|
+
digest=hashlib.sha256(header[7:].encode()).hexdigest()
|
|
73
|
+
with sqlite3.connect(self.path) as db:
|
|
74
|
+
row=db.execute('SELECT subject FROM tokens WHERE digest=? AND audience=? AND expires>?',(digest,'dpv2',time.time())).fetchone()
|
|
75
|
+
if row is None:raise Denied('DPV2 credential expired or invalid')
|
|
76
|
+
return row[0]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Application:
|
|
80
|
+
def __init__(self,config,*,candidate=False):
|
|
81
|
+
self.config=config
|
|
82
|
+
self.candidate=candidate
|
|
83
|
+
self.state=Path(config['state_root']).absolute()
|
|
84
|
+
self.state.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
85
|
+
self.jobs=Jobs(self.state/'jobs.sqlite3')
|
|
86
|
+
self.workstations=Workstations(self.state/'workstations.sqlite3')
|
|
87
|
+
self.auth=Auth(self.state/'auth.sqlite3',config['account'])
|
|
88
|
+
self.public=Path(config['public_root']).resolve()
|
|
89
|
+
self.releases=Path(config['releases_root']).resolve()
|
|
90
|
+
|
|
91
|
+
def version(self,target):
|
|
92
|
+
if target not in TARGETS:raise ContractError('unsupported client target')
|
|
93
|
+
path=self.releases/(target+'.json')
|
|
94
|
+
if not path.is_file():raise DependencyUnavailable('client target release not available')
|
|
95
|
+
raw=path.read_bytes()
|
|
96
|
+
if len(raw)>4*1024*1024:raise ContractError('release metadata exceeds size limit')
|
|
97
|
+
return manifest(loads(raw),'pdkadapt',target,self.config.get('test_registry'))
|
|
98
|
+
|
|
99
|
+
def workstation(self,subject,identifier):
|
|
100
|
+
return self.workstations.get(subject,identifier)
|
|
101
|
+
|
|
102
|
+
def worker(self):
|
|
103
|
+
if self.candidate:
|
|
104
|
+
release=self.config.get('candidate_worker')
|
|
105
|
+
if not isinstance(release,dict) or not release.get('version'):
|
|
106
|
+
raise DependencyUnavailable('local candidate worker unavailable')
|
|
107
|
+
return release
|
|
108
|
+
path=self.state/'worker-release.json'
|
|
109
|
+
if not path.is_file():raise DependencyUnavailable('pdkadapt worker release is not admitted')
|
|
110
|
+
release=loads(path.read_bytes())
|
|
111
|
+
from .admission import validate
|
|
112
|
+
try:return validate(self.config,release)
|
|
113
|
+
except (ContractError,KeyError,OSError,TypeError):
|
|
114
|
+
raise DependencyUnavailable('pdkadapt worker release evidence is invalid') from None
|
|
115
|
+
|
|
116
|
+
def dispatch(self,method,path,headers,body):
|
|
117
|
+
parsed=urllib.parse.urlsplit(path);route=parsed.path;query=urllib.parse.parse_qs(parsed.query)
|
|
118
|
+
if method=='GET' and route=='/healthz':return 200,{'ok':True,'service':'dpv2-pdkadapt'}
|
|
119
|
+
if method=='GET' and route=='/api/dpv2/plugins/pdkadapt/versions/recommended':
|
|
120
|
+
targets=query.get('target',[])
|
|
121
|
+
if len(targets)!=1:raise ContractError('one target required')
|
|
122
|
+
return 200,self.version(targets[0])
|
|
123
|
+
static={'/pkg/pdkadapt/cli.sh':('pkg/pdkadapt/cli.sh','text/x-shellscript'),
|
|
124
|
+
'/pkg/pdkadapt/cli.ps1':('pkg/pdkadapt/cli.ps1','text/plain'),
|
|
125
|
+
'/dpv2/guide.md':('guide.md','text/markdown'),
|
|
126
|
+
'/dpv2/skills/tedbrain/SKILL.md':('skills/tedbrain/SKILL.md','text/markdown')}
|
|
127
|
+
if method=='GET' and route in static:
|
|
128
|
+
relative,kind=static[route];file=self.public/relative
|
|
129
|
+
if not file.is_file():raise NotFound('public entry not available')
|
|
130
|
+
if file.is_symlink() or file.stat().st_size>65536:raise ContractError('public entry must be a thin regular file')
|
|
131
|
+
return 200,(file.read_bytes(),kind)
|
|
132
|
+
if method=='POST' and route=='/api/dpv2/auth/sessions':
|
|
133
|
+
if not isinstance(body,dict) or set(body)!={'credential'}:raise ContractError('credential required')
|
|
134
|
+
return 200,self.auth.exchange(body['credential'])
|
|
135
|
+
subject=self.auth.subject(headers.get('Authorization'))
|
|
136
|
+
if route==PREFIX+'/workstations' and method=='GET':
|
|
137
|
+
return 200,{'workstations':self.workstations.list(subject)}
|
|
138
|
+
if route==PREFIX+'/workstation-challenges' and method=='POST':
|
|
139
|
+
if not isinstance(body,dict) or set(body)!={'label'}:raise ContractError('workstation label required')
|
|
140
|
+
key=headers.get('Idempotency-Key')
|
|
141
|
+
if not re.fullmatch('[A-Za-z0-9._-]{1,128}',key or ''):raise ContractError('Idempotency-Key required')
|
|
142
|
+
return 201,self.workstations.challenge(subject,body['label'],key)
|
|
143
|
+
enrollment=re.fullmatch(re.escape(PREFIX)+r'/workstation-challenges/([a-f0-9]{32})/confirmation',route)
|
|
144
|
+
if enrollment and method=='POST':
|
|
145
|
+
if not isinstance(body,dict) or set(body)!={'connection_id'}:raise ContractError('workstation connection required')
|
|
146
|
+
config=self.config.get('transport')
|
|
147
|
+
if not config:raise DependencyUnavailable('DPV2 workstation transport unavailable')
|
|
148
|
+
return 200,self.workstations.confirm(subject,enrollment.group(1),body['connection_id'],EnrollmentReader(config))
|
|
149
|
+
if method=='GET' and route==PREFIX+'/capabilities':
|
|
150
|
+
try:worker=self.worker()
|
|
151
|
+
except DependencyUnavailable:worker=None
|
|
152
|
+
return 200,{'plugin':'pdkadapt','protocol_version':1,'worker_ready':worker is not None,
|
|
153
|
+
'workstation_proxy':self.config.get('transport',{}).get('public_proxy_url'),
|
|
154
|
+
'deployment_stage':'local-candidate' if self.candidate else 'release',
|
|
155
|
+
'actions':['start','status','resume','cancel'] if worker else ['status'],
|
|
156
|
+
'default_start':'async','plugin_version':worker['version'] if worker else None}
|
|
157
|
+
if method=='POST' and route==PREFIX+'/jobs':
|
|
158
|
+
if not isinstance(body,dict) or set(body)!={'workstation_id','request'}:raise ContractError('workstation_id and request required')
|
|
159
|
+
self.workstation(subject,body['workstation_id']);worker=self.worker()
|
|
160
|
+
from .request_contract import validate_request
|
|
161
|
+
request=validate_request(body['request'])
|
|
162
|
+
if request['action']!='start' or request['mode']!='full':raise ContractError('new jobs require full start')
|
|
163
|
+
value=self.jobs.submit(subject,body['workstation_id'],request,headers.get('Idempotency-Key'),worker['version'])
|
|
164
|
+
return 202,value
|
|
165
|
+
lookup=re.fullmatch(re.escape(PREFIX)+r'/requests/([A-Za-z0-9._-]{1,128})',route)
|
|
166
|
+
if method=='GET' and lookup:return 200,self.jobs.lookup(subject,lookup.group(1))
|
|
167
|
+
match=re.fullmatch(re.escape(PREFIX)+r'/jobs/([a-f0-9]{32})(?:/(events|resumptions|cancellations|artifacts))?',route)
|
|
168
|
+
if match:
|
|
169
|
+
job,action=match.groups();current=self.jobs.get(subject,job)
|
|
170
|
+
if method=='GET' and action is None:return 200,current
|
|
171
|
+
if method=='GET' and action=='events':
|
|
172
|
+
try:after=int(query.get('after',['0'])[0])
|
|
173
|
+
except ValueError:raise ContractError('invalid event cursor') from None
|
|
174
|
+
return 200,{'events':self.jobs.events(subject,job,after)}
|
|
175
|
+
if method=='GET' and action=='artifacts':
|
|
176
|
+
return 200,{'delivery':(current['result'] or {}).get('delivery'),'job_status':current['job_status']}
|
|
177
|
+
if method=='POST' and action=='cancellations':
|
|
178
|
+
if body!={}:raise ContractError('empty cancellation body required')
|
|
179
|
+
return 202,self.jobs.cancel(subject,job,headers.get('Idempotency-Key'))
|
|
180
|
+
if method=='POST' and action=='resumptions':
|
|
181
|
+
worker=self.worker()
|
|
182
|
+
if not isinstance(body,dict) or set(body)!={'request'}:raise ContractError('resume request required')
|
|
183
|
+
from .request_contract import validate_request
|
|
184
|
+
request=validate_request(body['request'])
|
|
185
|
+
if request['action']!='resume' or request['run_id']!=job:raise ContractError('resume must identify original run')
|
|
186
|
+
self.workstation(subject,current['workstation_id'])
|
|
187
|
+
return 202,self.jobs.submit(subject,current['workstation_id'],request,headers.get('Idempotency-Key'),worker['version'],
|
|
188
|
+
resume=job,compatible=worker.get('checkpoint_schemas',[]))
|
|
189
|
+
raise NotFound('API route not found')
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def server(config,host='127.0.0.1',port=0,*,candidate=False):
|
|
193
|
+
if candidate and (host!='127.0.0.1' or not (config.get('test_registry') or config.get('account',{}).get('test_registry'))):
|
|
194
|
+
raise ContractError('candidate worker requires an explicit isolated loopback test')
|
|
195
|
+
app=Application(config,candidate=candidate)
|
|
196
|
+
class Handler(BaseHTTPRequestHandler):
|
|
197
|
+
def handle_request(self):
|
|
198
|
+
try:
|
|
199
|
+
if self.headers.get('Transfer-Encoding'):raise ContractError('chunked request bodies are not supported')
|
|
200
|
+
length=int(self.headers.get('Content-Length','0'))
|
|
201
|
+
if not 0<=length<=65536:raise ContractError('request body too large')
|
|
202
|
+
raw=self.rfile.read(length)
|
|
203
|
+
if len(raw)!=length:raise ContractError('request body incomplete')
|
|
204
|
+
body=loads(raw) if raw else None
|
|
205
|
+
status,value=app.dispatch(self.command,self.path,self.headers,body)
|
|
206
|
+
except Denied as error:status,value=401,{'error':{'code':'AUTH_REQUIRED','message':str(error)}}
|
|
207
|
+
except NotFound as error:status,value=404,{'error':{'code':'NOT_FOUND','message':str(error)}}
|
|
208
|
+
except Conflict as error:status,value=409,{'error':{'code':'CONFLICT','message':str(error)}}
|
|
209
|
+
except (DependencyUnavailable,Unavailable) as error:status,value=503,{'error':{'code':'DEPENDENCY_UNAVAILABLE','message':str(error)}}
|
|
210
|
+
except (ContractError,ValueError,TypeError,KeyError) as error:status,value=400,{'error':{'code':'INVALID_REQUEST','message':'Invalid request or configuration'}}
|
|
211
|
+
except Exception:status,value=500,{'error':{'code':'INTERNAL_ERROR','message':'Request failed; query the original request before retrying'}}
|
|
212
|
+
if isinstance(value,tuple):payload,kind=value
|
|
213
|
+
else:payload,kind=canonical(value),'application/json'
|
|
214
|
+
self.send_response(status);self.send_header('Content-Type',kind);self.send_header('Content-Length',str(len(payload)))
|
|
215
|
+
self.send_header('Cache-Control','no-store');self.end_headers()
|
|
216
|
+
try:self.wfile.write(payload)
|
|
217
|
+
except (BrokenPipeError,ConnectionResetError):pass
|
|
218
|
+
def setup(self):
|
|
219
|
+
super().setup();self.connection.settimeout(30)
|
|
220
|
+
do_GET=handle_request;do_POST=handle_request
|
|
221
|
+
def log_message(self,*args):pass # Never put credential-bearing requests into access logs.
|
|
222
|
+
http=ThreadingHTTPServer((host,port),Handler);http.app=app
|
|
223
|
+
return http
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def main(argv=None):
|
|
227
|
+
p=argparse.ArgumentParser();p.add_argument('--config',type=Path,required=True);p.add_argument('--host',default='127.0.0.1');p.add_argument('--port',type=int,default=0)
|
|
228
|
+
args=p.parse_args(argv);http=server(loads(args.config.read_bytes()),args.host,args.port)
|
|
229
|
+
print(json.dumps({'service':'dpv2-pdkadapt','listen':list(http.server_address)}),flush=True)
|
|
230
|
+
try:http.serve_forever()
|
|
231
|
+
finally:http.server_close()
|
|
232
|
+
|
|
233
|
+
if __name__=='__main__':main()
|