fix(cms-deploy): resolve base from scoped image ancestry
This commit is contained in:
@@ -17,8 +17,10 @@ individual differing Env values were not recorded, so no exact Node version
|
||||
transition is claimed. An application release must preserve its accepted base,
|
||||
not silently update the Node image selected by a mutable local tag.
|
||||
|
||||
The corrected read-only preflight inspects the accepted image by immutable ID
|
||||
and a bounded local image inventory. It selects exactly one Node 24 base whose
|
||||
The initial correction inspected the accepted image by immutable ID and a
|
||||
bounded global local-image inventory. That lookup was rejected by the NAS in
|
||||
r41 preflight; it is superseded by the [scoped base discovery](R41_BASE_DISCOVERY.md).
|
||||
The current read-only preflight selects a Node 24 base whose
|
||||
complete root filesystem layers form a strict prefix of the accepted image,
|
||||
and whose environment plus the registered HOST/PORT instructions exactly equals
|
||||
the accepted image environment. Entrypoint, user, shell, labels, stop signal and
|
||||
@@ -50,6 +52,7 @@ all exported layers for the excluded private-project fixture and removes its
|
||||
own image tags. It verifies the build mechanism, not NAS cache availability;
|
||||
the production preflight remains authoritative for that.
|
||||
|
||||
Promotion is the separate root-owned runner gate. After verify-install,
|
||||
release a new CMS commit through the existing Git pipeline; no bootstrap,
|
||||
reconciliation replay or manual container command is needed.
|
||||
Promotion is the separate root-owned runner gate. r41 is the new CMS commit
|
||||
released after this correction; it remains staged, before application apply.
|
||||
The discovery correction resumes that queued run after runner promotion;
|
||||
no bootstrap, reconciliation replay or manual container command is needed.
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# CMS r41: scoped, immutable base discovery
|
||||
|
||||
On 2026-11-05 the operator verified installed runner SHA
|
||||
`73938104fcd004f028a52f5c4f46bf68af0712e25a828f014cb141af93745d26`.
|
||||
Canonical plan for r41 stopped with
|
||||
`CMS local base image inventory is invalid or outside bounds`.
|
||||
The old guard combined empty inventory, more than 2048 unique IDs and invalid
|
||||
ID formatting into that message. The actual NAS inventory was not captured;
|
||||
there is no claim that a particular count or malformed line caused the failure.
|
||||
The prior controller status also recorded TimeoutExpired, without its source.
|
||||
|
||||
r41 source is `4369f0a0cb813075e10ac917da62529420559f69`, Gitea run 41/number 3.
|
||||
Artifact `nodedc-dc-cms-release-v1-r41-4369f0a0cb813075e10ac917da62529420559f69.tgz`
|
||||
is 99102 bytes, SHA-256
|
||||
`576fd0c07fb35a1803a56e665b25b06628ce41137bc2ac954a0c801179f57a77`.
|
||||
Qualification passed and all payload bytes match the committed source.
|
||||
The lifecycle inspector still reports staged, no applied/failed record or
|
||||
backup, matching SHA, no warnings. r41 has not entered application apply.
|
||||
|
||||
The global inventory is removed. The new resolver first follows immutable
|
||||
Parent IDs from the accepted CMS image, including untagged legacy ancestors.
|
||||
Every edge must retain platform and a root-filesystem layer prefix; metadata
|
||||
steps with equal layers are allowed. Invalid IDs, cycles, inconsistent layers
|
||||
or platform, and depth beyond 128 edges stop safely. The nearest proven Node
|
||||
base must pass all existing configuration and filesystem checks; a Parent
|
||||
pointer alone is insufficient.
|
||||
|
||||
For images without a usable Parent chain, the fallback lists only local Node
|
||||
repository references (`node:*`, `docker.io/library/node:*`), using explicit
|
||||
`{{json .ID}}` formatting and full IDs. At most 256 rows are admitted. Each
|
||||
candidate is inspected by immutable ID and re-proved against the accepted CMS
|
||||
image; exactly one match is required. Tags are discovery hints, not authority.
|
||||
A base absent from both paths fails before mutation. No global inventory,
|
||||
prune, pull, base reconstruction or use of the old full application as a base.
|
||||
|
||||
CMS base-discovery reads have 30-second subprocess timeouts and an 8 MiB output
|
||||
ceiling. Failures expose only allowlisted `cms-base-*` reason codes in the
|
||||
public controller projection. Docker stderr, environment values, command
|
||||
arguments and arbitrary DeployError messages are not copied into that status.
|
||||
Runtime comparison, service scope, release identity, rollback, queue ordering,
|
||||
source qualification, Device Core and the build recipe remain unchanged.
|
||||
|
||||
Validation: 93 CMS tests and 95 Device Core regression tests passed. Tests
|
||||
cover untagged parent ancestry without listing, metadata steps, cycles, depth,
|
||||
platform/layer mismatch, mutable tag drift, absent/ambiguous fallback, invalid
|
||||
IDs, inventory bounds, timeouts and redacted status. A real local Docker
|
||||
integration exercised the Parent chain and explicit JSON Node-only filter
|
||||
(an inspect fixture cleared Parent to model that path), then built from the
|
||||
same proved base. Exact inherited configuration and clean exported layers
|
||||
passed. Only isolated local test tags were created and removed; no NAS or
|
||||
workload containers were used. This does not prove NAS base availability.
|
||||
|
||||
After atomic root runner promotion and verify-install, the existing controller
|
||||
performs a fresh canonical plan and apply for the queued r41. The corrected
|
||||
runner is a relevant external-state change; no application artifact is changed
|
||||
or restaged. r39/r40 and bootstrap/reconciliation remain terminal and must not
|
||||
be replayed. An actual canonical application receipt is still required before
|
||||
multisite migration and public-site publication.
|
||||
@@ -61,5 +61,9 @@ The separate `dc-cms-runtime-reconciliation` marker transition re-proves that
|
||||
exact legacy hash on NAS before releasing the r39 barrier. It never retries r39.
|
||||
Reconciliation was accepted at 2026-11-04T20:28:35Z. The next qualified run r40
|
||||
failed only `config.Env`; its automatic rollback passed completely. r40 is also
|
||||
terminal and must not be replayed. The build-base correction requires a new
|
||||
runner promotion followed by a new CMS commit/run, without another bootstrap.
|
||||
terminal and must not be replayed. The new r41 commit qualified and staged,
|
||||
but the original global image lookup was rejected during preflight. The
|
||||
[scoped discovery correction](R41_BASE_DISCOVERY.md) follows CMS image ancestry,
|
||||
with a bounded Node-only cache fallback and safe public error codes. After
|
||||
runner promotion the controller may resume staged r41 with a fresh plan;
|
||||
no bootstrap or failed-release replay is needed.
|
||||
|
||||
@@ -312,6 +312,16 @@ def cms_autodeploy_publish_status(result):
|
||||
print('cms_autodeploy_tick=' + json.dumps(result, sort_keys=True))
|
||||
|
||||
|
||||
def cms_autodeploy_error_status(error, policy_errors):
|
||||
result={'status':'attention','errorType':type(error).__name__}
|
||||
if isinstance(error,policy_errors):result['reason']=str(error)[:200]
|
||||
# Only fixed CMS codes are added. External stderr/raw exception text stays
|
||||
# private, even if a caller mutates the exception's message or code.
|
||||
if isinstance(error,CmsBuildBaseError) and error.code in CMS_BUILD_BASE_ERROR_CODES:
|
||||
result['reason']=error.code
|
||||
return result
|
||||
|
||||
|
||||
def cms_autodeploy_tick():
|
||||
require_root()
|
||||
ensure_layout()
|
||||
@@ -339,10 +349,7 @@ def cms_autodeploy_tick():
|
||||
try:
|
||||
result = Controller(queue,Source(token,runner_id=cms_ci_registered_runner_id()),CmsAutodeployInstaller()).tick()
|
||||
except Exception as error:
|
||||
result = {'status':'attention','errorType':type(error).__name__}
|
||||
# Policy errors contain only fixed codes/IDs; other exception text
|
||||
# can originate in external tools and is never copied to status.
|
||||
if isinstance(error,errors):result['reason']=str(error)[:200]
|
||||
result = cms_autodeploy_error_status(error,errors)
|
||||
finally:
|
||||
queue.close()
|
||||
cms_autodeploy_publish_status(result)
|
||||
|
||||
@@ -177,12 +177,47 @@ def cms_image_env(config):
|
||||
return result
|
||||
|
||||
|
||||
CMS_BUILD_BASE_ERROR_CODES = frozenset((
|
||||
'cms-base-docker-timeout','cms-base-docker-unavailable','cms-base-docker-failed',
|
||||
'cms-base-json-invalid','cms-base-output-limit','cms-base-image-mismatch',
|
||||
'cms-base-parent-invalid','cms-base-parent-cycle','cms-base-parent-depth',
|
||||
'cms-base-parent-layers','cms-base-parent-platform','cms-base-inventory-format',
|
||||
'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous',
|
||||
))
|
||||
|
||||
|
||||
class CmsBuildBaseError(DeployError):
|
||||
def __init__(self, code):
|
||||
if code not in CMS_BUILD_BASE_ERROR_CODES:
|
||||
raise ValueError('Unknown CMS base error code')
|
||||
self.code=code
|
||||
super().__init__(code)
|
||||
|
||||
|
||||
def cms_base_docker_json(args, *, lines=False):
|
||||
# CMS-only bounded read. Neither Docker stderr nor image Env is public.
|
||||
try:
|
||||
proc=subprocess.run([str(DOCKER),*args],capture_output=True,text=True,check=True,timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise CmsBuildBaseError('cms-base-docker-timeout') from None
|
||||
except subprocess.CalledProcessError:
|
||||
raise CmsBuildBaseError('cms-base-docker-failed') from None
|
||||
except (OSError,UnicodeError):
|
||||
raise CmsBuildBaseError('cms-base-docker-unavailable') from None
|
||||
if len(proc.stdout)>8*1024*1024:
|
||||
raise CmsBuildBaseError('cms-base-output-limit')
|
||||
try:
|
||||
return [json.loads(line) for line in proc.stdout.splitlines()] if lines else json.loads(proc.stdout)
|
||||
except (ValueError,TypeError):
|
||||
raise CmsBuildBaseError('cms-base-json-invalid') from None
|
||||
|
||||
|
||||
def cms_inspect_image(identity):
|
||||
if not re.fullmatch('sha256:[a-f0-9]{64}',str(identity)):
|
||||
die('CMS immutable image identity is invalid')
|
||||
rows=docker_json(['image','inspect',identity],'CMS immutable image')
|
||||
if not isinstance(rows,list) or len(rows)!=1 or rows[0].get('Id')!=identity:
|
||||
die('CMS immutable image inspection mismatch')
|
||||
rows=cms_base_docker_json(['image','inspect',identity])
|
||||
if not isinstance(rows,list) or len(rows)!=1 or not isinstance(rows[0],dict) or rows[0].get('Id')!=identity:
|
||||
raise CmsBuildBaseError('cms-base-image-mismatch')
|
||||
return rows[0]
|
||||
|
||||
|
||||
@@ -217,26 +252,52 @@ def cms_node_base_matches(image, accepted):
|
||||
|
||||
def cms_resolve_build_base(runtime):
|
||||
accepted=cms_inspect_image(runtime['imageId'])
|
||||
proc=subprocess.run([str(DOCKER),'image','ls','--all','--quiet','--no-trunc'],
|
||||
capture_output=True,text=True,check=True,timeout=30)
|
||||
identities=sorted(set(proc.stdout.split()))
|
||||
if not 1<=len(identities)<=2048 or any(not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in identities):
|
||||
die('CMS local base image inventory is invalid or outside bounds')
|
||||
matches=[]
|
||||
for start in range(0,len(identities),64):
|
||||
batch=identities[start:start+64]
|
||||
images=docker_json(['image','inspect',*batch],'CMS local base inventory')
|
||||
if not isinstance(images,list) or sorted(image.get('Id','') for image in images)!=batch:
|
||||
die('CMS local base inventory changed during inspection')
|
||||
for image in images:
|
||||
# Legacy builds retain immutable Parent edges, including untagged bases.
|
||||
# Follow this app's ancestry, never enumerate another component's cache.
|
||||
current=accepted;seen={accepted['Id']};base=None
|
||||
for depth in range(128):
|
||||
parent=current.get('Parent')
|
||||
if parent in ('',None):break
|
||||
if not re.fullmatch('sha256:[a-f0-9]{64}',str(parent)):
|
||||
raise CmsBuildBaseError('cms-base-parent-invalid')
|
||||
if parent in seen:raise CmsBuildBaseError('cms-base-parent-cycle')
|
||||
seen.add(parent);image=cms_inspect_image(parent)
|
||||
layers=(image.get('RootFS') or {}).get('Layers')
|
||||
child=(current.get('RootFS') or {}).get('Layers')
|
||||
if ((image.get('RootFS') or {}).get('Type')!='layers'
|
||||
or (current.get('RootFS') or {}).get('Type')!='layers'
|
||||
or not isinstance(layers,list) or not isinstance(child,list)
|
||||
or len(layers)>len(child) or child[:len(layers)]!=layers
|
||||
or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in child)):
|
||||
raise CmsBuildBaseError('cms-base-parent-layers')
|
||||
if any(image.get(k)!=current.get(k) for k in ('Os','Architecture','Variant')):
|
||||
raise CmsBuildBaseError('cms-base-parent-platform')
|
||||
if cms_node_base_matches(image,accepted):
|
||||
base=image;break
|
||||
current=image
|
||||
else:
|
||||
raise CmsBuildBaseError('cms-base-parent-depth')
|
||||
method='parent-chain'
|
||||
if base is None:
|
||||
# BuildKit/pulled images may have no Parent. Only inspect local official
|
||||
# Node repository candidates; a tag never substitutes for ancestry proof.
|
||||
rows=cms_base_docker_json(['image','ls','--all','--no-trunc',
|
||||
'--filter','reference=node:*','--filter','reference=docker.io/library/node:*',
|
||||
'--format','{{json .ID}}'],lines=True)
|
||||
if len(rows)>256:raise CmsBuildBaseError('cms-base-inventory-limit')
|
||||
if any(not isinstance(v,str) or not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in rows):
|
||||
raise CmsBuildBaseError('cms-base-inventory-format')
|
||||
matches=[]
|
||||
for identity in sorted(set(rows)):
|
||||
image=cms_inspect_image(identity)
|
||||
if cms_node_base_matches(image,accepted):matches.append(image)
|
||||
if len(matches)!=1:
|
||||
die('CMS exact cached Node base is missing or ambiguous; no image pull or runtime change permitted')
|
||||
base=matches[0]
|
||||
if not matches:raise CmsBuildBaseError('cms-base-missing')
|
||||
if len(matches)!=1:raise CmsBuildBaseError('cms-base-ambiguous')
|
||||
base=matches[0];method='node-cache'
|
||||
proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'],
|
||||
'layersSha256':cms_audit_digest(base['RootFS']['Layers']),
|
||||
'configSha256':cms_audit_digest(base['Config'])}
|
||||
print('cms_build_base=accepted-image-ancestor;immutable-id='+base['Id']+';pull=never')
|
||||
print('cms_build_base=accepted-image-ancestor;lookup='+method+';immutable-id='+base['Id']+';pull=never')
|
||||
return proof
|
||||
|
||||
|
||||
|
||||
@@ -51,20 +51,90 @@ class CmsBuildBaseTests(unittest.TestCase):
|
||||
with self.assertRaises(r.DeployError) as error:r.cms_image_env({'Env':env})
|
||||
self.assertNotIn('private-fixture',str(error.exception))
|
||||
|
||||
def test_resolver_ignores_mutable_tag_and_rejects_missing_or_ambiguous_base(self):
|
||||
def test_parent_chain_finds_untagged_base_without_global_inventory(self):
|
||||
base,old=images();middle=copy.deepcopy(old);middle['Id']='sha256:'+'c'*64
|
||||
old['Parent']=middle['Id'];middle['Parent']=base['Id']
|
||||
inventory={i['Id']:i for i in (base,old,middle)}
|
||||
with patch.object(r,'cms_inspect_image',side_effect=inventory.__getitem__) as inspect,patch.object(r,'cms_base_docker_json') as listing,redirect_stdout(io.StringIO()) as output:
|
||||
self.assertEqual(r.cms_resolve_build_base({'imageId':old['Id']}),proof(base,old))
|
||||
self.assertEqual(inspect.call_count,3);listing.assert_not_called()
|
||||
self.assertIn('lookup=parent-chain',output.getvalue())
|
||||
self.assertNotIn('PATH=',output.getvalue())
|
||||
|
||||
def test_parent_chain_rejects_cycles_invalid_edges_and_depth(self):
|
||||
base,old=images()
|
||||
for code,alter in [
|
||||
('parent-invalid',lambda b,o:o.update(Parent='latest')),
|
||||
('parent-cycle',lambda b,o:o.update(Parent=o['Id'])),
|
||||
('parent-layers',lambda b,o:b['RootFS']['Layers'].reverse()),
|
||||
('parent-platform',lambda b,o:b.update(Architecture='arm64')),
|
||||
]:
|
||||
b,o=copy.deepcopy(base),copy.deepcopy(old);o['Parent']=b['Id'];alter(b,o)
|
||||
inventory={i['Id']:i for i in (b,o)}
|
||||
with self.subTest(code=code),patch.object(r,'cms_inspect_image',side_effect=inventory.__getitem__),patch.object(r,'cms_base_docker_json') as listing:
|
||||
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code):r.cms_resolve_build_base({'imageId':o['Id']})
|
||||
listing.assert_not_called()
|
||||
chain=[]
|
||||
for i in range(130):
|
||||
item=copy.deepcopy(old);item['Id']='sha256:'+format(i,'064x');item['Parent']='sha256:'+format(i+1,'064x');chain.append(item)
|
||||
with patch.object(r,'cms_inspect_image',side_effect={i['Id']:i for i in chain}.__getitem__):
|
||||
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-parent-depth'):r.cms_resolve_build_base({'imageId':chain[0]['Id']})
|
||||
|
||||
def test_node_cache_fallback_ignores_mutable_tag_and_rejects_missing_or_ambiguous_base(self):
|
||||
base,old=images();latest=copy.deepcopy(base);latest['Id']='sha256:'+'c'*64
|
||||
latest['Config']['Env'][1]='NODE_VERSION=24.19.0'
|
||||
latest['RootFS']['Layers'][1]='sha256:'+'4'*64
|
||||
latest['RepoTags']=['node:24-alpine']
|
||||
for inventory,success in [([latest,base,old],True),([latest,old],False),([latest,base,old,{**base,'Id':'sha256:'+'d'*64}],False)]:
|
||||
listing=type('Result',(),{'stdout':'\n'.join(i['Id'] for i in inventory)})()
|
||||
with patch.object(r,'cms_inspect_image',return_value=old),patch.object(r.subprocess,'run',return_value=listing) as run,patch.object(r,'docker_json',return_value=inventory),redirect_stdout(io.StringIO()) as output:
|
||||
by_id={i['Id']:i for i in inventory}
|
||||
with patch.object(r,'cms_inspect_image',side_effect=by_id.__getitem__),patch.object(r,'cms_base_docker_json',return_value=list(by_id)) as run,redirect_stdout(io.StringIO()) as output:
|
||||
if success:self.assertEqual(r.cms_resolve_build_base({'imageId':old['Id']}),proof(base,old))
|
||||
else:
|
||||
with self.assertRaises(r.DeployError):r.cms_resolve_build_base({'imageId':old['Id']})
|
||||
self.assertEqual(run.call_args.args[0],[str(r.DOCKER),'image','ls','--all','--quiet','--no-trunc'])
|
||||
self.assertEqual(run.call_args.args[0],['image','ls','--all','--no-trunc','--filter','reference=node:*','--filter','reference=docker.io/library/node:*','--format','{{json .ID}}'])
|
||||
self.assertEqual(run.call_args.kwargs,{'lines':True})
|
||||
self.assertNotIn('PATH=',output.getvalue())
|
||||
|
||||
def test_inventory_rejects_short_ids_malformed_values_and_excess_before_inspect(self):
|
||||
base,old=images()
|
||||
for rows,code in [(['abcdef123456'],'format'),([{}],'format'),([None],'format'),([base['Id']]*257,'limit')]:
|
||||
with self.subTest(code=code,rows=len(rows)),patch.object(r,'cms_inspect_image',return_value=old) as inspect,patch.object(r,'cms_base_docker_json',return_value=rows):
|
||||
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-inventory-'+code):r.cms_resolve_build_base({'imageId':old['Id']})
|
||||
inspect.assert_called_once_with(old['Id'])
|
||||
|
||||
def test_docker_reads_are_bounded_and_external_errors_are_redacted(self):
|
||||
for error,code in [
|
||||
(r.subprocess.TimeoutExpired(['docker','private-fixture'],30,stderr='secret-fixture'),'docker-timeout'),
|
||||
(r.subprocess.CalledProcessError(1,['docker'],stderr='secret-fixture'),'docker-failed'),
|
||||
(OSError('secret-fixture'),'docker-unavailable'),
|
||||
]:
|
||||
with patch.object(r.subprocess,'run',side_effect=error) as run:
|
||||
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code) as caught:r.cms_base_docker_json(['image','inspect','fixture'])
|
||||
self.assertNotIn('secret-fixture',str(caught.exception));self.assertEqual(run.call_args.kwargs['timeout'],30)
|
||||
for value,lines,expected in [('[]',False,[]),('"sha256:abc"\n',True,['sha256:abc']),('',True,[])]:
|
||||
with patch.object(r.subprocess,'run',return_value=type('Result',(),{'stdout':value})()):
|
||||
self.assertEqual(r.cms_base_docker_json(['fixture'],lines=lines),expected)
|
||||
for value,code in [('secret-fixture','json-invalid'),('x'*(8*1024*1024+1),'output-limit')]:
|
||||
with patch.object(r.subprocess,'run',return_value=type('Result',(),{'stdout':value})()):
|
||||
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-'+code):r.cms_base_docker_json(['fixture'])
|
||||
|
||||
def test_image_inspection_requires_exact_immutable_identity(self):
|
||||
base,old=images()
|
||||
for rows in [[old],[],[base,base],[None],{}]:
|
||||
with patch.object(r,'cms_base_docker_json',return_value=rows):
|
||||
with self.assertRaisesRegex(r.CmsBuildBaseError,'cms-base-image-mismatch'):r.cms_inspect_image(base['Id'])
|
||||
with patch.object(r,'cms_base_docker_json',return_value=[base]):self.assertEqual(r.cms_inspect_image(base['Id']),base)
|
||||
|
||||
def test_public_status_contains_only_allowlisted_base_codes(self):
|
||||
error=r.CmsBuildBaseError('cms-base-missing');error.args=('secret-fixture',)
|
||||
self.assertEqual(r.cms_autodeploy_error_status(error,())['reason'],'cms-base-missing')
|
||||
error.code='secret-fixture'
|
||||
self.assertNotIn('reason',r.cms_autodeploy_error_status(error,()))
|
||||
for error in [r.DeployError('secret-fixture'),r.subprocess.TimeoutExpired(['private-fixture'],30)]:
|
||||
result=r.cms_autodeploy_error_status(error,())
|
||||
self.assertNotIn('reason',result);self.assertNotIn('fixture',json.dumps(result))
|
||||
with self.assertRaises(ValueError):r.CmsBuildBaseError('secret-fixture')
|
||||
|
||||
def test_build_pins_only_clean_temporary_recipe_and_rejects_drift_before_recreation(self):
|
||||
base,old=images()
|
||||
for drift in [False,True]:
|
||||
|
||||
@@ -43136,12 +43136,47 @@ def cms_image_env(config):
|
||||
return result
|
||||
|
||||
|
||||
CMS_BUILD_BASE_ERROR_CODES = frozenset((
|
||||
'cms-base-docker-timeout','cms-base-docker-unavailable','cms-base-docker-failed',
|
||||
'cms-base-json-invalid','cms-base-output-limit','cms-base-image-mismatch',
|
||||
'cms-base-parent-invalid','cms-base-parent-cycle','cms-base-parent-depth',
|
||||
'cms-base-parent-layers','cms-base-parent-platform','cms-base-inventory-format',
|
||||
'cms-base-inventory-limit','cms-base-missing','cms-base-ambiguous',
|
||||
))
|
||||
|
||||
|
||||
class CmsBuildBaseError(DeployError):
|
||||
def __init__(self, code):
|
||||
if code not in CMS_BUILD_BASE_ERROR_CODES:
|
||||
raise ValueError('Unknown CMS base error code')
|
||||
self.code=code
|
||||
super().__init__(code)
|
||||
|
||||
|
||||
def cms_base_docker_json(args, *, lines=False):
|
||||
# CMS-only bounded read. Neither Docker stderr nor image Env is public.
|
||||
try:
|
||||
proc=subprocess.run([str(DOCKER),*args],capture_output=True,text=True,check=True,timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise CmsBuildBaseError('cms-base-docker-timeout') from None
|
||||
except subprocess.CalledProcessError:
|
||||
raise CmsBuildBaseError('cms-base-docker-failed') from None
|
||||
except (OSError,UnicodeError):
|
||||
raise CmsBuildBaseError('cms-base-docker-unavailable') from None
|
||||
if len(proc.stdout)>8*1024*1024:
|
||||
raise CmsBuildBaseError('cms-base-output-limit')
|
||||
try:
|
||||
return [json.loads(line) for line in proc.stdout.splitlines()] if lines else json.loads(proc.stdout)
|
||||
except (ValueError,TypeError):
|
||||
raise CmsBuildBaseError('cms-base-json-invalid') from None
|
||||
|
||||
|
||||
def cms_inspect_image(identity):
|
||||
if not re.fullmatch('sha256:[a-f0-9]{64}',str(identity)):
|
||||
die('CMS immutable image identity is invalid')
|
||||
rows=docker_json(['image','inspect',identity],'CMS immutable image')
|
||||
if not isinstance(rows,list) or len(rows)!=1 or rows[0].get('Id')!=identity:
|
||||
die('CMS immutable image inspection mismatch')
|
||||
rows=cms_base_docker_json(['image','inspect',identity])
|
||||
if not isinstance(rows,list) or len(rows)!=1 or not isinstance(rows[0],dict) or rows[0].get('Id')!=identity:
|
||||
raise CmsBuildBaseError('cms-base-image-mismatch')
|
||||
return rows[0]
|
||||
|
||||
|
||||
@@ -43176,26 +43211,52 @@ def cms_node_base_matches(image, accepted):
|
||||
|
||||
def cms_resolve_build_base(runtime):
|
||||
accepted=cms_inspect_image(runtime['imageId'])
|
||||
proc=subprocess.run([str(DOCKER),'image','ls','--all','--quiet','--no-trunc'],
|
||||
capture_output=True,text=True,check=True,timeout=30)
|
||||
identities=sorted(set(proc.stdout.split()))
|
||||
if not 1<=len(identities)<=2048 or any(not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in identities):
|
||||
die('CMS local base image inventory is invalid or outside bounds')
|
||||
matches=[]
|
||||
for start in range(0,len(identities),64):
|
||||
batch=identities[start:start+64]
|
||||
images=docker_json(['image','inspect',*batch],'CMS local base inventory')
|
||||
if not isinstance(images,list) or sorted(image.get('Id','') for image in images)!=batch:
|
||||
die('CMS local base inventory changed during inspection')
|
||||
for image in images:
|
||||
# Legacy builds retain immutable Parent edges, including untagged bases.
|
||||
# Follow this app's ancestry, never enumerate another component's cache.
|
||||
current=accepted;seen={accepted['Id']};base=None
|
||||
for depth in range(128):
|
||||
parent=current.get('Parent')
|
||||
if parent in ('',None):break
|
||||
if not re.fullmatch('sha256:[a-f0-9]{64}',str(parent)):
|
||||
raise CmsBuildBaseError('cms-base-parent-invalid')
|
||||
if parent in seen:raise CmsBuildBaseError('cms-base-parent-cycle')
|
||||
seen.add(parent);image=cms_inspect_image(parent)
|
||||
layers=(image.get('RootFS') or {}).get('Layers')
|
||||
child=(current.get('RootFS') or {}).get('Layers')
|
||||
if ((image.get('RootFS') or {}).get('Type')!='layers'
|
||||
or (current.get('RootFS') or {}).get('Type')!='layers'
|
||||
or not isinstance(layers,list) or not isinstance(child,list)
|
||||
or len(layers)>len(child) or child[:len(layers)]!=layers
|
||||
or any(not re.fullmatch('sha256:[a-f0-9]{64}',str(v)) for v in child)):
|
||||
raise CmsBuildBaseError('cms-base-parent-layers')
|
||||
if any(image.get(k)!=current.get(k) for k in ('Os','Architecture','Variant')):
|
||||
raise CmsBuildBaseError('cms-base-parent-platform')
|
||||
if cms_node_base_matches(image,accepted):
|
||||
base=image;break
|
||||
current=image
|
||||
else:
|
||||
raise CmsBuildBaseError('cms-base-parent-depth')
|
||||
method='parent-chain'
|
||||
if base is None:
|
||||
# BuildKit/pulled images may have no Parent. Only inspect local official
|
||||
# Node repository candidates; a tag never substitutes for ancestry proof.
|
||||
rows=cms_base_docker_json(['image','ls','--all','--no-trunc',
|
||||
'--filter','reference=node:*','--filter','reference=docker.io/library/node:*',
|
||||
'--format','{{json .ID}}'],lines=True)
|
||||
if len(rows)>256:raise CmsBuildBaseError('cms-base-inventory-limit')
|
||||
if any(not isinstance(v,str) or not re.fullmatch('sha256:[a-f0-9]{64}',v) for v in rows):
|
||||
raise CmsBuildBaseError('cms-base-inventory-format')
|
||||
matches=[]
|
||||
for identity in sorted(set(rows)):
|
||||
image=cms_inspect_image(identity)
|
||||
if cms_node_base_matches(image,accepted):matches.append(image)
|
||||
if len(matches)!=1:
|
||||
die('CMS exact cached Node base is missing or ambiguous; no image pull or runtime change permitted')
|
||||
base=matches[0]
|
||||
if not matches:raise CmsBuildBaseError('cms-base-missing')
|
||||
if len(matches)!=1:raise CmsBuildBaseError('cms-base-ambiguous')
|
||||
base=matches[0];method='node-cache'
|
||||
proof={'imageId':base['Id'],'acceptedImageId':accepted['Id'],
|
||||
'layersSha256':cms_audit_digest(base['RootFS']['Layers']),
|
||||
'configSha256':cms_audit_digest(base['Config'])}
|
||||
print('cms_build_base=accepted-image-ancestor;immutable-id='+base['Id']+';pull=never')
|
||||
print('cms_build_base=accepted-image-ancestor;lookup='+method+';immutable-id='+base['Id']+';pull=never')
|
||||
return proof
|
||||
|
||||
|
||||
@@ -43968,6 +44029,16 @@ def cms_autodeploy_publish_status(result):
|
||||
print('cms_autodeploy_tick=' + json.dumps(result, sort_keys=True))
|
||||
|
||||
|
||||
def cms_autodeploy_error_status(error, policy_errors):
|
||||
result={'status':'attention','errorType':type(error).__name__}
|
||||
if isinstance(error,policy_errors):result['reason']=str(error)[:200]
|
||||
# Only fixed CMS codes are added. External stderr/raw exception text stays
|
||||
# private, even if a caller mutates the exception's message or code.
|
||||
if isinstance(error,CmsBuildBaseError) and error.code in CMS_BUILD_BASE_ERROR_CODES:
|
||||
result['reason']=error.code
|
||||
return result
|
||||
|
||||
|
||||
def cms_autodeploy_tick():
|
||||
require_root()
|
||||
ensure_layout()
|
||||
@@ -43995,10 +44066,7 @@ def cms_autodeploy_tick():
|
||||
try:
|
||||
result = Controller(queue,Source(token,runner_id=cms_ci_registered_runner_id()),CmsAutodeployInstaller()).tick()
|
||||
except Exception as error:
|
||||
result = {'status':'attention','errorType':type(error).__name__}
|
||||
# Policy errors contain only fixed codes/IDs; other exception text
|
||||
# can originate in external tools and is never copied to status.
|
||||
if isinstance(error,errors):result['reason']=str(error)[:200]
|
||||
result = cms_autodeploy_error_status(error,errors)
|
||||
finally:
|
||||
queue.close()
|
||||
cms_autodeploy_publish_status(result)
|
||||
|
||||
Reference in New Issue
Block a user