gowalk-cicd 1.0.227 → 1.0.228

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.
@@ -18,7 +18,7 @@ ROOT_UID = 0
18
18
  REQUIRED = (
19
19
  'ssh_gate.py', 'native_profile.py', 'native_deploy.py', 'runtime_host.py', 'runtime_launch.py',
20
20
  'runtime_model.py', 'runtime_healthcheck.py', 'runtime_image_health.py', 'runtime_readback.py',
21
- 'runtime_projection.py',
21
+ 'runtime_projection.py', 'runtime_lifecycle.py',
22
22
  'identity_diagnostics.py',
23
23
  'health_rollout.py', 'health_rollout_engine.py', 'health_rollout_spec.py', 'health_rollout_credit.py',
24
24
  'health_rollout_timing.py',
@@ -13,6 +13,7 @@ from native_profile import APPS, load_profile, model, unit_properties
13
13
  from runtime_host import admit, host_facts, running_containers, start_lock
14
14
  from runtime_launch import START_LOCK
15
15
  from runtime_model import duration
16
+ from runtime_lifecycle import require_active
16
17
 
17
18
 
18
19
  def run(arguments, timeout=60):
@@ -97,6 +98,7 @@ def health(profile):
97
98
 
98
99
 
99
100
  def deploy(app):
101
+ require_active(app)
100
102
  profile = load_profile(app)
101
103
  if profile['disabled']:
102
104
  raise ValueError('native_disabled')
@@ -107,6 +109,7 @@ def deploy(app):
107
109
  sync_source(app, profile)
108
110
  install(app, profile)
109
111
  with start_lock(START_LOCK):
112
+ require_active(app)
110
113
  # Re-read the host's freeze after preparation and immediately before start.
111
114
  if load_profile(app) != profile:
112
115
  raise ValueError('native_profile_changed')
@@ -10,6 +10,7 @@ from pathlib import Path
10
10
  from runtime_host import admit, host_facts, running_containers, start_lock
11
11
  from runtime_image_health import inherit_healthchecks
12
12
  from runtime_model import configure
13
+ from runtime_lifecycle import require_active
13
14
 
14
15
  PROFILE_ROOT = Path("/opt/gowalk-backend-runtime")
15
16
  START_LOCK = Path("/run/lock/gowalk-backend-start.lock")
@@ -30,6 +31,7 @@ def compose_model(app, arguments):
30
31
 
31
32
 
32
33
  def launch(app, arguments):
34
+ require_active(app)
33
35
  original_profile = profile_snapshot(app)
34
36
  model = compose_model(app, arguments)
35
37
  admit(app, model, host_facts(), running_containers())
@@ -41,6 +43,7 @@ def launch(app, arguments):
41
43
  if any(service.get("build") for service in model["services"].values()):
42
44
  subprocess.run(command + ["build"], check=True)
43
45
  with start_lock(START_LOCK):
46
+ require_active(app)
44
47
  if profile_snapshot(app) != original_profile:
45
48
  raise ValueError('runtime_profile_changed')
46
49
  admit(app, model, host_facts(), running_containers())
@@ -0,0 +1,242 @@
1
+ """Owner-scoped archive fence and data-preserving Docker shutdown.
2
+
3
+ The panel supplies a durable, increasing generation for each desired-state change.
4
+ The shared start lock orders that state against every released start path. A stop
5
+ failure retains the fence and an identical request retries it; unarchive only
6
+ clears this fence, never an operator's runtime profile or starts a container.
7
+ """
8
+ import json
9
+ import os
10
+ import re
11
+ import stat
12
+ import sys
13
+ import tempfile
14
+ from pathlib import Path
15
+
16
+ from identity_diagnostics import ReaderFailure, bounded
17
+ from runtime_host import start_lock
18
+
19
+ ROOT = Path('/var/lib/gowalk-backend-lifecycle')
20
+ START_LOCK = Path('/run/lock/gowalk-backend-start.lock')
21
+ ROOT_UID = 0
22
+ SCHEMA = 'gowalk-cicd/backend-lifecycle.v1'
23
+ RESULT = 'gowalk-cicd/backend-lifecycle-result.v1'
24
+ MAX_GENERATION = 9007199254740991
25
+ CODES = frozenset({'invalid_scope', 'state_invalid', 'owner_refused', 'host_disabled',
26
+ 'stale_generation', 'generation_conflict', 'native_runtime_unsupported',
27
+ 'container_scope_mismatch', 'container_inventory_invalid', 'runtime_changed',
28
+ 'runtime_not_stopped', 'command_failed', 'command_timeout', 'output_limit',
29
+ 'host_start_busy', 'unclassified'})
30
+ INSPECT = ('{"id":{{json .Id}},"running":{{json .State.Running}},'
31
+ '"restart":{{json .HostConfig.RestartPolicy.Name}},'
32
+ '"retry":{{.HostConfig.RestartPolicy.MaximumRetryCount}},'
33
+ '"project":{{json (index .Config.Labels "com.docker.compose.project")}},'
34
+ '"service":{{json (index .Config.Labels "com.docker.compose.service")}},'
35
+ '"directory":{{json (index .Config.Labels "com.docker.compose.project.working_dir")}}}')
36
+
37
+
38
+ def scope(project, generation, state):
39
+ if (not isinstance(project, str) or not re.fullmatch('[a-z0-9][a-z0-9-]{0,79}', project)
40
+ or type(generation) is not int or not 1 <= generation <= MAX_GENERATION
41
+ or state not in ('suspended', 'active')):
42
+ raise ValueError('invalid_scope')
43
+
44
+
45
+ def trusted(path, directory=False):
46
+ info = path.lstat()
47
+ kind = stat.S_ISDIR if directory else stat.S_ISREG
48
+ if (not kind(info.st_mode) or info.st_uid != ROOT_UID or info.st_mode & 0o022
49
+ or not directory and info.st_size > 16384):
50
+ raise ValueError('state_invalid')
51
+
52
+
53
+ def read(project):
54
+ scope(project, 1, 'active')
55
+ try:
56
+ trusted(ROOT, directory=True)
57
+ except FileNotFoundError:
58
+ return None
59
+ path = ROOT / (project + '.json')
60
+ try:
61
+ trusted(path)
62
+ except FileNotFoundError:
63
+ return None
64
+ with path.open() as stream:
65
+ value = json.load(stream)
66
+ if (not isinstance(value, dict) or set(value) != {'schema', 'project', 'owner', 'generation', 'state', 'restarts'}
67
+ or value['schema'] != SCHEMA or value['project'] != project
68
+ or not isinstance(value['owner'], str) or not re.fullmatch('[a-z0-9-]+', value['owner'])):
69
+ raise ValueError('state_invalid')
70
+ scope(project, value['generation'], value['state'])
71
+ if not isinstance(value['restarts'], list) or len(value['restarts']) > 32:
72
+ raise ValueError('state_invalid')
73
+ identifiers = set()
74
+ for row in value['restarts']:
75
+ if (not isinstance(row, dict) or set(row) != {'id', 'service', 'restart', 'retry'}
76
+ or not isinstance(row['id'], str) or not re.fullmatch('[0-9a-f]{64}', row['id'])
77
+ or row['id'] in identifiers or not valid_service(row['service']) or not valid_restart(row)):
78
+ raise ValueError('state_invalid')
79
+ identifiers.add(row['id'])
80
+ return value
81
+
82
+
83
+ def require_active(project):
84
+ value = read(project)
85
+ if value and value['state'] == 'suspended':
86
+ raise ValueError('runtime_suspended')
87
+
88
+
89
+ def write(value):
90
+ ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
91
+ trusted(ROOT, directory=True)
92
+ descriptor, temporary = tempfile.mkstemp(prefix='.state-', dir=str(ROOT))
93
+ try:
94
+ with os.fdopen(descriptor, 'w') as stream:
95
+ json.dump(value, stream, separators=(',', ':'))
96
+ stream.flush()
97
+ os.fsync(stream.fileno())
98
+ os.replace(temporary, str(ROOT / (value['project'] + '.json')))
99
+ descriptor = os.open(str(ROOT), os.O_RDONLY)
100
+ try:
101
+ os.fsync(descriptor)
102
+ finally:
103
+ os.close(descriptor)
104
+ finally:
105
+ if os.path.exists(temporary):
106
+ os.unlink(temporary)
107
+
108
+
109
+ def valid_service(value):
110
+ return isinstance(value, str) and re.fullmatch('[a-z0-9][a-z0-9_-]{0,63}', value)
111
+
112
+
113
+ def valid_restart(row):
114
+ return (row['restart'] in ('no', '', 'always', 'unless-stopped', 'on-failure')
115
+ and type(row['retry']) is int and 0 <= row['retry'] <= 2147483647
116
+ and (row['restart'] == 'on-failure' or row['retry'] == 0))
117
+
118
+
119
+ def inventory(project, app_root):
120
+ identifiers = bounded(['docker', 'ps', '--all', '--no-trunc', '--filter',
121
+ 'label=com.docker.compose.project=' + project,
122
+ '--format', '{{.ID}}'], seconds=15).decode().splitlines()
123
+ if (len(identifiers) > 32 or len(set(identifiers)) != len(identifiers)
124
+ or any(not re.fullmatch('[0-9a-f]{64}', value) for value in identifiers)):
125
+ raise ValueError('container_inventory_invalid')
126
+ if not identifiers:
127
+ return []
128
+ rows = [json.loads(line) for line in bounded(
129
+ ['docker', 'inspect', '--format', INSPECT, *identifiers], seconds=15).splitlines()]
130
+ if sorted(row['id'] for row in rows) != sorted(identifiers):
131
+ raise ValueError('runtime_changed')
132
+ for row in rows:
133
+ if (set(row) != {'id', 'running', 'restart', 'retry', 'project', 'service', 'directory'}
134
+ or row['project'] != project or row['directory'] != str(app_root / project)
135
+ or not valid_service(row['service'])
136
+ or type(row['running']) is not bool
137
+ or not valid_restart(row)):
138
+ raise ValueError('container_scope_mismatch')
139
+ return sorted(rows, key=lambda row: row['id'])
140
+
141
+
142
+ def restore(project, app_root, previous):
143
+ """Restore our exact containers' policies; never replace an operator's changed policy."""
144
+ saved = {row['id']: row for row in previous['restarts']}
145
+ expected = {}
146
+ for row in inventory(project, app_root):
147
+ original = saved.get(row['id'])
148
+ if original is None:
149
+ continue
150
+ if original['service'] != row['service']:
151
+ raise ValueError('container_scope_mismatch')
152
+ if row['restart'] != 'no' or row['retry'] != 0:
153
+ continue
154
+ policy = original['restart'] or 'no'
155
+ if policy == 'on-failure' and original['retry']:
156
+ policy += ':' + str(original['retry'])
157
+ bounded(['docker', 'update', '--restart=' + policy, row['id']], seconds=30)
158
+ expected[row['id']] = (original['restart'] or 'no', original['retry'])
159
+ observed = {row['id']: row for row in inventory(project, app_root)}
160
+ for identifier, policy in expected.items():
161
+ row = observed.get(identifier)
162
+ if row is None or (row['restart'], row['retry']) != policy:
163
+ raise ValueError('runtime_changed')
164
+
165
+
166
+ def apply(project, generation, state, owner):
167
+ import ssh_gate
168
+
169
+ scope(project, generation, state)
170
+ with start_lock(START_LOCK):
171
+ policy = ssh_gate.load_policy(owner)
172
+ if policy['disabled']:
173
+ raise ValueError('host_disabled')
174
+ try:
175
+ ssh_gate.authorize(owner, project, policy, False)
176
+ ssh_gate.scoped_path(str(ssh_gate.APPS / project))
177
+ except ValueError:
178
+ raise ValueError('owner_refused') from None
179
+ # Native unit ownership needs its own shutdown contract; never infer it.
180
+ if os.path.lexists(str(ssh_gate.NATIVE_PROFILES / (project + '.json'))):
181
+ raise ValueError('native_runtime_unsupported')
182
+ previous = read(project)
183
+ if previous:
184
+ if previous['owner'] != owner:
185
+ raise ValueError('owner_refused')
186
+ if generation < previous['generation']:
187
+ raise ValueError('stale_generation')
188
+ if generation == previous['generation'] and state != previous['state']:
189
+ raise ValueError('generation_conflict')
190
+ value = {'schema': SCHEMA, 'project': project, 'owner': owner,
191
+ 'generation': generation, 'state': state, 'restarts': []}
192
+ stopped = 0
193
+ if state == 'suspended':
194
+ rows = inventory(project, ssh_gate.APPS)
195
+ saved = {row['id']: row for row in (previous or {}).get('restarts', [])}
196
+ for row in rows:
197
+ original = saved.get(row['id'])
198
+ if original and original['service'] != row['service']:
199
+ raise ValueError('container_scope_mismatch')
200
+ value['restarts'].append(original or {key: row[key] for key in ('id', 'service', 'restart', 'retry')})
201
+ if value != previous:
202
+ write(value)
203
+ identifiers = [row['id'] for row in rows]
204
+ if identifiers:
205
+ # Manual stop alone does not survive a daemon restart with policy=always.
206
+ bounded(['docker', 'update', '--restart=no', *identifiers], seconds=30)
207
+ current = inventory(project, ssh_gate.APPS)
208
+ if ([row['id'] for row in current] != identifiers
209
+ or any(row['restart'] != 'no' for row in current)):
210
+ raise ValueError('runtime_changed')
211
+ running = [row['id'] for row in current if row['running']]
212
+ if running:
213
+ bounded(['docker', 'stop', '--time', '30', *running], seconds=90)
214
+ stopped = len(running)
215
+ current = inventory(project, ssh_gate.APPS)
216
+ if ([row['id'] for row in current] != identifiers
217
+ or any(row['running'] or row['restart'] != 'no' for row in current)):
218
+ raise ValueError('runtime_not_stopped')
219
+ else:
220
+ if previous and previous['state'] == 'suspended':
221
+ restore(project, ssh_gate.APPS, previous)
222
+ if value != previous:
223
+ write(value)
224
+ return {'schema': RESULT, 'ok': True, 'project': project, 'generation': generation,
225
+ 'state': state, 'containers_stopped': stopped}
226
+
227
+
228
+ def main():
229
+ try:
230
+ project, raw_generation, state, owner = sys.argv[1:]
231
+ if not re.fullmatch('[1-9][0-9]{0,15}', raw_generation):
232
+ raise ValueError('invalid_scope')
233
+ result = apply(project, int(raw_generation), state, owner)
234
+ except Exception as error:
235
+ code = error.code if isinstance(error, ReaderFailure) else str(error)
236
+ result = {'schema': RESULT, 'ok': False, 'code': code if code in CODES else 'unclassified'}
237
+ print(json.dumps(result, separators=(',', ':')))
238
+ return 0 if result['ok'] else 1
239
+
240
+
241
+ if __name__ == '__main__':
242
+ sys.exit(main())
@@ -80,6 +80,12 @@ def authorize(owner, project, policy, may_claim):
80
80
 
81
81
 
82
82
  def helper_command(words):
83
+ if len(words) == 5 and words[:2] == ['gowalk-backend', 'lifecycle']:
84
+ from runtime_lifecycle import scope
85
+ if not re.fullmatch('[1-9][0-9]{0,15}', words[3]):
86
+ raise ValueError('ssh_arguments_refused')
87
+ scope(words[2], int(words[3]), words[4])
88
+ return words[2], False, [sys.executable, str(HELPERS / 'runtime_lifecycle.py'), *words[2:]]
83
89
  if words[:2] == ['gowalk-backend', 'network-diagnostics']:
84
90
  return network_command(words)
85
91
  if len(words) in (5, 6) and words[:2] == ['gowalk-backend', 'runtime-diagnostics']:
@@ -189,6 +195,12 @@ def main():
189
195
  raise ValueError('ssh_backend_disabled')
190
196
  project, may_claim, arguments = plan(command)
191
197
  authorize(owner, project, policy, may_claim)
198
+ if arguments[1:2] == [str(HELPERS / 'runtime_lifecycle.py')]:
199
+ arguments.append(owner)
200
+ elif arguments[1:2] not in ([str(HELPERS / name)] for name in
201
+ ('runtime_readback.py', 'network_readback.py', 'identity_diagnostics.py')):
202
+ from runtime_lifecycle import require_active
203
+ require_active(project)
192
204
  if arguments[:2] == ['/bin/bash', str(HELPERS / 'remote_deploy.sh')]:
193
205
  if (NATIVE_PROFILES / (project + '.json')).exists():
194
206
  raise ValueError('ssh_native_project_required')
@@ -45,6 +45,7 @@ The entry permits only:
45
45
  - the standard bounded identity-diagnostic invocation, also redirected to the released helper;
46
46
  - `gowalk-backend network-diagnostics` with fixed owned project, API build, bridge key and namespace-only VPN pool;
47
47
  - `gowalk-backend native-deploy <project>` for an existing [root-profiled native service](BACKEND_NATIVE.md).
48
+ - `gowalk-backend lifecycle <project> <generation> <suspended|active>` for the panel's archive lifecycle.
48
49
 
49
50
  It refuses arbitrary shell commands, interactive shells, rsync sender/download operations, traversal,
50
51
  directory symlinks escaping an app and any attempt to execute an app-mirror helper. App code still owns
@@ -58,6 +59,38 @@ project refuses. A disabled runtime profile must still refuse a legacy deploy in
58
59
  task-owned project can be claimed and replayed, then remove only that verification project and binding.
59
60
  Failures emit only `backend_ssh_refused`, never the original command or private stdin.
60
61
 
62
+ ## Archive lifecycle
63
+
64
+ From host runtime 1.0.228, the existing owner key may suspend its registered Docker project with
65
+ `gowalk-backend lifecycle <project> <generation> suspended`. The generation is the panel's durable,
66
+ strictly increasing integer (1 through 9007199254740991) for each desired-state change. The panel,
67
+ not this host transport, verifies archive policy and Apple production-approval history before sending it.
68
+ The host rechecks owner registration and policy under the same lock as container starts, writes and
69
+ fsyncs `/var/lib/gowalk-backend-lifecycle/<project>.json`, then disables restart policies and stops
70
+ only containers whose exact project, service and working-directory labels match this project.
71
+ Stopped containers, volumes, application files, databases and operator runtime profiles are retained.
72
+ A successful reply requires fresh stopped-state and `restart=no` readback of the complete original inventory.
73
+
74
+ An identical request retries a partial stop. Lower generations and the same generation with another
75
+ state refuse without mutation. The journal retains original restart policies against exact container
76
+ identities before disabling them. `active` restores those policies only on matching containers still
77
+ using our `restart=no`, verifies the restoration, then clears this archive fence. It never starts a
78
+ container or replaces a later operator-changed policy or an operator-disabled runtime profile. Native profiles explicitly refuse
79
+ with `native_runtime_unsupported`; their units are never inferred from Docker naming.
80
+
81
+ The fixed JSON success receipt is `schema=gowalk-cicd/backend-lifecycle-result.v1`, `ok=true`,
82
+ `project`, `generation`, `state`, and integer `containers_stopped`. Zero means there was nothing
83
+ running to stop on that successful read, including an exact replay. A failure contains only the same
84
+ schema, `ok=false` and a fixed `code`; a gate-level refusal retains `backend_ssh_refused` instead.
85
+ No environment, application output or other project's inventory leaves the host.
86
+
87
+ While suspended, the gate refuses source/configuration writes and deployments but retains lifecycle
88
+ and diagnostic reads. Both Compose and native launchers check the fence again under the start lock,
89
+ so a build that began before suspension cannot start afterward. Installing the new runtime cannot
90
+ change already running older helper processes: drain those before the first lifecycle request (the
91
+ existing global deployment freeze may be used during that adoption). Installation alone neither
92
+ suspends an app nor changes the global freeze. No consumer workflow update is needed for this protocol.
93
+
61
94
  ## Applied runtime readback
62
95
 
63
96
  The released backend action accepts `operation: runtime-diagnostics`, `diagnostic-service` (default `api`) and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gowalk-cicd",
3
- "version": "1.0.227",
3
+ "version": "1.0.228",
4
4
  "description": "Zero-config GitHub Actions delivery for iOS TestFlight and Android Google Play.",
5
5
  "type": "module",
6
6
  "bin": {