gowalk-cicd 1.0.227 → 1.0.229

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.
@@ -12,6 +12,7 @@ from health_rollout_engine import Engine, MARKER, healthy, probe, unshared
12
12
  from health_rollout_spec import ROLES, receipt, scope, specification, unchanged, verified
13
13
  from runtime_host import host_enabled, start_lock
14
14
  from runtime_launch import START_LOCK
15
+ from runtime_lifecycle import require_active
15
16
  from runtime_readback import profile
16
17
 
17
18
 
@@ -20,6 +21,7 @@ def allowed(app, service, identifier, image):
20
21
  or not re.fullmatch('[a-f0-9]{64}', identifier) or not re.fullmatch('sha256:[a-f0-9]{64}', image)):
21
22
  raise ValueError('rollout_scope_invalid')
22
23
  host_enabled()
24
+ require_active(app)
23
25
  document = profile(app)
24
26
  if document is not None:
25
27
  value = json.loads(document)
@@ -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,252 @@
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
+ import time
15
+ from pathlib import Path
16
+
17
+ from identity_diagnostics import ReaderFailure, bounded
18
+ from runtime_host import start_lock
19
+
20
+ ROOT = Path('/var/lib/gowalk-backend-lifecycle')
21
+ START_LOCK = Path('/run/lock/gowalk-backend-start.lock')
22
+ ROOT_UID = 0
23
+ SCHEMA = 'gowalk-cicd/backend-lifecycle.v1'
24
+ RESULT = 'gowalk-cicd/backend-lifecycle-result.v1'
25
+ MAX_GENERATION = 9007199254740991
26
+ WORK_SECONDS = 180
27
+ CODES = frozenset({'invalid_scope', 'state_invalid', 'owner_refused', 'host_disabled',
28
+ 'stale_generation', 'generation_conflict', 'native_runtime_unsupported',
29
+ 'container_scope_mismatch', 'container_inventory_invalid', 'runtime_changed',
30
+ 'runtime_not_stopped', 'command_failed', 'command_timeout', 'output_limit',
31
+ 'host_start_busy', 'unclassified'})
32
+ INSPECT = ('{"id":{{json .Id}},"running":{{json .State.Running}},'
33
+ '"restart":{{json .HostConfig.RestartPolicy.Name}},'
34
+ '"retry":{{.HostConfig.RestartPolicy.MaximumRetryCount}},'
35
+ '"project":{{json (index .Config.Labels "com.docker.compose.project")}},'
36
+ '"service":{{json (index .Config.Labels "com.docker.compose.service")}},'
37
+ '"directory":{{json (index .Config.Labels "com.docker.compose.project.working_dir")}}}')
38
+
39
+
40
+ def scope(project, generation, state):
41
+ if (not isinstance(project, str) or not re.fullmatch('[a-z0-9][a-z0-9-]{0,79}', project)
42
+ or type(generation) is not int or not 1 <= generation <= MAX_GENERATION
43
+ or state not in ('suspended', 'active')):
44
+ raise ValueError('invalid_scope')
45
+
46
+
47
+ def trusted(path, directory=False):
48
+ info = path.lstat()
49
+ kind = stat.S_ISDIR if directory else stat.S_ISREG
50
+ if (not kind(info.st_mode) or info.st_uid != ROOT_UID or info.st_mode & 0o022
51
+ or not directory and info.st_size > 16384):
52
+ raise ValueError('state_invalid')
53
+
54
+
55
+ def read(project):
56
+ scope(project, 1, 'active')
57
+ try:
58
+ trusted(ROOT, directory=True)
59
+ except FileNotFoundError:
60
+ return None
61
+ path = ROOT / (project + '.json')
62
+ try:
63
+ trusted(path)
64
+ except FileNotFoundError:
65
+ return None
66
+ with path.open() as stream:
67
+ value = json.load(stream)
68
+ if (not isinstance(value, dict) or set(value) != {'schema', 'project', 'owner', 'generation', 'state', 'restarts'}
69
+ or value['schema'] != SCHEMA or value['project'] != project
70
+ or not isinstance(value['owner'], str) or not re.fullmatch('[a-z0-9-]+', value['owner'])):
71
+ raise ValueError('state_invalid')
72
+ scope(project, value['generation'], value['state'])
73
+ if not isinstance(value['restarts'], list) or len(value['restarts']) > 32:
74
+ raise ValueError('state_invalid')
75
+ identifiers = set()
76
+ for row in value['restarts']:
77
+ if (not isinstance(row, dict) or set(row) != {'id', 'service', 'restart', 'retry'}
78
+ or not isinstance(row['id'], str) or not re.fullmatch('[0-9a-f]{64}', row['id'])
79
+ or row['id'] in identifiers or not valid_service(row['service']) or not valid_restart(row)):
80
+ raise ValueError('state_invalid')
81
+ identifiers.add(row['id'])
82
+ return value
83
+
84
+
85
+ def require_active(project):
86
+ value = read(project)
87
+ if value and value['state'] == 'suspended':
88
+ raise ValueError('runtime_suspended')
89
+
90
+
91
+ def write(value):
92
+ ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
93
+ trusted(ROOT, directory=True)
94
+ descriptor, temporary = tempfile.mkstemp(prefix='.state-', dir=str(ROOT))
95
+ try:
96
+ with os.fdopen(descriptor, 'w') as stream:
97
+ json.dump(value, stream, separators=(',', ':'))
98
+ stream.flush()
99
+ os.fsync(stream.fileno())
100
+ os.replace(temporary, str(ROOT / (value['project'] + '.json')))
101
+ descriptor = os.open(str(ROOT), os.O_RDONLY)
102
+ try:
103
+ os.fsync(descriptor)
104
+ finally:
105
+ os.close(descriptor)
106
+ finally:
107
+ if os.path.exists(temporary):
108
+ os.unlink(temporary)
109
+
110
+
111
+ def valid_service(value):
112
+ return isinstance(value, str) and re.fullmatch('[a-z0-9][a-z0-9_-]{0,63}', value)
113
+
114
+
115
+ def valid_restart(row):
116
+ return (row['restart'] in ('no', '', 'always', 'unless-stopped', 'on-failure')
117
+ and type(row['retry']) is int and 0 <= row['retry'] <= 2147483647
118
+ and (row['restart'] == 'on-failure' or row['retry'] == 0))
119
+
120
+
121
+ def run(arguments, seconds, deadline):
122
+ remaining = deadline - time.monotonic()
123
+ if remaining <= 0:
124
+ raise ReaderFailure('command_timeout')
125
+ return bounded(arguments, seconds=min(seconds, remaining))
126
+
127
+
128
+ def inventory(project, app_root, deadline):
129
+ identifiers = run(['docker', 'ps', '--all', '--no-trunc', '--filter',
130
+ 'label=com.docker.compose.project=' + project,
131
+ '--format', '{{.ID}}'], 15, deadline).decode().splitlines()
132
+ if (len(identifiers) > 32 or len(set(identifiers)) != len(identifiers)
133
+ or any(not re.fullmatch('[0-9a-f]{64}', value) for value in identifiers)):
134
+ raise ValueError('container_inventory_invalid')
135
+ if not identifiers:
136
+ return []
137
+ rows = [json.loads(line) for line in run(
138
+ ['docker', 'inspect', '--format', INSPECT, *identifiers], 15, deadline).splitlines()]
139
+ if sorted(row['id'] for row in rows) != sorted(identifiers):
140
+ raise ValueError('runtime_changed')
141
+ for row in rows:
142
+ if (set(row) != {'id', 'running', 'restart', 'retry', 'project', 'service', 'directory'}
143
+ or row['project'] != project or row['directory'] != str(app_root / project)
144
+ or not valid_service(row['service'])
145
+ or type(row['running']) is not bool
146
+ or not valid_restart(row)):
147
+ raise ValueError('container_scope_mismatch')
148
+ return sorted(rows, key=lambda row: row['id'])
149
+
150
+
151
+ def restore(project, app_root, previous, deadline):
152
+ """Restore our exact containers' policies; never replace an operator's changed policy."""
153
+ saved = {row['id']: row for row in previous['restarts']}
154
+ expected = {}
155
+ for row in inventory(project, app_root, deadline):
156
+ original = saved.get(row['id'])
157
+ if original is None:
158
+ continue
159
+ if original['service'] != row['service']:
160
+ raise ValueError('container_scope_mismatch')
161
+ if row['restart'] != 'no' or row['retry'] != 0:
162
+ continue
163
+ policy = original['restart'] or 'no'
164
+ if policy == 'on-failure' and original['retry']:
165
+ policy += ':' + str(original['retry'])
166
+ run(['docker', 'update', '--restart=' + policy, row['id']], 30, deadline)
167
+ expected[row['id']] = (original['restart'] or 'no', original['retry'])
168
+ observed = {row['id']: row for row in inventory(project, app_root, deadline)}
169
+ for identifier, policy in expected.items():
170
+ row = observed.get(identifier)
171
+ if row is None or (row['restart'], row['retry']) != policy:
172
+ raise ValueError('runtime_changed')
173
+
174
+
175
+ def apply(project, generation, state, owner):
176
+ import ssh_gate
177
+
178
+ scope(project, generation, state)
179
+ with start_lock(START_LOCK):
180
+ deadline = time.monotonic() + WORK_SECONDS
181
+ policy = ssh_gate.load_policy(owner)
182
+ if policy['disabled']:
183
+ raise ValueError('host_disabled')
184
+ try:
185
+ ssh_gate.authorize(owner, project, policy, False)
186
+ ssh_gate.scoped_path(str(ssh_gate.APPS / project))
187
+ except ValueError:
188
+ raise ValueError('owner_refused') from None
189
+ # Native unit ownership needs its own shutdown contract; never infer it.
190
+ if os.path.lexists(str(ssh_gate.NATIVE_PROFILES / (project + '.json'))):
191
+ raise ValueError('native_runtime_unsupported')
192
+ previous = read(project)
193
+ if previous:
194
+ if previous['owner'] != owner:
195
+ raise ValueError('owner_refused')
196
+ if generation < previous['generation']:
197
+ raise ValueError('stale_generation')
198
+ if generation == previous['generation'] and state != previous['state']:
199
+ raise ValueError('generation_conflict')
200
+ value = {'schema': SCHEMA, 'project': project, 'owner': owner,
201
+ 'generation': generation, 'state': state, 'restarts': []}
202
+ stopped = 0
203
+ if state == 'suspended':
204
+ rows = inventory(project, ssh_gate.APPS, deadline)
205
+ saved = {row['id']: row for row in (previous or {}).get('restarts', [])}
206
+ for row in rows:
207
+ original = saved.get(row['id'])
208
+ if original and original['service'] != row['service']:
209
+ raise ValueError('container_scope_mismatch')
210
+ value['restarts'].append(original or {key: row[key] for key in ('id', 'service', 'restart', 'retry')})
211
+ if value != previous:
212
+ write(value)
213
+ identifiers = [row['id'] for row in rows]
214
+ if identifiers:
215
+ # Manual stop alone does not survive a daemon restart with policy=always.
216
+ run(['docker', 'update', '--restart=no', *identifiers], 30, deadline)
217
+ current = inventory(project, ssh_gate.APPS, deadline)
218
+ if ([row['id'] for row in current] != identifiers
219
+ or any(row['restart'] != 'no' for row in current)):
220
+ raise ValueError('runtime_changed')
221
+ running = [row['id'] for row in current if row['running']]
222
+ if running:
223
+ run(['docker', 'stop', '--time', '30', *running], 90, deadline)
224
+ stopped = len(running)
225
+ current = inventory(project, ssh_gate.APPS, deadline)
226
+ if ([row['id'] for row in current] != identifiers
227
+ or any(row['running'] or row['restart'] != 'no' for row in current)):
228
+ raise ValueError('runtime_not_stopped')
229
+ else:
230
+ if previous and previous['state'] == 'suspended':
231
+ restore(project, ssh_gate.APPS, previous, deadline)
232
+ if value != previous:
233
+ write(value)
234
+ return {'schema': RESULT, 'ok': True, 'project': project, 'generation': generation,
235
+ 'state': state, 'containers_stopped': stopped}
236
+
237
+
238
+ def main():
239
+ try:
240
+ project, raw_generation, state, owner = sys.argv[1:]
241
+ if not re.fullmatch('[1-9][0-9]{0,15}', raw_generation):
242
+ raise ValueError('invalid_scope')
243
+ result = apply(project, int(raw_generation), state, owner)
244
+ except Exception as error:
245
+ code = error.code if isinstance(error, ReaderFailure) else str(error)
246
+ result = {'schema': RESULT, 'ok': False, 'code': code if code in CODES else 'unclassified'}
247
+ print(json.dumps(result, separators=(',', ':')))
248
+ return 0 if result['ok'] else 1
249
+
250
+
251
+ if __name__ == '__main__':
252
+ 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,42 @@ 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.229, 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
+ Lifecycle commands share a 180-second work deadline after the existing 120-second start-lock
82
+ admission. Partial work remains journaled and replayable; a 330-second client transport bound leaves
83
+ room for cleanup and the fixed result. This does not add a wait to successful commands.
84
+
85
+ The fixed JSON success receipt is `schema=gowalk-cicd/backend-lifecycle-result.v1`, `ok=true`,
86
+ `project`, `generation`, `state`, and integer `containers_stopped`. Zero means there was nothing
87
+ running to stop on that successful read, including an exact replay. A failure contains only the same
88
+ schema, `ok=false` and a fixed `code`; a gate-level refusal retains `backend_ssh_refused` instead.
89
+ No environment, application output or other project's inventory leaves the host.
90
+
91
+ While suspended, the gate refuses source/configuration writes and deployments but retains lifecycle
92
+ and diagnostic reads. Compose, native and operator health-cache rollout launchers check the fence again under the start lock,
93
+ so a build that began before suspension cannot start afterward. Installing the new runtime cannot
94
+ change already running older helper processes: drain those before the first lifecycle request (the
95
+ existing global deployment freeze may be used during that adoption). Installation alone neither
96
+ suspends an app nor changes the global freeze. No consumer workflow update is needed for this protocol.
97
+
61
98
  ## Applied runtime readback
62
99
 
63
100
  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.229",
4
4
  "description": "Zero-config GitHub Actions delivery for iOS TestFlight and Android Google Play.",
5
5
  "type": "module",
6
6
  "bin": {