@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
package/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# DPV2 pdkadapt 开发候选
|
|
2
|
+
|
|
3
|
+
这是独立 Python distribution,当前提供安装器、REST 控制面和客户端候选。源码与 DPV1 同仓,运行时不导入旧 cli/MCP;没有改动 DPV1 的入口、服务器或客户端。
|
|
4
|
+
|
|
5
|
+
**尚未具备完整适配能力。** 真实工作站绑定、独立 SDK/EDA worker、旧 check/source-* 动作和四平台实际验收仍属 I01618。不要手工写 admitted=true 绕过未完成的 worker 准入。未配置准入时,业务提交明确返回 503;健康检查通过不表示可执行适配。
|
|
6
|
+
|
|
7
|
+
## 本地安装与验证
|
|
8
|
+
|
|
9
|
+
本 distribution 仅使用 Python 3.9+ 标准库。测试从产品仓执行:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
PYTHONDONTWRITEBYTECODE=1 TED_EDA_MODE=LOCAL python3 -m pytest tests/test_dpv2*.py -q
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`tools/verify_dpv2_npm.py --help` 提供可复现的 Linux npm 实际安装验收:必须指定新 prefix、协调仓、已有 Verdaccio、固定 Python 组件归档及其 SHA512、实际 vlink 二进制。只对新建的 loopback registry publish/view/download,保留收据并停止本轮服务;不向公共 npm 发布。测试实际私有解释器、runtime cli.sh、vlink REST、热启动与离线校验缓存,不包含 EDA 或 Win/Mac 实机验证。
|
|
16
|
+
|
|
17
|
+
服务使用 `python -m tedbrain_plugin_runtime.service --config FILE`,须由该 distribution 的环境运行。配置包括独立 state_root/public_root/releases_root 和账号验证 endpoint/appid/secret_file。账号 secret 必须是私有文件,不能使用现有 DPV1 token;服务签发独立 audience=dpv2 的 token。生产 TLS/资源配方和部署命令尚未交付。开发测试使用临时 loopback 和模拟账号验证源。
|
|
18
|
+
|
|
19
|
+
## 安装和任务合同
|
|
20
|
+
|
|
21
|
+
- 私有目录固定为 `~/.ted/tedbrain/plugins/pdkadapt/`;meta.json 原子选择不可变 components,不修改全局 vlink/Python。
|
|
22
|
+
- 每次本地入口获取线上薄脚本、版本 API;仅下载变化组件,核验 npm SHA512/SHA256 及完整文件清单;归档只来自 npm。
|
|
23
|
+
- 网络暂不可用可使用完整校验缓存;认证拒绝、重定向、TLS 校验或内容校验失败不降级。首次无缓存失败。
|
|
24
|
+
- sh/PowerShell 生成器要求全部四目标的固定 bootstrap 元数据。当前没有四平台生产产物,因此未生成可公开的线上安装入口。
|
|
25
|
+
- 变更请求通过私有 vlink REST 传输,先记录 request ID,未知结果查询原请求,不自动重放。
|
|
26
|
+
- SQLite 保留 job/attempt/幂等键/事件。运行中版本固定;恢复必须确认旧执行停止、检查点兼容且原工艺范围一致。
|
|
27
|
+
- guide.md 和 tedbrain skill 是发布候选文档,不代表其目标公网 URL 已可用。
|
|
28
|
+
|
|
29
|
+
公开 runtime、服务器独立部署和真实 full 适配必须另取实际证据。发布授权边界以项目规则为准。
|
|
30
|
+
|
package/entry.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Verified bootstrap entry, invoked with the bundled Python and -B."""
|
|
2
|
+
# Windows embedded Python and isolated interpreters omit the script directory.
|
|
3
|
+
# Load only this verified, immutable plugin package beside the entry point.
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
7
|
+
from tedbrain_plugin_runtime.launcher import main
|
|
8
|
+
from tedbrain_plugin_runtime.installer import ContractError, Unavailable
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
raise SystemExit(main())
|
|
14
|
+
except (ContractError, Unavailable) as error:
|
|
15
|
+
print(json.dumps({'ok': False, 'error': {'code': 'PLUGIN_INSTALL_FAILED', 'message': str(error)}}), file=sys.stderr)
|
|
16
|
+
raise SystemExit(2)
|
package/package.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.1.r1"}
|
package/plugin_cli.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Windows embedded Python and isolated interpreters omit the script directory.
|
|
2
|
+
# Load only this verified, immutable plugin package beside the entry point.
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
6
|
+
from tedbrain_plugin_runtime.cli import main
|
|
7
|
+
from tedbrain_plugin_runtime.installer import ContractError
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
try:
|
|
11
|
+
raise SystemExit(main())
|
|
12
|
+
except ContractError as error:
|
|
13
|
+
print(json.dumps({'ok':False,'error':{'code':'PLUGIN_REQUEST_FAILED','message':str(error)}}),file=sys.stderr)
|
|
14
|
+
raise SystemExit(2)
|
package/runtime/cli.ps1
ADDED
package/runtime/cli.sh
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Bind production admission to the tested server and client release inputs."""
|
|
2
|
+
import hashlib
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import re
|
|
5
|
+
from .installer import ContractError,loads
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def read(path,expected):
|
|
9
|
+
path=Path(path)
|
|
10
|
+
if (not re.fullmatch('[a-f0-9]{64}',expected or '') or path.is_symlink()
|
|
11
|
+
or not path.is_file() or path.stat().st_size>16*1024*1024):
|
|
12
|
+
raise ContractError('release evidence unavailable')
|
|
13
|
+
raw=path.read_bytes()
|
|
14
|
+
if hashlib.sha256(raw).hexdigest()!=expected:raise ContractError('release evidence changed')
|
|
15
|
+
return loads(raw)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def validate(config,release):
|
|
19
|
+
if release.get('schema')!=1 or release.get('kind')!='dpv2-worker-admission':
|
|
20
|
+
raise ContractError('fixed worker admission required')
|
|
21
|
+
root=Path(config['state_root'])/'admissions'
|
|
22
|
+
receipt=read(root/(release['receipt_sha256']+'.json'),release['receipt_sha256'])
|
|
23
|
+
build=read(Path(config['server_release_root'])/'server-build.json',receipt['server_build_sha256'])
|
|
24
|
+
if (build.get('kind')!='dpv2-pdkadapt-server' or build.get('version')!=release['version']
|
|
25
|
+
or build.get('candidate')!=receipt.get('candidate')):
|
|
26
|
+
raise ContractError('admission server identity mismatch')
|
|
27
|
+
selection=Path(config['releases_root'])/'linux-x64.json'
|
|
28
|
+
read(selection,receipt['selection_sha256'])
|
|
29
|
+
job=receipt.get('job',{});result=job.get('result') or {};delivery=result.get('delivery') or {}
|
|
30
|
+
if (receipt.get('eda_executed') is not True or receipt.get('server_build_verified') is not True
|
|
31
|
+
or job.get('plugin_version')!=release['version'] or job.get('job_status')!='SUCCEEDED'
|
|
32
|
+
or job.get('remote_stop_confirmed') is not True or result.get('ok') is not True
|
|
33
|
+
or result.get('job_status')!='COMPLETED' or delivery.get('status')!='INSTALLED'
|
|
34
|
+
or type(delivery.get('files')) is not int or delivery['files']<=0
|
|
35
|
+
or not re.fullmatch('[a-f0-9]{64}',delivery.get('tree_sha256',''))):
|
|
36
|
+
raise ContractError('real fixed-release EDA acceptance required')
|
|
37
|
+
if release.get('checkpoint_schemas')!=['dpv2-pdk-session-1']:
|
|
38
|
+
raise ContractError('unsupported admitted checkpoint schema')
|
|
39
|
+
return release
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Render small public installers from exact, reviewed npm bootstrap identities."""
|
|
2
|
+
from .installer import ContractError, TARGETS, SHA, endpoint, relative
|
|
3
|
+
from .launcher import shell_quote, ps_quote
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def validate(releases):
|
|
7
|
+
if set(releases) != TARGETS:
|
|
8
|
+
raise ContractError('all four client targets required for public bootstrap')
|
|
9
|
+
for target,item in releases.items():
|
|
10
|
+
if set(item) != {'url','sha256','python','entry'} or not SHA.fullmatch(item['sha256']):
|
|
11
|
+
raise ContractError('fixed bootstrap artifact required')
|
|
12
|
+
endpoint(item['url'],registry=True)
|
|
13
|
+
relative(item['python']);relative(item['entry'])
|
|
14
|
+
return releases
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def render_sh(releases, origin='https://tedbrain.com'):
|
|
18
|
+
validate(releases); endpoint(origin)
|
|
19
|
+
cases=[]
|
|
20
|
+
for target in ('linux-x64','darwin-x64','darwin-arm64'):
|
|
21
|
+
item=releases[target]
|
|
22
|
+
cases.append(' '+target+') '+ '; '.join(key+'='+shell_quote(value) for key,value in
|
|
23
|
+
[('DPV2_URL',item['url']),('DPV2_SHA',item['sha256']),('DPV2_PY',item['python']),('DPV2_ENTRY',item['entry'])])+' ;;')
|
|
24
|
+
script='''#!/bin/sh
|
|
25
|
+
set -eu
|
|
26
|
+
umask 077
|
|
27
|
+
DPV2_ROOT="$HOME/.ted/tedbrain/plugins/pdkadapt"
|
|
28
|
+
case "$(uname -s):$(uname -m)" in
|
|
29
|
+
Linux:x86_64) DPV2_TARGET=linux-x64 ;;
|
|
30
|
+
Darwin:x86_64) DPV2_TARGET=darwin-x64 ;;
|
|
31
|
+
Darwin:arm64) DPV2_TARGET=darwin-arm64 ;;
|
|
32
|
+
*) printf '%s\\n' 'Unsupported platform. Windows: use cli.ps1.' >&2; exit 2 ;;
|
|
33
|
+
esac
|
|
34
|
+
case "$DPV2_TARGET" in
|
|
35
|
+
@CASES@
|
|
36
|
+
esac
|
|
37
|
+
DPV2_BOOT="$DPV2_ROOT/bootstrap/$DPV2_SHA"
|
|
38
|
+
if [ ! -f "$DPV2_BOOT/package/$DPV2_PY" ]; then
|
|
39
|
+
mkdir -p "$DPV2_ROOT/bootstrap"
|
|
40
|
+
DPV2_TEMP=$(mktemp -d "$DPV2_ROOT/bootstrap/.download-XXXXXX")
|
|
41
|
+
trap 'rm -rf "$DPV2_TEMP"' EXIT HUP INT TERM
|
|
42
|
+
curl --proto '=https' --proto-redir '=https' -fsS --connect-timeout 10 --max-time 600 "$DPV2_URL" -o "$DPV2_TEMP/bootstrap.tgz"
|
|
43
|
+
if command -v sha256sum >/dev/null 2>&1; then
|
|
44
|
+
DPV2_ACTUAL=$(sha256sum "$DPV2_TEMP/bootstrap.tgz" | cut -d ' ' -f 1)
|
|
45
|
+
else
|
|
46
|
+
DPV2_ACTUAL=$(shasum -a 256 "$DPV2_TEMP/bootstrap.tgz" | cut -d ' ' -f 1)
|
|
47
|
+
fi
|
|
48
|
+
[ "$DPV2_ACTUAL" = "$DPV2_SHA" ] || { printf '%s\\n' 'Bootstrap integrity mismatch' >&2; exit 2; }
|
|
49
|
+
mkdir "$DPV2_TEMP/extracted"
|
|
50
|
+
tar -xzf "$DPV2_TEMP/bootstrap.tgz" -C "$DPV2_TEMP/extracted"
|
|
51
|
+
# Immutable destinations; the install lock serializes concurrent cold starts.
|
|
52
|
+
DPV2_LOCK="$DPV2_ROOT/bootstrap/.install-lock"
|
|
53
|
+
DPV2_TRIES=0
|
|
54
|
+
until mkdir "$DPV2_LOCK" 2>/dev/null; do
|
|
55
|
+
DPV2_TRIES=$((DPV2_TRIES+1))
|
|
56
|
+
[ "$DPV2_TRIES" -lt 60 ] || { printf '%s\\n' 'Bootstrap installer busy' >&2; exit 2; }
|
|
57
|
+
sleep 1
|
|
58
|
+
done
|
|
59
|
+
trap 'rmdir "$DPV2_LOCK" 2>/dev/null || :; rm -rf "$DPV2_TEMP"' EXIT HUP INT TERM
|
|
60
|
+
if [ ! -d "$DPV2_BOOT" ]; then mv "$DPV2_TEMP/extracted" "$DPV2_BOOT"; fi
|
|
61
|
+
rmdir "$DPV2_LOCK"
|
|
62
|
+
fi
|
|
63
|
+
"$DPV2_BOOT/package/$DPV2_PY" -E -s -B "$DPV2_BOOT/package/$DPV2_ENTRY" --root "$DPV2_ROOT" --origin @ORIGIN@ -- "$@"
|
|
64
|
+
'''
|
|
65
|
+
return script.replace('@CASES@','\n'.join(cases)).replace('@ORIGIN@',shell_quote(origin))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def render_ps(releases, origin='https://tedbrain.com'):
|
|
69
|
+
validate(releases); endpoint(origin)
|
|
70
|
+
item=releases['win32-x64']
|
|
71
|
+
script='''$ErrorActionPreference = 'Stop'
|
|
72
|
+
if (-not [Environment]::Is64BitOperatingSystem -or $env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { throw 'Windows x64 required' }
|
|
73
|
+
$Root = Join-Path $HOME '.ted/tedbrain/plugins/pdkadapt'
|
|
74
|
+
$Sha = @SHA@
|
|
75
|
+
$Boot = Join-Path (Join-Path $Root 'bootstrap') $Sha
|
|
76
|
+
$Python = Join-Path $Boot @PYTHON@
|
|
77
|
+
if (-not (Test-Path -LiteralPath $Python -PathType Leaf)) {
|
|
78
|
+
$Parent = Join-Path $Root 'bootstrap'
|
|
79
|
+
New-Item -ItemType Directory -Path $Parent -Force | Out-Null
|
|
80
|
+
$Temp = Join-Path $Parent ('.download-' + [Guid]::NewGuid().ToString('N'))
|
|
81
|
+
New-Item -ItemType Directory -Path $Temp | Out-Null
|
|
82
|
+
$Lock = $null
|
|
83
|
+
try {
|
|
84
|
+
$Archive = Join-Path $Temp 'bootstrap.tgz'
|
|
85
|
+
Invoke-WebRequest -UseBasicParsing -MaximumRedirection 0 -Uri @URL@ -OutFile $Archive -TimeoutSec 600
|
|
86
|
+
if ((Get-FileHash -Algorithm SHA256 -LiteralPath $Archive).Hash.ToLowerInvariant() -ne $Sha) { throw 'Bootstrap integrity mismatch' }
|
|
87
|
+
$Extract = Join-Path $Temp 'extracted'
|
|
88
|
+
New-Item -ItemType Directory -Path $Extract | Out-Null
|
|
89
|
+
& tar.exe -xzf $Archive -C $Extract
|
|
90
|
+
if ($LASTEXITCODE -ne 0) { throw 'Bootstrap extraction failed' }
|
|
91
|
+
$LockPath = Join-Path $Parent '.install.lock'
|
|
92
|
+
for ($i = 0; $i -lt 60; $i++) {
|
|
93
|
+
try { $Lock = [IO.File]::Open($LockPath, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None); break }
|
|
94
|
+
catch [IO.IOException] { Start-Sleep -Seconds 1 }
|
|
95
|
+
}
|
|
96
|
+
if ($null -eq $Lock) { throw 'Bootstrap installer busy' }
|
|
97
|
+
if (-not (Test-Path -LiteralPath $Boot)) { Move-Item -LiteralPath $Extract -Destination $Boot }
|
|
98
|
+
} finally {
|
|
99
|
+
if ($null -ne $Lock) { $Lock.Dispose() }
|
|
100
|
+
Remove-Item -LiteralPath $Temp -Recurse -Force -ErrorAction SilentlyContinue
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
& $Python -E -s -B (Join-Path $Boot @ENTRY@) --root $Root --origin @ORIGIN@ -- @args
|
|
104
|
+
exit $LASTEXITCODE
|
|
105
|
+
'''
|
|
106
|
+
values={'SHA':item['sha256'],'URL':item['url'],'PYTHON':'package/'+item['python'],'ENTRY':'package/'+item['entry'],'ORIGIN':origin}
|
|
107
|
+
for key,value in values.items():script=script.replace('@'+key+'@',ps_quote(value))
|
|
108
|
+
return script
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""AI-facing plugin CLI; HTTP is executed by the private new vlink."""
|
|
2
|
+
import argparse
|
|
3
|
+
import getpass
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import secrets
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import time
|
|
12
|
+
from .installer import ContractError, atomic, canonical, loads
|
|
13
|
+
from .service import PREFIX
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def transport(method,path,body=None,key=None,authenticated=True):
|
|
17
|
+
root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
|
|
18
|
+
root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
19
|
+
vlink=os.environ.get('DPV2_VLINK')
|
|
20
|
+
if not vlink or not Path(vlink).is_absolute() or not Path(vlink).is_file():
|
|
21
|
+
raise ContractError('private vlink missing; run the plugin entry first')
|
|
22
|
+
origin=os.environ.get('DPV2_ORIGIN','https://tedbrain.com')
|
|
23
|
+
token=root/'credentials/token'
|
|
24
|
+
if authenticated and not token.is_file():raise ContractError('login required: cli.sh login')
|
|
25
|
+
config={'schema':1,'origin':origin,'path':path,'method':method,'timeout_ms':30000,
|
|
26
|
+
'token_file':str(token) if authenticated else None,'idempotency_key':key}
|
|
27
|
+
# Loopback is only enabled by an explicitly selected isolated test origin.
|
|
28
|
+
if os.environ.get('DPV2_TEST_LOOPBACK')=='1':config['allow_loopback_http']=True
|
|
29
|
+
with tempfile.TemporaryDirectory(prefix='.http-',dir=root) as temporary:
|
|
30
|
+
request=Path(temporary)/'request.json';request.write_bytes(canonical(config));request.chmod(0o600)
|
|
31
|
+
result=subprocess.run([vlink,'rest','request',str(request)],input=canonical(body) if body is not None else b'',capture_output=True)
|
|
32
|
+
try:envelope=loads(result.stdout)
|
|
33
|
+
except ContractError:
|
|
34
|
+
raise ContractError('private vlink REST command failed before a valid response') from None
|
|
35
|
+
return result.returncode,envelope
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def show(code,envelope):
|
|
39
|
+
if envelope.get('outcome')=='response':
|
|
40
|
+
value=envelope.get('body')
|
|
41
|
+
else:value=envelope
|
|
42
|
+
print(json.dumps(value,ensure_ascii=False),flush=True)
|
|
43
|
+
return code
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def main(argv=None):
|
|
47
|
+
argv=list(sys.argv[1:] if argv is None else argv)
|
|
48
|
+
root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
|
|
49
|
+
if argv and argv[0]=='workstation':
|
|
50
|
+
p=argparse.ArgumentParser(description='Enroll a private Linux EDA executor; existing vlink stays untouched')
|
|
51
|
+
p.add_argument('workstation');p.add_argument('operation',choices=['connect','list','prepare'])
|
|
52
|
+
p.add_argument('--label',default='Linux EDA')
|
|
53
|
+
p.add_argument('--ssh',help='Explicit Linux EDA host alias or user@host; uses existing trusted OpenSSH configuration')
|
|
54
|
+
args=p.parse_args(argv)
|
|
55
|
+
if args.operation=='prepare':
|
|
56
|
+
payload=loads(sys.stdin.buffer.read(8193))
|
|
57
|
+
if not isinstance(payload,dict) or set(payload)!={'proxy','challenge'}:
|
|
58
|
+
raise ContractError('workstation preparation requires an enrollment challenge')
|
|
59
|
+
from .executor import start,prove
|
|
60
|
+
executor=start(root,payload['proxy'])
|
|
61
|
+
prove(executor['home'],payload['challenge'],executor['release_sha256'])
|
|
62
|
+
print(json.dumps({key:executor[key] for key in ('connection_id','release_sha256')}),flush=True)
|
|
63
|
+
return 0
|
|
64
|
+
if args.operation=='list':return show(*transport('GET',PREFIX+'/workstations'))
|
|
65
|
+
code,envelope=transport('GET',PREFIX+'/capabilities')
|
|
66
|
+
if code:return show(code,envelope)
|
|
67
|
+
proxy=envelope['body'].get('workstation_proxy')
|
|
68
|
+
if not proxy:raise ContractError('DPV2 workstation endpoint is not available')
|
|
69
|
+
from .executor import start,prove
|
|
70
|
+
intent_path=root/'enrollment-request.json'
|
|
71
|
+
intent=loads(intent_path.read_bytes()) if intent_path.is_file() else {}
|
|
72
|
+
if intent.get('label')!=args.label or intent.get('ssh')!=args.ssh or time.time()-intent.get('created',0)>600:
|
|
73
|
+
intent={'label':args.label,'ssh':args.ssh,'key':secrets.token_hex(16),'created':time.time()}
|
|
74
|
+
atomic(intent_path,canonical(intent))
|
|
75
|
+
code,envelope=transport('POST',PREFIX+'/workstation-challenges',{'label':args.label},intent['key'])
|
|
76
|
+
if code:return show(code,envelope)
|
|
77
|
+
challenge=envelope['body'];proof=None
|
|
78
|
+
if args.ssh:
|
|
79
|
+
from .ssh_workstation import prepare
|
|
80
|
+
executor=prepare(args.ssh,proxy,challenge)
|
|
81
|
+
else:
|
|
82
|
+
executor=start(root,proxy)
|
|
83
|
+
proof=prove(executor['home'],challenge,executor['release_sha256'])
|
|
84
|
+
code,envelope=transport('POST',PREFIX+'/workstation-challenges/'+challenge['challenge_id']+'/confirmation',
|
|
85
|
+
{'connection_id':executor['connection_id']},challenge['challenge_id'])
|
|
86
|
+
if not code:
|
|
87
|
+
atomic(root/'workstation.json',canonical(envelope['body']))
|
|
88
|
+
if proof is not None:proof.unlink()
|
|
89
|
+
intent_path.unlink()
|
|
90
|
+
return show(code,envelope)
|
|
91
|
+
if argv and argv[0]=='login':
|
|
92
|
+
p=argparse.ArgumentParser();p.add_argument('login');p.add_argument('--stdin',action='store_true');a=p.parse_args(argv)
|
|
93
|
+
credential=sys.stdin.readline().strip() if a.stdin else getpass.getpass('TedBrain invitation code: ')
|
|
94
|
+
code,envelope=transport('POST','/api/dpv2/auth/sessions',{'credential':credential},secrets.token_hex(16),authenticated=False)
|
|
95
|
+
if code:return show(code,envelope)
|
|
96
|
+
body=envelope['body'];token=body.get('access_token')
|
|
97
|
+
if body.get('audience')!='dpv2' or not isinstance(token,str) or not token.startswith('dpv2_'):
|
|
98
|
+
raise ContractError('login returned an invalid DPV2 credential')
|
|
99
|
+
directory=root/'credentials';directory.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
100
|
+
atomic(directory/'token',token.encode())
|
|
101
|
+
print(json.dumps({'ok':True,'subject':body['subject'],'expires_at':body['expires_at']}));return 0
|
|
102
|
+
p=argparse.ArgumentParser(description='DPV2 pdkadapt plugin: asynchronous REST jobs')
|
|
103
|
+
p.add_argument('--version',action='version',version='pdkadapt plugin '+os.environ.get('DPV2_RELEASE_VERSION','0.1.0'))
|
|
104
|
+
p.add_argument('--action',choices=['check','start','status','resume','cancel','logs','source-preview','source-confirm','source-install','source-publish'],default='start')
|
|
105
|
+
p.add_argument('--mode',default='')
|
|
106
|
+
for name in ['vendor-dir','alias','foundry','arch','cells','run-id','from-step','layer-decision','layer-rule-decision','source-package','use-client-revision','options-hash','revision','token','reason']:
|
|
107
|
+
p.add_argument('--'+name,default='')
|
|
108
|
+
p.add_argument('--confirmed',action='store_true')
|
|
109
|
+
station=loads((root/'workstation.json').read_bytes()).get('workstation_id','') if (root/'workstation.json').is_file() else ''
|
|
110
|
+
p.add_argument('--workstation-id',default=station)
|
|
111
|
+
p.add_argument('--request-id',default='')
|
|
112
|
+
p.add_argument('--after',type=int,default=0)
|
|
113
|
+
p.add_argument('--wait',action='store_true')
|
|
114
|
+
args=p.parse_args(argv or ['--help'])
|
|
115
|
+
if args.action=='status':
|
|
116
|
+
path=PREFIX+('/jobs/'+args.run_id if args.run_id else '/requests/'+args.request_id)
|
|
117
|
+
if not args.run_id and not args.request_id:p.error('status requires --run-id or --request-id')
|
|
118
|
+
return show(*transport('GET',path))
|
|
119
|
+
if args.action=='logs':
|
|
120
|
+
if not args.run_id:p.error('logs requires --run-id')
|
|
121
|
+
return show(*transport('GET',PREFIX+'/jobs/'+args.run_id+'/events?after='+str(args.after)))
|
|
122
|
+
key=args.request_id or secrets.token_hex(16)
|
|
123
|
+
if not __import__('re').fullmatch(r'[A-Za-z0-9._-]{1,128}',key):p.error('invalid --request-id')
|
|
124
|
+
fields=['action','mode','vendor_dir','alias','foundry','arch','cells','run_id','from_step','layer_decision','layer_rule_decision','source_package','use_client_revision']
|
|
125
|
+
request={name:getattr(args,name) for name in fields}
|
|
126
|
+
if args.action=='start':
|
|
127
|
+
if not args.workstation_id:p.error('start requires --workstation-id')
|
|
128
|
+
path=PREFIX+'/jobs';body={'workstation_id':args.workstation_id,'request':request}
|
|
129
|
+
elif args.action=='resume':
|
|
130
|
+
if not args.run_id:p.error('resume requires --run-id')
|
|
131
|
+
path=PREFIX+'/jobs/'+args.run_id+'/resumptions';body={'request':request}
|
|
132
|
+
elif args.action=='cancel':
|
|
133
|
+
if not args.run_id:p.error('cancel requires --run-id')
|
|
134
|
+
path=PREFIX+'/jobs/'+args.run_id+'/cancellations';body={}
|
|
135
|
+
else:
|
|
136
|
+
raise ContractError('This action has not been admitted on DPV2; it will not run through DPV1')
|
|
137
|
+
journal=root/'requests';journal.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
138
|
+
record=journal/(key+'.json');intent={'path':path,'body':body,'request_id':key}
|
|
139
|
+
# Exclusive creation makes a reused key with different input fail before send.
|
|
140
|
+
try:
|
|
141
|
+
descriptor=os.open(record,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
|
142
|
+
except FileExistsError:
|
|
143
|
+
if loads(record.read_bytes())!=intent:raise ContractError('request ID belongs to different input')
|
|
144
|
+
else:
|
|
145
|
+
with os.fdopen(descriptor,'wb') as stream:
|
|
146
|
+
stream.write(canonical(intent));stream.flush();os.fsync(stream.fileno())
|
|
147
|
+
code,envelope=transport('POST',path,body,key)
|
|
148
|
+
print(json.dumps({'request_id':key,'request_record':str(record)},ensure_ascii=False),file=sys.stderr)
|
|
149
|
+
if code or not args.wait:return show(code,envelope)
|
|
150
|
+
body=envelope['body'];job=body['job_id']
|
|
151
|
+
print(json.dumps(body,ensure_ascii=False),flush=True)
|
|
152
|
+
while True:
|
|
153
|
+
time.sleep(2)
|
|
154
|
+
code,envelope=transport('GET',PREFIX+'/jobs/'+job)
|
|
155
|
+
if code:return show(code,envelope)
|
|
156
|
+
state=envelope['body']['job_status']
|
|
157
|
+
if state in ('SUCCEEDED','FAILED','CANCELLED','UNKNOWN','WAITING_INPUT'):
|
|
158
|
+
return show(0 if state=='SUCCEEDED' else 1,envelope)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
if __name__=='__main__':
|
|
162
|
+
try:raise SystemExit(main())
|
|
163
|
+
except ContractError as error:
|
|
164
|
+
print(json.dumps({'ok':False,'error':{'code':'PLUGIN_REQUEST_FAILED','message':str(error)}}),file=sys.stderr)
|
|
165
|
+
raise SystemExit(2)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Run one fixed DPV2 attempt through the existing PDK adaptation engine."""
|
|
2
|
+
from dataclasses import asdict
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import sys
|
|
7
|
+
import traceback
|
|
8
|
+
from .installer import atomic,canonical,loads,ContractError
|
|
9
|
+
from .jobs import Jobs
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Cancelled(Exception):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def run(path):
|
|
17
|
+
path=Path(path);spec=loads(path.read_bytes());row=spec['job'];config=spec['config'];station=spec['workstation']
|
|
18
|
+
jobs=Jobs(Path(config['state_root'])/'jobs.sqlite3')
|
|
19
|
+
request=loads(row['request']);directory=path.parent
|
|
20
|
+
# Only server-pinned inventories can bind the runtime. Remote home and
|
|
21
|
+
# connection come from the authenticated enrollment, never job parameters.
|
|
22
|
+
executor=config['executor_contracts'][station['release_sha256']]
|
|
23
|
+
contract=dict(executor,schema=1,kind='dpv2-npm-executor',home=station['home'],
|
|
24
|
+
release_sha256=station['release_sha256'],connection_id=station['connection_id'],
|
|
25
|
+
serve_url=config['transport']['serve_url'])
|
|
26
|
+
atomic(directory/'runtime-contract.json',canonical(contract))
|
|
27
|
+
os.environ.update(TED_CLIENT_RUNTIME_CONTRACT=str(directory/'runtime-contract.json'),
|
|
28
|
+
PDK_ADAPTER_CELLS=request.get('cells',''),TED_PDK_ADAPTER_MODE='v2',
|
|
29
|
+
TED_PDK_LAYER_DECISION=request.get('layer_decision',''),
|
|
30
|
+
TED_PDK_LAYER_RULE_DECISION=request.get('layer_rule_decision',''),
|
|
31
|
+
TED_EDA_MODE='3')
|
|
32
|
+
os.environ.pop('TED_MOS_FIELDS_MODE',None)
|
|
33
|
+
from ted_eda_tools.protocol.pdk_session import PdkAdaptSession
|
|
34
|
+
from ted_eda_tools.protocol.pdk_progress import PdkWorkflow
|
|
35
|
+
from ted_pdk_adapter.src.layer_mapping_validation import LayerMappingDecisionRequired
|
|
36
|
+
|
|
37
|
+
def cancelled():
|
|
38
|
+
current=jobs.get(row['subject'],row['id'])
|
|
39
|
+
if current['attempt']!=row['attempt']:raise ContractError('attempt ownership changed')
|
|
40
|
+
if current['job_status']=='CANCELLING':raise Cancelled()
|
|
41
|
+
|
|
42
|
+
class Session(PdkAdaptSession):
|
|
43
|
+
def send_tool(self,*args,**kwargs):
|
|
44
|
+
cancelled()
|
|
45
|
+
result=super().send_tool(*args,**kwargs)
|
|
46
|
+
cancelled()
|
|
47
|
+
return result
|
|
48
|
+
def publish_server_result(self):
|
|
49
|
+
# The engine's verified tree already lives in the DPV2 run store.
|
|
50
|
+
# Final installation is verified by deliver_final_pdk itself.
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
session=Session(str(Path(config['state_root'])/'engine'),'dpv2',station['connection_id'],
|
|
54
|
+
row['id'],request['alias'],client_key=row['subject'],machine_key=row['workstation'],mode='full')
|
|
55
|
+
pointer=directory.parent/'session-location.json'
|
|
56
|
+
if request['action']=='resume':
|
|
57
|
+
previous=Path(loads(pointer.read_bytes())['path'])
|
|
58
|
+
root=(Path(config['state_root'])/'engine').resolve()
|
|
59
|
+
if root not in previous.resolve().parents or previous.is_symlink():raise ContractError('checkpoint path escaped run store')
|
|
60
|
+
document=loads((previous/'session.json').read_bytes())
|
|
61
|
+
for key,value in [('tenant','dpv2'),('run_id',row['id']),('alias',request['alias']),('client_key',row['subject']),('machine_key',row['workstation'])]:
|
|
62
|
+
if document.get(key)!=value:raise ContractError('checkpoint identity mismatch')
|
|
63
|
+
session.rebase(previous)
|
|
64
|
+
identity={key:getattr(session.state,key) for key in ('tenant','client_id','run_id','alias','client_key','machine_key')}
|
|
65
|
+
session.state=session._restore_state(identity,document)
|
|
66
|
+
if request.get('from_step'):
|
|
67
|
+
session.prepare_attempt(int(request['from_step']),{'working_dir':'attempts/'+row['attempt'],'attempt_id':row['attempt']})
|
|
68
|
+
else:
|
|
69
|
+
if session.root.exists():raise ContractError('new job already has an engine workspace')
|
|
70
|
+
session.root.mkdir(parents=True,mode=0o700)
|
|
71
|
+
session._save_state()
|
|
72
|
+
atomic(pointer,canonical({'path':str(session.root),'attempt':row['attempt']}))
|
|
73
|
+
session.workflow=PdkWorkflow(session,request)
|
|
74
|
+
os.environ['TED_PDK_PROGRESS_FILE']=str(session.root/'extraction-progress.json')
|
|
75
|
+
def progress(state):
|
|
76
|
+
jobs.append(row['id'],row['attempt'],{'event':'checkpoint','step':state.step,'phase':state.status})
|
|
77
|
+
cancelled()
|
|
78
|
+
result=None;stopped=False
|
|
79
|
+
try:
|
|
80
|
+
cancelled()
|
|
81
|
+
with session.workflow.reporting():
|
|
82
|
+
session.run_automatic(config['transport']['serve_url'],request['vendor_dir'],request['foundry'],request['arch'],progress=progress,
|
|
83
|
+
source_package=request.get('source_package',''))
|
|
84
|
+
result={'ok':True,'job_status':'COMPLETED','delivery':session.state.decision,'step':session.state.step}
|
|
85
|
+
stopped=True
|
|
86
|
+
except Cancelled:
|
|
87
|
+
# Cooperative cancellation occurs only between completed synchronous
|
|
88
|
+
# operations. A network failure never reaches this branch.
|
|
89
|
+
result={'ok':False,'job_status':'CANCELLED'};stopped=True
|
|
90
|
+
except LayerMappingDecisionRequired as error:
|
|
91
|
+
result={'ok':False,'job_status':'WAITING_FOR_DECISION','pending_decision':error.decision};stopped=True
|
|
92
|
+
except Exception as error:
|
|
93
|
+
traceback.print_exc()
|
|
94
|
+
stopped=getattr(error,'remote_terminal_ack',None) in ('stopped','prevented','completed')
|
|
95
|
+
result={'ok':False,'job_status':'FAILED','error':{'code':'ADAPTATION_FAILED',
|
|
96
|
+
'message':'Adaptation failed; inspect this attempt events and reconcile remote execution'}}
|
|
97
|
+
session.workflow.finish(result['job_status'])
|
|
98
|
+
atomic(directory/'result.json',canonical({'job_id':row['id'],'attempt':row['attempt'],'version':row['version'],
|
|
99
|
+
'result':result,'remote_stop_confirmed':stopped,'checkpoint_schema':'dpv2-pdk-session-1'}))
|
|
100
|
+
return 0 if result.get('ok') else 1
|
|
101
|
+
|
|
102
|
+
if __name__=='__main__':raise SystemExit(run(sys.argv[1]))
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Launch the npm-pinned transport executor in a private DPV2 workstation HOME."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
import time
|
|
9
|
+
from urllib.parse import urlsplit
|
|
10
|
+
from .installer import ContractError, atomic, canonical, loads, Installer, locked
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def runtime_identity(components):
|
|
14
|
+
selected={key:components[key]['sha256'] for key in ('executor','python')}
|
|
15
|
+
if any(not re.fullmatch('[a-f0-9]{64}',value) for value in selected.values()):
|
|
16
|
+
raise ContractError('fixed executor and Python identities required')
|
|
17
|
+
return hashlib.sha256(canonical(dict(selected,schema=1))).hexdigest()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def environment(home, proxy, python, runtime):
|
|
21
|
+
home=Path(home)
|
|
22
|
+
# Remove inherited V1 routes and execution state. Retain explicitly supplied
|
|
23
|
+
# EDA installation/license environment and the user's ordinary executable PATH.
|
|
24
|
+
env={k:v for k,v in os.environ.items() if not k.startswith(('ELINK_', 'VLINK_', 'DPV2_', 'TED_', 'TEDBRAIN_', 'PDK', 'PYTHON', 'XDG_'))}
|
|
25
|
+
for key,relative in [('HOME','.'),('XDG_CONFIG_HOME','config'),('XDG_CACHE_HOME','cache'),
|
|
26
|
+
('XDG_STATE_HOME','state'),('XDG_RUNTIME_DIR','run'),('TMPDIR','tmp'),
|
|
27
|
+
('TED_VLINK_RUNTIME_ROOT','vlink'),('VLINK_REMOTE_WORKSPACE_PREFIX','store'),
|
|
28
|
+
('TED_DATA','data'),('PDKS_FOLDER','assets/pdks')]:
|
|
29
|
+
path=home/relative;path.mkdir(parents=True,exist_ok=True,mode=0o700);env[key]=str(path)
|
|
30
|
+
env.update(ELINK_PROXY_URL=proxy,TEDMIND_SKIP_VLINK_UPDATE='1',VLINK_REMOTE_MAX_CONCURRENT='2',
|
|
31
|
+
PYTHONNOUSERSITE='1',PYTHONDONTWRITEBYTECODE='1',TED_PATH=str(runtime),
|
|
32
|
+
PATH=str(Path(python).parent)+os.pathsep+env.get('PATH',''),
|
|
33
|
+
PYTHONPATH=str(runtime),LC_ALL='C',LANG='C')
|
|
34
|
+
return env
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def live(record):
|
|
38
|
+
try:
|
|
39
|
+
value=Path('/proc/%d/stat'%record['pid']).read_text()
|
|
40
|
+
fields=value[value.rfind(')')+2:].split()
|
|
41
|
+
return fields[0]!='Z' and fields[19]==record['start_time']
|
|
42
|
+
except (OSError,KeyError,IndexError):return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def start(root, proxy):
|
|
46
|
+
root=Path(root).absolute()
|
|
47
|
+
with locked(root):
|
|
48
|
+
return _start(root, proxy)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _start(root, proxy):
|
|
52
|
+
if os.name!='posix' or not Path('/proc').is_dir():raise ContractError('EDA executor requires Linux')
|
|
53
|
+
parsed=urlsplit(proxy)
|
|
54
|
+
local=os.environ.get('DPV2_TEST_LOOPBACK')=='1' and parsed.scheme=='ws' and parsed.hostname=='127.0.0.1'
|
|
55
|
+
if not local and (parsed.scheme!='wss' or parsed.hostname not in ('tedbrain.com','www.tedbrain.com')):
|
|
56
|
+
raise ContractError('DPV2 executor requires the published WSS endpoint')
|
|
57
|
+
if parsed.username or parsed.password or parsed.query or parsed.fragment:raise ContractError('invalid executor endpoint')
|
|
58
|
+
install=Installer(root,target='linux-x64',local_registry=os.environ.get('DPV2_TEST_REGISTRY'));meta=install.cached()
|
|
59
|
+
component=meta['release']['components'].get('executor')
|
|
60
|
+
if component is None:raise ContractError('this release does not contain the EDA executor')
|
|
61
|
+
directory=install.component_path(component)
|
|
62
|
+
binary=directory/'bin/vlink-executor';runtime=directory/'runtime'
|
|
63
|
+
python=install.entries(meta)['python']
|
|
64
|
+
if not binary.is_file() or not runtime.is_dir():raise ContractError('executor payload is incomplete')
|
|
65
|
+
# A new runtime gets a distinct HOME; an older active executor keeps all its
|
|
66
|
+
# state and process identity. Never overwrite or restart it during upgrade.
|
|
67
|
+
release=runtime_identity(meta['release']['components'])
|
|
68
|
+
home=Path(root)/'workstations'/release/'home'
|
|
69
|
+
home.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
70
|
+
env=environment(home,proxy,python,runtime)
|
|
71
|
+
for name,target in [('runtime',runtime),('python',python.parent.parent)]:
|
|
72
|
+
link=home/name
|
|
73
|
+
if link.is_symlink():
|
|
74
|
+
if link.resolve()!=target.resolve():raise ContractError('executor link changed')
|
|
75
|
+
elif link.exists():raise ContractError('executor path is already occupied')
|
|
76
|
+
else:link.symlink_to(target.resolve(),target_is_directory=True)
|
|
77
|
+
record_path=home/'process.json'
|
|
78
|
+
if record_path.exists():
|
|
79
|
+
record=loads(record_path.read_bytes())
|
|
80
|
+
if not live(record):raise ContractError('executor stopped; reconcile its jobs before explicitly restarting')
|
|
81
|
+
if record['proxy_url']!=proxy:raise ContractError('executor is already bound to another endpoint')
|
|
82
|
+
else:
|
|
83
|
+
with (home/'executor.log').open('ab') as log:
|
|
84
|
+
process=subprocess.Popen([str(binary),'daemon','start'],env=env,stdin=subprocess.DEVNULL,
|
|
85
|
+
stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
|
|
86
|
+
fields=Path('/proc/%d/stat'%process.pid).read_text().rsplit(')',1)[1].split()
|
|
87
|
+
record={'pid':process.pid,'start_time':fields[19],'proxy_url':proxy,'release_sha256':release}
|
|
88
|
+
atomic(record_path,canonical(record))
|
|
89
|
+
deadline=time.monotonic()+20
|
|
90
|
+
while time.monotonic()<deadline:
|
|
91
|
+
if not live(record):raise ContractError('private executor exited; inspect its private log')
|
|
92
|
+
paths=list((home/'run/ted/vlink/metadata').glob('vlink-remote-client-*.json'))
|
|
93
|
+
for path in paths:
|
|
94
|
+
info=loads(path.read_bytes())
|
|
95
|
+
if info.get('pid')==record['pid'] and info.get('proxy_url')==proxy and info.get('conn_id'):
|
|
96
|
+
return {'home':str(home),'connection_id':info['conn_id'],'release_sha256':release}
|
|
97
|
+
time.sleep(.2)
|
|
98
|
+
raise ContractError('executor connection pending; retry enrollment with the same release')
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def prove(home, challenge, release):
|
|
102
|
+
identifier=challenge.get('challenge_id','');nonce=challenge.get('nonce','')
|
|
103
|
+
if not re.fullmatch('[a-f0-9]{32}',identifier) or not re.fullmatch('[a-f0-9]{64}',nonce):
|
|
104
|
+
raise ContractError('invalid enrollment challenge')
|
|
105
|
+
path=Path(home)/'.ted/tedbrain/dpv2-binding'/ (identifier+'.json')
|
|
106
|
+
path.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
107
|
+
atomic(path,canonical({'protocol':1,'platform':'linux-x64','nonce':nonce,'release_sha256':release}))
|
|
108
|
+
return path
|