@tedbrain/vlink 0.0.0-dpv2.pdkadapt.plugin.0.1.1.r1 → 0.0.0-dpv2.pdkadapt.plugin.0.1.3.r2
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 +4 -2
- package/package.json +1 -1
- package/tedbrain_plugin_runtime/auth.py +88 -0
- package/tedbrain_plugin_runtime/cli.py +93 -20
- package/tedbrain_plugin_runtime/jobs.py +17 -0
- package/tedbrain_plugin_runtime/publication.py +10 -2
- package/tedbrain_plugin_runtime/service.py +52 -1
- package/tedbrain_plugin_runtime/worker.py +40 -1
package/README.md
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
这是独立 Python distribution,当前提供安装器、REST 控制面和客户端候选。源码与 DPV1 同仓,运行时不导入旧 cli/MCP;没有改动 DPV1 的入口、服务器或客户端。
|
|
4
4
|
|
|
5
|
-
**尚未具备完整适配能力。** 真实工作站绑定、独立 SDK/EDA worker
|
|
5
|
+
**尚未具备完整适配能力。** 真实工作站绑定、独立 SDK/EDA worker 和四平台实际验收仍属 I01618。不要手工写 admitted=true 绕过未完成的 worker 准入。未配置准入时,业务提交明确返回 503;健康检查通过不表示可执行适配。
|
|
6
|
+
|
|
7
|
+
旧动作面映射(2026-11-29):`--action check` 映射 `POST /checks`,只查询不启动适配;复用判定只来自本账号自身的 DPV2 交付历史(服务器端跨主体复用保持关闭)。REUSED 必须携带与交付 tree 摘要一致的 `--use-client-revision`;有交付未确认时返回 `CLIENT_CONFIRMATION_REQUIRED`,无历史时按旧语义返回 `ADAPTATION_REQUIRED`/`REUSE_DISABLED`,check 恒以退出码 0 结束。`source-preview/confirm/install/publish` 保留旧参数校验(--vendor-dir、64 位 --options-hash/--revision、--token、--confirmed、--reason、--alias/--run-id),映射 `POST /sources/{previews,confirmations,installations,publications}`;DPV2 未提供公共工艺源复用通道,服务端以结构化 `SOURCE_REUSE_UNAVAILABLE` 应答(退出码 1),不伪造成功也不静默忽略。
|
|
6
8
|
|
|
7
9
|
## 本地安装与验证
|
|
8
10
|
|
|
@@ -14,7 +16,7 @@ PYTHONDONTWRITEBYTECODE=1 TED_EDA_MODE=LOCAL python3 -m pytest tests/test_dpv2*.
|
|
|
14
16
|
|
|
15
17
|
`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
18
|
|
|
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
|
|
19
|
+
服务使用 `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。客户端只读复用 V1 vlink 保存的邀请码或 VLINK_INVITE_CODE,使用已有 auth/sessions 验证换取;首次认证与到期自动完成,V1 配置保持原状。生产 TLS/资源配方和部署命令尚未交付。开发测试使用临时 loopback 和模拟账号验证源。
|
|
18
20
|
|
|
19
21
|
## 安装和任务合同
|
|
20
22
|
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.
|
|
1
|
+
{"name": "@tedbrain/vlink", "private": false, "version": "0.0.0-dpv2.pdkadapt.plugin.0.1.3.r2"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Read existing vlink onboarding state without changing the V1 installation."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import re
|
|
6
|
+
import stat
|
|
7
|
+
import time
|
|
8
|
+
from urllib.parse import urlsplit
|
|
9
|
+
from .installer import ContractError, atomic, canonical, loads
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def config_root(environ=None, platform=None):
|
|
13
|
+
env=os.environ if environ is None else environ
|
|
14
|
+
if (os.name if platform is None else platform)=='nt':
|
|
15
|
+
profile=env.get('USERPROFILE') or (env.get('HOMEDRIVE','')+env.get('HOMEPATH',''))
|
|
16
|
+
base=Path(env['APPDATA']) if 'APPDATA' in env else Path(profile or '.')/'AppData/Roaming'
|
|
17
|
+
return base/'TED/vlink'
|
|
18
|
+
return Path(env.get('HOME') or '.')/'.config/.vlink'
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def normalize(value):
|
|
22
|
+
code=value.strip().upper() if isinstance(value,str) else ''
|
|
23
|
+
if not re.fullmatch(r'TB-[A-Z0-9]{12}',code):
|
|
24
|
+
raise ContractError('V1 vlink credential invalid; use cli.sh login --stdin or repair VLINK_INVITE_CODE')
|
|
25
|
+
return code
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def saved_credential():
|
|
29
|
+
# Match V1 precedence: even an empty explicit override must not fall through.
|
|
30
|
+
if 'VLINK_INVITE_CODE' in os.environ:return normalize(os.environ['VLINK_INVITE_CODE'])
|
|
31
|
+
root=config_root()
|
|
32
|
+
for relative in ('mcp/credentials.json','agents/tedbrain.json'):
|
|
33
|
+
path=root/relative
|
|
34
|
+
try:
|
|
35
|
+
info=path.lstat()
|
|
36
|
+
except FileNotFoundError:continue
|
|
37
|
+
except OSError:raise ContractError('Cannot read V1 vlink credential; use cli.sh login --stdin') from None
|
|
38
|
+
if (not stat.S_ISREG(info.st_mode) or info.st_size>65536 or
|
|
39
|
+
(os.name!='nt' and (info.st_uid!=os.geteuid() or info.st_mode & 0o077))):
|
|
40
|
+
raise ContractError('V1 vlink credential must be a private regular file; use cli.sh login --stdin')
|
|
41
|
+
try:
|
|
42
|
+
with path.open('rb') as stream:raw=stream.read(65537)
|
|
43
|
+
if len(raw)>65536:raise ValueError()
|
|
44
|
+
value=json.loads(raw)
|
|
45
|
+
return normalize(value.get('invitation_code') if isinstance(value,dict) else None)
|
|
46
|
+
except (OSError,ValueError):
|
|
47
|
+
raise ContractError('Cannot read V1 vlink credential; use cli.sh login --stdin') from None
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def save_session(root,envelope,origin):
|
|
52
|
+
body=envelope.get('body',{});token=body.get('access_token')
|
|
53
|
+
expires=body.get('expires_at');subject=body.get('subject')
|
|
54
|
+
if (envelope.get('outcome')!='response' or body.get('audience')!='dpv2' or
|
|
55
|
+
not isinstance(token,str) or not re.fullmatch(r'dpv2_[A-Za-z0-9_-]{32,128}',token) or
|
|
56
|
+
not isinstance(expires,(float,int)) or not isinstance(subject,str)):
|
|
57
|
+
raise ContractError('login returned an invalid DPV2 credential')
|
|
58
|
+
directory=root/'credentials';directory.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
59
|
+
atomic(directory/'token',token.encode())
|
|
60
|
+
metadata={'subject':subject,'expires_at':expires,'origin':origin}
|
|
61
|
+
atomic(directory/'session.json',canonical(metadata))
|
|
62
|
+
return metadata
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def ensure_session(root,origin,exchange,force=False):
|
|
66
|
+
token=root/'credentials/token';metadata=root/'credentials/session.json'
|
|
67
|
+
if token.is_file() and not force:
|
|
68
|
+
if not metadata.is_file():return None # Existing releases renew on a real 401.
|
|
69
|
+
try:session=loads(metadata.read_bytes())
|
|
70
|
+
except (OSError,ContractError):raise ContractError('DPV2 session metadata unreadable; use cli.sh login --stdin') from None
|
|
71
|
+
if session.get('origin')!=origin:raise ContractError('DPV2 session origin differs; login explicitly for the selected origin')
|
|
72
|
+
if session.get('expires_at',0)>time.time()+30:return session
|
|
73
|
+
parsed=urlsplit(origin)
|
|
74
|
+
official=origin in ('https://tedbrain.com','https://www.tedbrain.com')
|
|
75
|
+
loopback=(os.environ.get('DPV2_TEST_LOOPBACK')=='1' and parsed.scheme=='http' and
|
|
76
|
+
parsed.hostname in ('127.0.0.1','localhost','::1') and not parsed.username and not parsed.password)
|
|
77
|
+
if not (official or loopback):
|
|
78
|
+
raise ContractError('Automatic V1 login reuse requires the official TedBrain HTTPS origin')
|
|
79
|
+
credential=saved_credential()
|
|
80
|
+
if credential is None:
|
|
81
|
+
raise ContractError('login required: cli.sh login (or login --stdin); no saved V1 vlink credential')
|
|
82
|
+
code,envelope=exchange(credential)
|
|
83
|
+
if code:
|
|
84
|
+
status=envelope.get('status')
|
|
85
|
+
if envelope.get('outcome')=='response' and status in (401,403):
|
|
86
|
+
raise ContractError('Saved V1 vlink credential rejected; use cli.sh login --stdin')
|
|
87
|
+
raise ContractError('DPV2 login service unavailable; retry authentication later; business request was not replayed')
|
|
88
|
+
return save_session(root,envelope,origin)
|
|
@@ -4,16 +4,41 @@ import getpass
|
|
|
4
4
|
import json
|
|
5
5
|
import os
|
|
6
6
|
from pathlib import Path
|
|
7
|
+
import re
|
|
7
8
|
import secrets
|
|
8
9
|
import subprocess
|
|
9
10
|
import sys
|
|
10
11
|
import tempfile
|
|
11
12
|
import time
|
|
13
|
+
import unicodedata
|
|
12
14
|
from .installer import ContractError, atomic, canonical, loads
|
|
13
15
|
from .service import PREFIX
|
|
14
16
|
|
|
15
17
|
|
|
18
|
+
def exchange_session(root,credential):
|
|
19
|
+
# Persist only the request identity, never the reusable V1 secret.
|
|
20
|
+
directory=root/'credentials';directory.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
21
|
+
key=secrets.token_hex(16)
|
|
22
|
+
atomic(directory/'login-request.json',canonical({'path':'/api/dpv2/auth/sessions','request_id':key}))
|
|
23
|
+
return _request('POST','/api/dpv2/auth/sessions',{'credential':credential},key,False)
|
|
24
|
+
|
|
25
|
+
|
|
16
26
|
def transport(method,path,body=None,key=None,authenticated=True):
|
|
27
|
+
from .auth import ensure_session
|
|
28
|
+
root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
|
|
29
|
+
origin=os.environ.get('DPV2_ORIGIN','https://tedbrain.com')
|
|
30
|
+
exchange=lambda credential:exchange_session(root,credential)
|
|
31
|
+
if authenticated:ensure_session(root,origin,exchange)
|
|
32
|
+
result=_request(method,path,body,key,authenticated)
|
|
33
|
+
# Only an explicit authentication rejection proves business was not run.
|
|
34
|
+
# Keep the original intent/key; never retry a timeout, 5xx or unknown result.
|
|
35
|
+
if authenticated and result[1].get('outcome')=='response' and result[1].get('status')==401:
|
|
36
|
+
ensure_session(root,origin,exchange,force=True)
|
|
37
|
+
result=_request(method,path,body,key,authenticated)
|
|
38
|
+
return result
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _request(method,path,body=None,key=None,authenticated=True):
|
|
17
42
|
root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
|
|
18
43
|
root.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
19
44
|
vlink=os.environ.get('DPV2_VLINK')
|
|
@@ -43,6 +68,55 @@ def show(code,envelope):
|
|
|
43
68
|
return code
|
|
44
69
|
|
|
45
70
|
|
|
71
|
+
SOURCE_ROUTES={'source-preview':'previews','source-confirm':'confirmations',
|
|
72
|
+
'source-install':'installations','source-publish':'publications'}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def post_request(root,key,path,body):
|
|
76
|
+
"""Persist every authenticated POST intent before invoking private vlink."""
|
|
77
|
+
journal=root/'requests';journal.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
78
|
+
record=journal/(key+'.json');intent={'path':path,'body':body,'request_id':key}
|
|
79
|
+
# Exclusive creation makes a reused key with different input fail before send.
|
|
80
|
+
try:
|
|
81
|
+
descriptor=os.open(record,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
|
82
|
+
except FileExistsError:
|
|
83
|
+
if loads(record.read_bytes())!=intent:raise ContractError('request ID belongs to different input')
|
|
84
|
+
else:
|
|
85
|
+
with os.fdopen(descriptor,'wb') as stream:
|
|
86
|
+
stream.write(canonical(intent));stream.flush();os.fsync(stream.fileno())
|
|
87
|
+
code,envelope=transport('POST',path,body,key)
|
|
88
|
+
print(json.dumps({'request_id':key,'request_record':str(record)},ensure_ascii=False),file=sys.stderr)
|
|
89
|
+
return code,envelope
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def source_action(args,root,key):
|
|
93
|
+
"""Old source-reuse face: DPV1 parameter validation, then the DPV2 REST answer.
|
|
94
|
+
|
|
95
|
+
The shared source channel stays closed on DPV2 (server-side reuse
|
|
96
|
+
boundary), so the service returns the defined structured status; the CLI
|
|
97
|
+
keeps DPV1's exit code for it instead of silently succeeding.
|
|
98
|
+
"""
|
|
99
|
+
vendor=args.vendor_dir
|
|
100
|
+
if not vendor:raise ContractError('必须提供厂商 PDK 的绝对目录 --vendor-dir。')
|
|
101
|
+
if args.action=='source-publish':
|
|
102
|
+
reason=args.reason.strip()
|
|
103
|
+
if not 1<=len(reason)<=500 or any(unicodedata.category(char)=='Cc' for char in reason):
|
|
104
|
+
raise ContractError('请提供 1–500 字符的明确任务理由,说明本次源归档上传的用途,不得包含控制字符。')
|
|
105
|
+
if args.action in ('source-confirm','source-install'):
|
|
106
|
+
if not re.fullmatch('[0-9a-f]{64}',args.options_hash) or not re.fullmatch('[0-9a-f]{64}',args.revision) or not args.token:
|
|
107
|
+
raise ContractError('source-confirm/source-install 需要预览回执中的 --options-hash、--revision 和 --token。')
|
|
108
|
+
if not args.confirmed:
|
|
109
|
+
raise ContractError('公共工艺复用必须显式确认:请附加 --confirmed 表示用户已确认该配置。')
|
|
110
|
+
if args.action=='source-install' and (not args.alias or not args.run_id):
|
|
111
|
+
raise ContractError('source-install 需要交付目标 --alias 和本次复用作业的 --run-id。')
|
|
112
|
+
code,envelope=post_request(root,key,PREFIX+'/sources/'+SOURCE_ROUTES[args.action],
|
|
113
|
+
{'action':args.action,'vendor_dir':vendor})
|
|
114
|
+
if not code:
|
|
115
|
+
value=envelope.get('body') if envelope.get('outcome')=='response' else envelope
|
|
116
|
+
if isinstance(value,dict) and value.get('ok') is False:return show(1,envelope)
|
|
117
|
+
return show(code,envelope)
|
|
118
|
+
|
|
119
|
+
|
|
46
120
|
def main(argv=None):
|
|
47
121
|
argv=list(sys.argv[1:] if argv is None else argv)
|
|
48
122
|
root=Path(os.environ.get('DPV2_PLUGIN_ROOT',str(Path.home()/'.ted/tedbrain/plugins/pdkadapt')))
|
|
@@ -90,15 +164,19 @@ def main(argv=None):
|
|
|
90
164
|
return show(code,envelope)
|
|
91
165
|
if argv and argv[0]=='login':
|
|
92
166
|
p=argparse.ArgumentParser();p.add_argument('login');p.add_argument('--stdin',action='store_true');a=p.parse_args(argv)
|
|
167
|
+
from .auth import ensure_session,save_session
|
|
168
|
+
origin=os.environ.get('DPV2_ORIGIN','https://tedbrain.com')
|
|
169
|
+
if not a.stdin:
|
|
170
|
+
from .auth import saved_credential
|
|
171
|
+
if saved_credential() is not None:
|
|
172
|
+
session=ensure_session(root,origin,lambda credential:exchange_session(root,credential),force=True)
|
|
173
|
+
print(json.dumps(dict(session,ok=True,reused_v1=True)));return 0
|
|
174
|
+
if not sys.stdin.isatty():raise ContractError('login required: no saved V1 vlink credential; use login --stdin')
|
|
93
175
|
credential=sys.stdin.readline().strip() if a.stdin else getpass.getpass('TedBrain invitation code: ')
|
|
94
|
-
code,envelope=
|
|
176
|
+
code,envelope=exchange_session(root,credential)
|
|
95
177
|
if code:return show(code,envelope)
|
|
96
|
-
|
|
97
|
-
|
|
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
|
|
178
|
+
session=save_session(root,envelope,origin)
|
|
179
|
+
print(json.dumps(dict(session,ok=True)));return 0
|
|
102
180
|
p=argparse.ArgumentParser(description='DPV2 pdkadapt plugin: asynchronous REST jobs')
|
|
103
181
|
p.add_argument('--version',action='version',version='pdkadapt plugin '+os.environ.get('DPV2_RELEASE_VERSION','0.1.0'))
|
|
104
182
|
p.add_argument('--action',choices=['check','start','status','resume','cancel','logs','source-preview','source-confirm','source-install','source-publish'],default='start')
|
|
@@ -123,6 +201,12 @@ def main(argv=None):
|
|
|
123
201
|
if not __import__('re').fullmatch(r'[A-Za-z0-9._-]{1,128}',key):p.error('invalid --request-id')
|
|
124
202
|
fields=['action','mode','vendor_dir','alias','foundry','arch','cells','run_id','from_step','layer_decision','layer_rule_decision','source_package','use_client_revision']
|
|
125
203
|
request={name:getattr(args,name) for name in fields}
|
|
204
|
+
if args.action=='check':
|
|
205
|
+
# Old check face: pure reuse/prerequisite query; DPV1 answers it with
|
|
206
|
+
# exit 0 regardless of the reuse verdict, and so does DPV2.
|
|
207
|
+
code,envelope=post_request(root,key,PREFIX+'/checks',request)
|
|
208
|
+
return show(0 if not code else code,envelope)
|
|
209
|
+
if args.action in SOURCE_ROUTES:return source_action(args,root,key)
|
|
126
210
|
if args.action=='start':
|
|
127
211
|
if not args.workstation_id:p.error('start requires --workstation-id')
|
|
128
212
|
path=PREFIX+'/jobs';body={'workstation_id':args.workstation_id,'request':request}
|
|
@@ -133,19 +217,8 @@ def main(argv=None):
|
|
|
133
217
|
if not args.run_id:p.error('cancel requires --run-id')
|
|
134
218
|
path=PREFIX+'/jobs/'+args.run_id+'/cancellations';body={}
|
|
135
219
|
else:
|
|
136
|
-
raise ContractError('
|
|
137
|
-
|
|
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)
|
|
220
|
+
raise ContractError('unsupported action for this request path')
|
|
221
|
+
code,envelope=post_request(root,key,path,body)
|
|
149
222
|
if code or not args.wait:return show(code,envelope)
|
|
150
223
|
body=envelope['body'];job=body['job_id']
|
|
151
224
|
print(json.dumps(body,ensure_ascii=False),flush=True)
|
|
@@ -197,3 +197,20 @@ class Jobs:
|
|
|
197
197
|
row=db.execute('SELECT job,attempt FROM requests WHERE subject=? AND key=?',(subject,key)).fetchone()
|
|
198
198
|
if row is None:raise NotFound('request not found')
|
|
199
199
|
return dict(self.get(subject,row['job']),submission_attempt=row['attempt'])
|
|
200
|
+
|
|
201
|
+
def latest_delivery(self,subject,alias):
|
|
202
|
+
"""Latest confirmed INSTALLED delivery this subject owns for the alias.
|
|
203
|
+
|
|
204
|
+
The old check action needs a reuse answer. DPV2 keeps server-side
|
|
205
|
+
cross-subject reuse closed, so the only honest reusable asset is this
|
|
206
|
+
subject's own completed adaptation history.
|
|
207
|
+
"""
|
|
208
|
+
with self.connection() as db:
|
|
209
|
+
rows=db.execute("SELECT * FROM jobs WHERE subject=? AND state='SUCCEEDED' ORDER BY updated DESC",(subject,)).fetchall()
|
|
210
|
+
for row in rows:
|
|
211
|
+
if json.loads(row['request']).get('alias')!=alias:continue
|
|
212
|
+
result=json.loads(row['result']) if row['result'] else None
|
|
213
|
+
delivery=(result or {}).get('delivery') or {}
|
|
214
|
+
if delivery.get('status')=='INSTALLED':
|
|
215
|
+
return dict(self.public(row),delivery=delivery)
|
|
216
|
+
return None
|
|
@@ -7,6 +7,14 @@ from pathlib import Path
|
|
|
7
7
|
import tarfile
|
|
8
8
|
from .installer import ContractError, relative, package_identity
|
|
9
9
|
|
|
10
|
+
# 1980-01-01T00:00:00Z: a fixed deterministic epoch above tar's plausibility
|
|
11
|
+
# threshold. Epoch-zero member stamps made GNU tar emit hundreds of
|
|
12
|
+
# "implausibly old time stamp" warnings during cold installs (I01728) while
|
|
13
|
+
# extraction itself succeeded; this constant keeps the bytes reproducible and
|
|
14
|
+
# stays within ustar/bsdtar/Windows-tar support. Already published npm
|
|
15
|
+
# versions are immutable and are never rebuilt with the new constant.
|
|
16
|
+
ARCHIVE_EPOCH = 315532800
|
|
17
|
+
|
|
10
18
|
|
|
11
19
|
def pack(directory, output, package, version, registry='https://registry.npmjs.org'):
|
|
12
20
|
directory=Path(directory);output=Path(output)
|
|
@@ -32,10 +40,10 @@ def pack(directory, output, package, version, registry='https://registry.npmjs.o
|
|
|
32
40
|
output.parent.mkdir(parents=True,exist_ok=True)
|
|
33
41
|
# Fixed tar/gzip timestamps make the artifact content reproducible.
|
|
34
42
|
import gzip
|
|
35
|
-
with output.open('wb') as stream, gzip.GzipFile(fileobj=stream,mode='wb',mtime=
|
|
43
|
+
with output.open('wb') as stream, gzip.GzipFile(fileobj=stream,mode='wb',mtime=ARCHIVE_EPOCH,filename='') as zipped:
|
|
36
44
|
with tarfile.open(fileobj=zipped,mode='w|') as tar:
|
|
37
45
|
for name,data in sorted(payload.items()):
|
|
38
|
-
member=tarfile.TarInfo('package/'+name);member.size=len(data);member.mtime=
|
|
46
|
+
member=tarfile.TarInfo('package/'+name);member.size=len(data);member.mtime=ARCHIVE_EPOCH
|
|
39
47
|
member.mode=0o755 if name in executables else 0o644
|
|
40
48
|
tar.addfile(member,io.BytesIO(data))
|
|
41
49
|
raw=output.read_bytes()
|
|
@@ -99,6 +99,39 @@ class Application:
|
|
|
99
99
|
def workstation(self,subject,identifier):
|
|
100
100
|
return self.workstations.get(subject,identifier)
|
|
101
101
|
|
|
102
|
+
def check(self,subject,request):
|
|
103
|
+
"""Old check face over DPV2's own durable history; never starts work.
|
|
104
|
+
|
|
105
|
+
DPV1 semantics kept where the state exists: REUSED needs the caller to
|
|
106
|
+
confirm the installed delivery digest via use_client_revision, because
|
|
107
|
+
DPV2 has no client back-channel to compare the vendor content itself.
|
|
108
|
+
"""
|
|
109
|
+
alias=request['alias'];mode=request['mode'];vendor=request.get('vendor_dir','')
|
|
110
|
+
found=self.jobs.latest_delivery(subject,alias)
|
|
111
|
+
if found is None:
|
|
112
|
+
if vendor:
|
|
113
|
+
return {'ok':False,'status':'ADAPTATION_REQUIRED','pdk_id':alias,'mode':mode,
|
|
114
|
+
'reuse_available':False,'adaptation_started':False,'next_action':'start_adaptation',
|
|
115
|
+
'message':'没有可复用的既有交付;请以提供的原始 PDK 目录发起新适配。'}
|
|
116
|
+
return {'ok':False,'status':'REUSE_DISABLED','pdk_id':alias,'mode':mode,'reuse_enabled':False,
|
|
117
|
+
'reuse_available':False,'adaptation_started':False,'next_action':'provide_vendor_directory',
|
|
118
|
+
'message':'DPV2 未启用公共工艺复用,也没有该账号的既有交付;请提供原始 PDK 目录进行适配。'}
|
|
119
|
+
delivery=found['delivery'];tree=delivery.get('tree_sha256','')
|
|
120
|
+
revision=request.get('use_client_revision','')
|
|
121
|
+
if tree and revision==tree:
|
|
122
|
+
return {'ok':True,'status':'REUSED','job_status':'REUSED','pdk_id':alias,'mode':mode,
|
|
123
|
+
'adaptation_started':False,'run_id':found['job_id'],'workstation_id':found['workstation_id'],
|
|
124
|
+
'origin':'dpv2-history','version':tree,'match_method':'client_revision','completed_mode':'full'}
|
|
125
|
+
if revision:
|
|
126
|
+
return {'ok':False,'status':'ADAPTATION_REQUIRED','pdk_id':alias,'mode':mode,'adaptation_started':False,
|
|
127
|
+
'previous_run_id':found['job_id'],
|
|
128
|
+
'message':'确认的安装摘要与既有 DPV2 交付不一致;请核实当前安装的交付摘要,或以原始 PDK 目录重新适配。'}
|
|
129
|
+
return {'ok':False,'status':'CLIENT_CONFIRMATION_REQUIRED','pdk_id':alias,'mode':mode,'adaptation_started':False,
|
|
130
|
+
'run_id':found['job_id'],'workstation_id':found['workstation_id'],'delivery_tree_sha256':tree,
|
|
131
|
+
'next_action':'confirm_revision_or_start_adaptation',
|
|
132
|
+
'message':'已有 DPV2 交付(run_id=%s)。请用 --use-client-revision 提交当前安装的交付摘要以确认复用,'
|
|
133
|
+
'或提供 --vendor-dir 重新适配。'%found['job_id']}
|
|
134
|
+
|
|
102
135
|
def worker(self):
|
|
103
136
|
if self.candidate:
|
|
104
137
|
release=self.config.get('candidate_worker')
|
|
@@ -152,8 +185,26 @@ class Application:
|
|
|
152
185
|
return 200,{'plugin':'pdkadapt','protocol_version':1,'worker_ready':worker is not None,
|
|
153
186
|
'workstation_proxy':self.config.get('transport',{}).get('public_proxy_url'),
|
|
154
187
|
'deployment_stage':'local-candidate' if self.candidate else 'release',
|
|
155
|
-
'actions':['start','status','resume','cancel'] if worker else ['status'],
|
|
188
|
+
'actions':['check','start','status','resume','cancel'] if worker else ['status'],
|
|
156
189
|
'default_start':'async','plugin_version':worker['version'] if worker else None}
|
|
190
|
+
if method=='POST' and route==PREFIX+'/checks':
|
|
191
|
+
if not isinstance(body,dict) or not isinstance(body.get('action'),str):
|
|
192
|
+
raise ContractError('check request required')
|
|
193
|
+
from .request_contract import validate_request
|
|
194
|
+
request=validate_request(body)
|
|
195
|
+
if request['action']!='check':raise ContractError('checks only accept action=check')
|
|
196
|
+
return 200,self.check(subject,request)
|
|
197
|
+
source=re.fullmatch(re.escape(PREFIX)+r'/sources/(previews|confirmations|installations|publications)',route)
|
|
198
|
+
if source and method=='POST':
|
|
199
|
+
if not isinstance(body,dict):raise ContractError('source request required')
|
|
200
|
+
# The shared source-reuse channel is a DPV1 reuse surface; DPV2
|
|
201
|
+
# keeps server-side reuse closed. The old action face stays mapped
|
|
202
|
+
# so callers get the defined structured status instead of a silent
|
|
203
|
+
# ignore or a fabricated success. Nothing is published or shared.
|
|
204
|
+
return 200,{'ok':False,'event':'tpdk_source','job_status':'FAILED','adaptation_started':False,
|
|
205
|
+
'error':{'code':'SOURCE_REUSE_UNAVAILABLE',
|
|
206
|
+
'message':'DPV2 未提供公共工艺源复用通道(服务器端工艺复用保持关闭);'
|
|
207
|
+
'请直接以 --action start --vendor-dir 发起新适配。'}}
|
|
157
208
|
if method=='POST' and route==PREFIX+'/jobs':
|
|
158
209
|
if not isinstance(body,dict) or set(body)!={'workstation_id','request'}:raise ContractError('workstation_id and request required')
|
|
159
210
|
self.workstation(subject,body['workstation_id']);worker=self.worker()
|
|
@@ -9,6 +9,7 @@ import fcntl
|
|
|
9
9
|
import json
|
|
10
10
|
import os
|
|
11
11
|
from pathlib import Path
|
|
12
|
+
import signal
|
|
12
13
|
import subprocess
|
|
13
14
|
import sys
|
|
14
15
|
import time
|
|
@@ -44,11 +45,49 @@ class Worker:
|
|
|
44
45
|
checkpoint_schema=result.get('checkpoint_schema'))
|
|
45
46
|
atomic(observed,canonical({'sha256':digest}))
|
|
46
47
|
return
|
|
47
|
-
if process.is_file() and live(loads(process.read_bytes())):
|
|
48
|
+
if process.is_file() and live(loads(process.read_bytes())):
|
|
49
|
+
if row['state']=='CANCELLING':
|
|
50
|
+
# Cooperative cancellation only fires between synchronous
|
|
51
|
+
# engine operations; a long EDA call never reaches those
|
|
52
|
+
# checks, so the supervisor escalates after the grace (I01769).
|
|
53
|
+
self._escalate_cancel(row,loads(process.read_bytes()))
|
|
54
|
+
return
|
|
48
55
|
if row['state']!='UNKNOWN':
|
|
49
56
|
self.jobs.complete(row['id'],row['attempt'],{'ok':False,'job_status':'UNKNOWN',
|
|
50
57
|
'error':{'code':'WORKER_OUTCOME_UNKNOWN','message':'Execution receipt unavailable; reconcile the original attempt'}},stopped=False)
|
|
51
58
|
|
|
59
|
+
def _escalate_cancel(self,row,process_row):
|
|
60
|
+
"""Terminate a CANCELLING engine group once the grace elapses.
|
|
61
|
+
|
|
62
|
+
``jobs.cancel`` timestamps the state change in ``updated``; the engine
|
|
63
|
+
keeps its cooperative window until then. SIGTERM, then SIGKILL the
|
|
64
|
+
whole session group (the engine owns its EDA children), and confirm
|
|
65
|
+
death before recording the receipt: the execution tree stopping is
|
|
66
|
+
the worker's own observation, never an assumption. A killed engine
|
|
67
|
+
leaves no trustworthy checkpoint, so the receipt carries
|
|
68
|
+
``checkpoint_schema=None`` and this attempt cannot be resumed.
|
|
69
|
+
"""
|
|
70
|
+
grace=float(self.config.get('cancel_grace_seconds',30))
|
|
71
|
+
if time.time()<row['updated']+grace:return
|
|
72
|
+
pid=process_row['pid']
|
|
73
|
+
self.jobs.append(row['id'],row['attempt'],{'event':'worker_cancel_escalation','pid':pid})
|
|
74
|
+
for name,delay in (('SIGTERM',float(self.config.get('cancel_term_seconds',10))),
|
|
75
|
+
('SIGKILL',5.0)):
|
|
76
|
+
try:os.killpg(pid,getattr(signal,name))
|
|
77
|
+
except ProcessLookupError:break
|
|
78
|
+
deadline=time.time()+delay
|
|
79
|
+
while time.time()<deadline and live(process_row):time.sleep(0.2)
|
|
80
|
+
if not live(process_row):break
|
|
81
|
+
if live(process_row):
|
|
82
|
+
# Termination unconfirmed: stay CANCELLING and retry on the next tick.
|
|
83
|
+
return
|
|
84
|
+
atomic(self.path(row)/'result.json',canonical({
|
|
85
|
+
'job_id':row['id'],'attempt':row['attempt'],'version':row['version'],
|
|
86
|
+
'result':{'ok':False,'job_status':'CANCELLED',
|
|
87
|
+
'error':{'code':'WORKER_CANCEL_TERMINATED',
|
|
88
|
+
'message':'Engine process group terminated after the cancellation grace; the local execution tree is confirmed stopped'}},
|
|
89
|
+
'remote_stop_confirmed':True,'checkpoint_schema':None}))
|
|
90
|
+
|
|
52
91
|
def launch(self, row):
|
|
53
92
|
directory=self.path(row)
|
|
54
93
|
# Exclusive creation is a second guard after the DB claim. Existing
|