mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-06 07:01:52 +09:00
feat(manifest): dockerfilePath — build services from a repo Dockerfile
A v1 manifest service gains a third image source next to buildpacks and
BYO image: — `dockerfilePath: services/api/Dockerfile`. This is the
monorepo path: one repository, several services, each built from its own
Dockerfile with the repo root as the shared build context.
- spec: new service key (camel + snake alias), validated relative-only
(no `..`/absolute), mutually exclusive with `image` and `containers`,
rejected on db services; schema docs copy kept in sync.
- resolve/plan: the path rides the create_app payload (with autoDeploy)
and shows in the step description; a changed path plans as an app
update; drift_pair tracks it against the stored build config.
- apply: create clones the project's repository into the managed apps
dir (idempotent — an existing checkout is reused) and writes the same
git-deployment + build config the import wizard does, so the existing
deploy pipeline (push webhook, per-service autoDeploy) takes over
unchanged. Source resolves from the stored manifest's provenance, else
a sibling app's git deployment; neither is a plan-time blocker
(dockerfile_no_source). Remote targets refuse like the other appliance
features ('a Dockerfile build' joins _service_features).
- scaffold: a dockerfile-built app round-trips its build config instead
of leaking the built image as a BYO `image:` declaration.
- import wizard: a v1 manifest with dockerfilePath seeds
build_method=dockerfile + the path.
Tests: 10 new (spec exclusivity/traversal + plan/apply/blocker wiring);
manifest suite 96/96, full backend suite green except 3 pre-existing
test_server_time_timezone failures also present on a clean tree.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
33b21c8ba6
commit
284bc02dc1
9 files changed
+345
-2
No files matched your search
@@ -121,6 +121,7 @@ class ManifestApplyService:
|
||||
'healthcheck_path': svc.get('healthcheck_path'),
|
||||
'build_command': svc.get('build_command'),
|
||||
'start_command': svc.get('start_command'),
|
||||
'dockerfile_path': svc.get('dockerfile_path'),
|
||||
'cpu': cls._stringify(svc.get('cpu')),
|
||||
'memory': cls._stringify(svc.get('memory')),
|
||||
'auto_deploy': svc.get('auto_deploy', False),
|
||||
@@ -205,6 +206,11 @@ class ManifestApplyService:
|
||||
if resolved.get('image'):
|
||||
expected['image'] = resolved['image']
|
||||
observed['image'] = app.docker_image
|
||||
if resolved.get('dockerfile_path'):
|
||||
from app.services.build_service import BuildService
|
||||
build_cfg = BuildService.get_app_build_config(app.id) or {}
|
||||
expected['dockerfile_path'] = resolved['dockerfile_path']
|
||||
observed['dockerfile_path'] = build_cfg.get('dockerfile_path')
|
||||
|
||||
declared_env = sorted(list(resolved.get('env', {}).keys())
|
||||
+ [r['key'] for r in resolved.get('env_refs', [])])
|
||||
@@ -317,6 +323,11 @@ class ManifestApplyService:
|
||||
if resolved.get('registry'):
|
||||
reg = cls._resolve_registry(resolved['registry'])
|
||||
payload['registry_id'] = reg.id if reg else None
|
||||
# Dockerfile build: carry the path + autoDeploy so create can wire
|
||||
# the git deployment and build config (monorepo: repo root = context)
|
||||
if resolved.get('dockerfile_path'):
|
||||
payload['dockerfile_path'] = resolved['dockerfile_path']
|
||||
payload['auto_deploy'] = resolved.get('auto_deploy', False)
|
||||
# fleet targeting (#21): route the app to a server when declared
|
||||
server_ref = resolved.get('server')
|
||||
if server_ref:
|
||||
@@ -327,9 +338,11 @@ class ManifestApplyService:
|
||||
issues.append({'service': name, 'kind': 'unknown_server',
|
||||
'server': server_ref})
|
||||
target = ' @ ' + server_ref if server_ref else ''
|
||||
built = (f' — built from `{resolved["dockerfile_path"]}`'
|
||||
if resolved.get('dockerfile_path') else '')
|
||||
steps.append({
|
||||
'type': 'create_app', 'service': name,
|
||||
'description': f'Create app `{name}` ({resolved["app_type"]}){target}',
|
||||
'description': f'Create app `{name}` ({resolved["app_type"]}){target}{built}',
|
||||
'payload': payload,
|
||||
})
|
||||
else:
|
||||
@@ -501,6 +514,8 @@ class ManifestApplyService:
|
||||
feats.append('a first-boot bootstrap')
|
||||
if resolved.get('containers'):
|
||||
feats.append('a multi-container unit')
|
||||
if resolved.get('dockerfile_path'):
|
||||
feats.append('a Dockerfile build')
|
||||
return feats
|
||||
|
||||
@classmethod
|
||||
@@ -531,6 +546,17 @@ class ManifestApplyService:
|
||||
'message': f'service {name} binds its public IP via fromServer, but '
|
||||
f'{where} has no recorded public IP — set it, then re-apply.'})
|
||||
|
||||
# A Dockerfile build needs a repository to clone. Plan-time, like a
|
||||
# missing secret: the stored manifest's provenance, or a git
|
||||
# deployment already configured on a sibling app in the project.
|
||||
if resolved.get('dockerfile_path') and cls._project_source(project) is None:
|
||||
blockers.append({
|
||||
'kind': 'dockerfile_no_source', 'service': name,
|
||||
'message': f'service {name} builds from `{resolved["dockerfile_path"]}`, '
|
||||
f'but the project has no source repository on record — import '
|
||||
f'the project from its repository (or configure a git deployment '
|
||||
f'on one of its apps), then re-apply.'})
|
||||
|
||||
feats = cls._service_features(resolved)
|
||||
if not feats:
|
||||
continue
|
||||
@@ -688,6 +714,25 @@ class ManifestApplyService:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _project_source(cls, project) -> Optional[Dict[str, str]]:
|
||||
"""The repository a Dockerfile-built service clones: the stored
|
||||
manifest's provenance, else the git deployment of a sibling app in the
|
||||
project. None when neither exists (a plan-time blocker)."""
|
||||
row = ApplicationManifest.query.filter_by(project_id=project.id).first()
|
||||
if row is not None and row.source_repo:
|
||||
return {'repo_url': row.source_repo, 'branch': row.source_ref or 'main'}
|
||||
try:
|
||||
from app.services.git_service import GitService
|
||||
deploy_configs = GitService.get_config().get('apps', {})
|
||||
except Exception:
|
||||
return None
|
||||
for sibling in Application.query.filter_by(project_id=project.id).all():
|
||||
cfg = deploy_configs.get(str(sibling.id))
|
||||
if cfg and cfg.get('repo_url'):
|
||||
return {'repo_url': cfg['repo_url'], 'branch': cfg.get('branch') or 'main'}
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _registry_has_credential(reg) -> bool:
|
||||
# ECR authenticates via a key-pair exchange, so no stored secret needed.
|
||||
@@ -870,8 +915,54 @@ class ManifestApplyService:
|
||||
)
|
||||
db.session.add(app)
|
||||
db.session.commit()
|
||||
if payload.get('dockerfile_path'):
|
||||
cls._wire_dockerfile_source(project, app, payload)
|
||||
return {'app_id': app.id, 'server_id': app.server_id}
|
||||
|
||||
@classmethod
|
||||
def _wire_dockerfile_source(cls, project, app, payload):
|
||||
"""Give a Dockerfile-built manifest service real source: clone the
|
||||
project's repository into the managed apps dir and write the same git
|
||||
deployment + build config the import wizard does, so the existing
|
||||
deploy pipeline builds `dockerfile_path` with the repo root as context."""
|
||||
import os
|
||||
from app import paths
|
||||
from app.services.git_service import GitService
|
||||
from app.services.build_service import BuildService
|
||||
|
||||
source = cls._project_source(project)
|
||||
if not source:
|
||||
raise RuntimeError('no source repository on record for the project')
|
||||
|
||||
base_dir = os.path.abspath(paths.APPS_DIR)
|
||||
app_path = os.path.abspath(os.path.join(base_dir, app.name))
|
||||
if app_path == base_dir or not app_path.startswith(base_dir + os.sep):
|
||||
raise RuntimeError('invalid application path')
|
||||
|
||||
# idempotent: a re-apply after a partial failure reuses the checkout
|
||||
if not os.path.isdir(os.path.join(app_path, '.git')):
|
||||
cloned = GitService.clone_repository(app_path, source['repo_url'],
|
||||
source['branch'])
|
||||
if not cloned.get('success'):
|
||||
raise RuntimeError(cloned.get('error') or 'clone failed')
|
||||
|
||||
app.root_path = app_path
|
||||
db.session.commit()
|
||||
|
||||
deploy = GitService.configure_deployment(
|
||||
app_id=app.id, app_path=app_path,
|
||||
repo_url=source['repo_url'], branch=source['branch'],
|
||||
auto_deploy=bool(payload.get('auto_deploy')))
|
||||
if not deploy.get('success'):
|
||||
raise RuntimeError(deploy.get('error') or 'failed to configure deployment')
|
||||
|
||||
built = BuildService.configure_build(
|
||||
app_id=app.id, app_path=app_path,
|
||||
build_method='dockerfile',
|
||||
dockerfile_path=payload['dockerfile_path'])
|
||||
if not built.get('success'):
|
||||
raise RuntimeError(built.get('error') or 'failed to configure build')
|
||||
|
||||
@classmethod
|
||||
def _do_update_app(cls, project, env, payload, user_id):
|
||||
import json
|
||||
@@ -901,6 +992,20 @@ class ManifestApplyService:
|
||||
if 'start_command' in changes:
|
||||
overrides['start_command'] = changes['start_command']
|
||||
app.buildpack_overrides = json.dumps(overrides)
|
||||
if 'dockerfile_path' in changes:
|
||||
from app.services.build_service import BuildService
|
||||
cfg = BuildService.get_config()
|
||||
entry = cfg.get('apps', {}).get(str(app.id))
|
||||
if entry:
|
||||
entry['dockerfile_path'] = changes['dockerfile_path']
|
||||
entry['build_method'] = 'dockerfile'
|
||||
BuildService.save_config(cfg)
|
||||
else:
|
||||
# app existed without a build config (e.g. created pre-manifest)
|
||||
BuildService.configure_build(
|
||||
app_id=app.id, app_path=app.root_path,
|
||||
build_method='dockerfile',
|
||||
dockerfile_path=changes['dockerfile_path'])
|
||||
db.session.commit()
|
||||
return {'app_id': app.id, 'changed': list(changes.keys())}
|
||||
|
||||
@@ -1092,6 +1197,11 @@ class ManifestApplyService:
|
||||
changes['memory'] = resolved['memory']
|
||||
if resolved.get('image') and app.docker_image != resolved['image']:
|
||||
changes['image'] = resolved['image']
|
||||
if resolved.get('dockerfile_path'):
|
||||
from app.services.build_service import BuildService
|
||||
build_cfg = BuildService.get_app_build_config(app.id) or {}
|
||||
if build_cfg.get('dockerfile_path') != resolved['dockerfile_path']:
|
||||
changes['dockerfile_path'] = resolved['dockerfile_path']
|
||||
overrides = {}
|
||||
if app.buildpack_overrides:
|
||||
try:
|
||||
|
||||
@@ -47,7 +47,13 @@ class ManifestScaffoldService:
|
||||
service['port'] = app.port
|
||||
|
||||
# Appliance tier (plan 35): round-trip a BYO image + typed L4 ports.
|
||||
if getattr(app, 'docker_image', None):
|
||||
# A Dockerfile-built app round-trips its build config instead — its
|
||||
# recorded docker_image is the build artifact, not a declaration.
|
||||
from app.services.build_service import BuildService
|
||||
build_cfg = BuildService.get_app_build_config(app.id) or {}
|
||||
if build_cfg.get('build_method') == 'dockerfile' and build_cfg.get('dockerfile_path'):
|
||||
service['dockerfilePath'] = build_cfg['dockerfile_path']
|
||||
elif getattr(app, 'docker_image', None):
|
||||
service['image'] = app.docker_image
|
||||
ports = cls._ports(app)
|
||||
if ports:
|
||||
|
||||
@@ -108,6 +108,7 @@ MANIFEST_SCHEMA: Dict[str, Any] = {
|
||||
"runtime": {"type": "string"},
|
||||
"buildCommand": {"type": "string"},
|
||||
"startCommand": {"type": "string"},
|
||||
"dockerfilePath": {"type": "string", "minLength": 1},
|
||||
"port": {"type": "integer", "minimum": 1, "maximum": 65535},
|
||||
"ports": {"type": "array", "items": {"$ref": "#/definitions/portDecl"}},
|
||||
"image": {"type": "string"},
|
||||
@@ -464,6 +465,23 @@ class ManifestSpecService:
|
||||
or svc.get('host_requirements'))
|
||||
containers = cls._normalize_containers(svc, prefix, errors)
|
||||
|
||||
# Dockerfile build: the service is built from a Dockerfile in the
|
||||
# repository (repo root = build context). Exactly one image source per
|
||||
# service — a declared path excludes BYO `image` and `containers`.
|
||||
dockerfile_path = cls._alias(svc, 'dockerfilePath', 'dockerfile_path')
|
||||
if dockerfile_path:
|
||||
if kind == 'database':
|
||||
errors.append(f'{prefix}: `dockerfilePath` does not apply to database services')
|
||||
if image:
|
||||
errors.append(f'{prefix}: `dockerfilePath` and `image` are mutually exclusive '
|
||||
'— build from source or bring an image, not both')
|
||||
if containers:
|
||||
errors.append(f'{prefix}: `dockerfilePath` cannot be combined with `containers` '
|
||||
'— unit containers declare ready-made images')
|
||||
if not cls._safe_relative_path(dockerfile_path):
|
||||
errors.append(f'{prefix}: `dockerfilePath` must be a relative path inside the '
|
||||
'repository (no leading `/`, no `..`)')
|
||||
|
||||
return {
|
||||
'name': name,
|
||||
'type': stype,
|
||||
@@ -473,6 +491,7 @@ class ManifestSpecService:
|
||||
'runtime': svc.get('runtime'),
|
||||
'build_command': cls._alias(svc, 'buildCommand', 'build_command'),
|
||||
'start_command': cls._alias(svc, 'startCommand', 'start_command'),
|
||||
'dockerfile_path': dockerfile_path or None,
|
||||
'port': svc.get('port'),
|
||||
'ports': ports,
|
||||
'bootstrap': bootstrap,
|
||||
@@ -795,6 +814,17 @@ class ManifestSpecService:
|
||||
|
||||
# -- helpers ------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _safe_relative_path(path: Any) -> bool:
|
||||
"""True for a repo-relative path with no traversal — rejects absolute
|
||||
paths (POSIX or drive-letter) and any `..` segment."""
|
||||
if not isinstance(path, str) or not path.strip():
|
||||
return False
|
||||
p = path.replace('\\', '/')
|
||||
if p.startswith('/') or re.match(r'^[A-Za-z]:', p):
|
||||
return False
|
||||
return not any(part == '..' for part in p.split('/'))
|
||||
|
||||
@staticmethod
|
||||
def _alias(obj: Dict[str, Any], camel: str, snake: str, default: Any = None) -> Any:
|
||||
if camel in obj and obj[camel] is not None:
|
||||
|
||||
@@ -183,7 +183,9 @@ class RepositoryManifestService:
|
||||
result,
|
||||
strategy='serverkit',
|
||||
app_type=first_app.get('app_type'),
|
||||
build_method='dockerfile' if first_app.get('dockerfile_path') else None,
|
||||
port=first_app.get('port'),
|
||||
dockerfile_path=first_app.get('dockerfile_path'),
|
||||
custom_build_cmd=first_app.get('build_command'),
|
||||
custom_start_cmd=first_app.get('start_command'),
|
||||
healthcheck_path=first_app.get('healthcheck_path'),
|
||||
|
||||
@@ -167,3 +167,90 @@ def test_redis_declared_but_warns(project, owner):
|
||||
assert plan['steps'][0]['type'] == 'warn'
|
||||
result = ManifestApplyService.apply(project, n, user_id=owner.id)
|
||||
assert result['success'] is True
|
||||
|
||||
|
||||
# -- Dockerfile builds ------------------------------------------------------
|
||||
|
||||
DOCKERFILE_MANIFEST = {
|
||||
'version': 1,
|
||||
'services': [
|
||||
{'name': 'api-worker', 'type': 'worker', 'autoDeploy': True,
|
||||
'dockerfilePath': 'services/api/Dockerfile',
|
||||
'envVars': [{'key': 'LOG_LEVEL', 'value': 'info'}]},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _store_source(project, repo='https://example.com/acme/mono.git', ref='main'):
|
||||
from app import db
|
||||
from app.models.application_manifest import ApplicationManifest
|
||||
row = ApplicationManifest(project_id=project.id, source_repo=repo, source_ref=ref)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return row
|
||||
|
||||
|
||||
def test_dockerfile_build_plans_and_blocks_without_source(project):
|
||||
n = ManifestSpecService.normalize(DOCKERFILE_MANIFEST)
|
||||
plan = ManifestApplyService.plan(project, n)
|
||||
create = next(s for s in plan['steps'] if s['type'] == 'create_app')
|
||||
assert create['payload']['dockerfile_path'] == 'services/api/Dockerfile'
|
||||
assert create['payload']['auto_deploy'] is True
|
||||
assert 'services/api/Dockerfile' in create['description']
|
||||
# no repository on record -> plan-time blocker (apply would refuse)
|
||||
assert any(b['kind'] == 'dockerfile_no_source' for b in plan['blockers'])
|
||||
|
||||
|
||||
def test_dockerfile_build_applies_end_to_end(project, owner, monkeypatch, tmp_path):
|
||||
import os
|
||||
from app import paths
|
||||
from app.models import Application
|
||||
from app.services.git_service import GitService
|
||||
from app.services.build_service import BuildService
|
||||
|
||||
monkeypatch.setattr(paths, 'APPS_DIR', str(tmp_path / 'apps'))
|
||||
calls = {}
|
||||
|
||||
def _clone(cls, app_path, repo_url, branch='main'):
|
||||
os.makedirs(os.path.join(app_path, '.git'))
|
||||
calls['clone'] = {'path': app_path, 'repo': repo_url, 'branch': branch}
|
||||
return {'success': True, 'path': app_path}
|
||||
|
||||
def _deploy(cls, app_id, app_path, repo_url, branch='main',
|
||||
auto_deploy=True, **kw):
|
||||
calls['deploy'] = {'app_id': app_id, 'repo': repo_url,
|
||||
'branch': branch, 'auto_deploy': auto_deploy}
|
||||
return {'success': True}
|
||||
|
||||
def _build(cls, app_id, app_path, **kw):
|
||||
calls['build'] = {'app_id': app_id, **kw}
|
||||
return {'success': True}
|
||||
|
||||
monkeypatch.setattr(GitService, 'clone_repository', classmethod(_clone))
|
||||
monkeypatch.setattr(GitService, 'configure_deployment', classmethod(_deploy))
|
||||
monkeypatch.setattr(BuildService, 'configure_build', classmethod(_build))
|
||||
|
||||
_store_source(project)
|
||||
n = ManifestSpecService.normalize(DOCKERFILE_MANIFEST)
|
||||
result = ManifestApplyService.apply(project, n, user_id=owner.id)
|
||||
assert result['success'] is True, result
|
||||
|
||||
app_row = Application.query.filter_by(project_id=project.id,
|
||||
name='api-worker').first()
|
||||
assert app_row is not None
|
||||
assert app_row.root_path == calls['clone']['path']
|
||||
assert calls['clone']['repo'] == 'https://example.com/acme/mono.git'
|
||||
assert calls['deploy']['auto_deploy'] is True
|
||||
assert calls['build']['build_method'] == 'dockerfile'
|
||||
assert calls['build']['dockerfile_path'] == 'services/api/Dockerfile'
|
||||
|
||||
|
||||
def test_dockerfile_build_remote_target_blocked(project):
|
||||
manifest = {'version': 1,
|
||||
'services': [{**DOCKERFILE_MANIFEST['services'][0],
|
||||
'server': 'edge-1'}]}
|
||||
_store_source(project)
|
||||
n = ManifestSpecService.normalize(manifest)
|
||||
plan = ManifestApplyService.plan(project, n)
|
||||
assert any(b['kind'] in ('remote_target', 'observed_server')
|
||||
for b in plan['blockers'])
|
||||
@@ -242,3 +242,54 @@ def test_validate_endpoint(client, auth_headers, app):
|
||||
json={'manifest': VALID})
|
||||
assert resp.status_code == 200
|
||||
assert resp.get_json()['valid'] is True
|
||||
|
||||
|
||||
# -- Dockerfile builds ------------------------------------------------------
|
||||
|
||||
def _dockerfile_manifest(**svc_extra):
|
||||
svc = {'name': 'api', 'type': 'worker'}
|
||||
svc.update(svc_extra)
|
||||
return {'version': 1, 'services': [svc]}
|
||||
|
||||
|
||||
def test_dockerfile_path_normalizes():
|
||||
n = ManifestSpecService.normalize(
|
||||
_dockerfile_manifest(dockerfilePath='services/api/Dockerfile'))
|
||||
assert n['services'][0]['dockerfile_path'] == 'services/api/Dockerfile'
|
||||
|
||||
|
||||
def test_dockerfile_path_snake_alias():
|
||||
n = ManifestSpecService.normalize(
|
||||
_dockerfile_manifest(dockerfile_path='Dockerfile.api'))
|
||||
assert n['services'][0]['dockerfile_path'] == 'Dockerfile.api'
|
||||
|
||||
|
||||
def test_dockerfile_path_exclusive_with_image():
|
||||
with pytest.raises(ManifestError) as exc:
|
||||
ManifestSpecService.normalize(
|
||||
_dockerfile_manifest(dockerfilePath='Dockerfile', image='nginx:1'))
|
||||
assert any('mutually exclusive' in e for e in exc.value.errors)
|
||||
|
||||
|
||||
def test_dockerfile_path_exclusive_with_containers():
|
||||
with pytest.raises(ManifestError) as exc:
|
||||
ManifestSpecService.normalize(_dockerfile_manifest(
|
||||
dockerfilePath='Dockerfile',
|
||||
containers={'main': {'image': 'nginx:1'}}))
|
||||
assert any('containers' in e for e in exc.value.errors)
|
||||
|
||||
|
||||
def test_dockerfile_path_rejects_unsafe_paths():
|
||||
for bad in ('../evil/Dockerfile', '/abs/Dockerfile', 'C:\evil\Dockerfile',
|
||||
'services/../../evil'):
|
||||
with pytest.raises(ManifestError):
|
||||
ManifestSpecService.normalize(_dockerfile_manifest(dockerfilePath=bad))
|
||||
|
||||
|
||||
def test_dockerfile_path_not_for_databases():
|
||||
with pytest.raises(ManifestError) as exc:
|
||||
ManifestSpecService.normalize({
|
||||
'version': 1,
|
||||
'services': [{'name': 'db', 'type': 'postgres',
|
||||
'dockerfilePath': 'Dockerfile'}]})
|
||||
assert any('database' in e for e in exc.value.errors)
|
||||
Reference in new issue
Block a user