Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(docker): container auto-sleep (policy, manual sleep/wake, idle sweep)

Juan Denis6554e7982131
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index c5889616..2990d8e9 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -14,6 +14,7 @@ from app.services.repository_manifest_service import RepositoryManifestService
from app.services.source_connection_service import SourceConnectionService
from app.services.remote_docker_service import RemoteDockerService
from app.services.image_update_service import ImageUpdateService
+from app.services.container_sleep_service import ContainerSleepService
from app.services.log_service import LogService
from app.services.process_service import ProcessService
from app.services.upload_service import (
@@ -1211,6 +1212,71 @@ def apply_image_update(app_id):
}), 200
+@apps_bp.route('/<int:app_id>/sleep-policy', methods=['GET'])
+@jwt_required()
+def get_sleep_policy(app_id):
+ app = Application.query.get(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ return jsonify(ContainerSleepService.get_or_create_policy(app_id).to_dict())
+
+
+@apps_bp.route('/<int:app_id>/sleep-policy', methods=['PUT'])
+@jwt_required()
+def update_sleep_policy(app_id):
+ user = User.query.get(get_jwt_identity())
+ app = Application.query.get(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ if not _can_edit_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+ data = request.get_json() or {}
+ policy = ContainerSleepService.set_policy(
+ app_id, enabled=data.get('enabled'), idle_timeout_minutes=data.get('idle_timeout_minutes'))
+ return jsonify(policy.to_dict())
+
+
+@apps_bp.route('/<int:app_id>/sleep', methods=['POST'])
+@jwt_required()
+def sleep_app(app_id):
+ user = User.query.get(get_jwt_identity())
+ app = Application.query.get(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ if not _can_edit_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+ result = ContainerSleepService.sleep_app(app_id)
+ if not result.get('success'):
+ return jsonify({'error': result['error']}), 400
+ return jsonify({'message': 'Application asleep', 'policy': result['policy'], 'app': app.to_dict()})
+
+
+@apps_bp.route('/<int:app_id>/wake', methods=['POST'])
+@jwt_required()
+def wake_app(app_id):
+ user = User.query.get(get_jwt_identity())
+ app = Application.query.get(app_id)
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ if not _can_edit_app(user, app):
+ return jsonify({'error': 'Access denied'}), 403
+ result = ContainerSleepService.wake_app(app_id)
+ if not result.get('success'):
+ return jsonify({'error': result['error']}), 400
+ return jsonify({'message': 'Application awake', 'policy': result['policy'], 'app': app.to_dict()})
+
+
+@apps_bp.route('/sweep-idle', methods=['POST'])
+@jwt_required()
+def sweep_idle_apps():
+ """Sleep all enabled apps that have been idle past their timeout. Intended
+ to be hit periodically (cron or a scheduler)."""
+ user = User.query.get(get_jwt_identity())
+ if not (user and user.is_admin):
+ return jsonify({'error': 'Admin access required'}), 403
+ return jsonify(ContainerSleepService.sweep_idle())
+
+
@apps_bp.route('/<int:app_id>/stop', methods=['POST'])
@jwt_required()
def stop_app(app_id):
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index 5c1766fa..3657b74d 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -117,6 +117,17 @@ class Application(db.Model):
}
else:
result['image_update'] = None
+
+ # Lightweight auto-sleep badge
+ sleep_policy = self.sleep_policy
+ if sleep_policy:
+ result['sleep'] = {
+ 'enabled': sleep_policy.enabled,
+ 'asleep': sleep_policy.asleep,
+ 'idle_timeout_minutes': sleep_policy.idle_timeout_minutes,
+ }
+ else:
+ result['sleep'] = None
if include_linked and self.linked_app:
result['linked_app'] = {
'id': self.linked_app.id,
diff --git a/backend/app/models/container_sleep_policy.py b/backend/app/models/container_sleep_policy.py
new file mode 100644
index 00000000..c9518a34
--- /dev/null
+++ b/backend/app/models/container_sleep_policy.py
@@ -0,0 +1,29 @@
+from datetime import datetime
+from app import db
+
+
+class ContainerSleepPolicy(db.Model):
+ """Per-application auto-sleep policy: when enabled, an idle app is stopped
+ after `idle_timeout_minutes` of no recorded activity, and can be woken on
+ demand. One row per application."""
+ __tablename__ = 'container_sleep_policies'
+
+ id = db.Column(db.Integer, primary_key=True)
+ application_id = db.Column(db.Integer, db.ForeignKey('applications.id'),
+ nullable=False, unique=True, index=True)
+ enabled = db.Column(db.Boolean, default=False, nullable=False)
+ idle_timeout_minutes = db.Column(db.Integer, default=30, nullable=False)
+ last_activity_at = db.Column(db.DateTime)
+ asleep = db.Column(db.Boolean, default=False, nullable=False)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ application = db.relationship('Application', backref=db.backref('sleep_policy', uselist=False))
+
+ def to_dict(self):
+ return {
+ 'application_id': self.application_id,
+ 'enabled': self.enabled,
+ 'idle_timeout_minutes': self.idle_timeout_minutes,
+ 'last_activity_at': self.last_activity_at.isoformat() if self.last_activity_at else None,
+ 'asleep': self.asleep,
+ }
diff --git a/backend/app/services/container_sleep_service.py b/backend/app/services/container_sleep_service.py
new file mode 100644
index 00000000..ce1acc4b
--- /dev/null
+++ b/backend/app/services/container_sleep_service.py
@@ -0,0 +1,112 @@
+"""Container auto-sleep: stop idle apps to free resources and wake them on
+demand. Idle is measured from `last_activity_at` (bumped on wake and via
+record_activity); wiring real traffic into record_activity — e.g. from the
+nginx access log — and request-triggered wake-on-demand are follow-ups."""
+import logging
+from datetime import datetime, timedelta
+
+from app import db
+from app.models import Application
+from app.models.container_sleep_policy import ContainerSleepPolicy
+from app.services.docker_service import DockerService
+
+logger = logging.getLogger(__name__)
+
+
+class ContainerSleepService:
+
+ @staticmethod
+ def get_or_create_policy(application_id):
+ policy = ContainerSleepPolicy.query.filter_by(application_id=application_id).first()
+ if not policy:
+ policy = ContainerSleepPolicy(application_id=application_id)
+ db.session.add(policy)
+ db.session.commit()
+ return policy
+
+ @classmethod
+ def set_policy(cls, application_id, enabled=None, idle_timeout_minutes=None):
+ policy = cls.get_or_create_policy(application_id)
+ if enabled is not None:
+ policy.enabled = bool(enabled)
+ if idle_timeout_minutes is not None:
+ policy.idle_timeout_minutes = max(1, int(idle_timeout_minutes))
+ # (Re)configuring the policy resets the idle clock.
+ policy.last_activity_at = datetime.utcnow()
+ db.session.commit()
+ return policy
+
+ @staticmethod
+ def record_activity(application_id):
+ policy = ContainerSleepPolicy.query.filter_by(application_id=application_id).first()
+ if policy:
+ policy.last_activity_at = datetime.utcnow()
+ db.session.commit()
+ return policy
+
+ @classmethod
+ def _stop(cls, app):
+ if app.server_id:
+ return {'success': False, 'error': 'Sleep is not yet supported for apps on remote servers'}
+ if app.app_type == 'docker' and app.root_path and app.compose_file:
+ return DockerService.compose_down(app.root_path, compose_file=app.compose_file)
+ if app.container_id:
+ return DockerService.stop_container(app.container_id)
+ return {'success': False, 'error': 'No container or compose project to stop'}
+
+ @classmethod
+ def _start(cls, app):
+ if app.server_id:
+ return {'success': False, 'error': 'Wake is not yet supported for apps on remote servers'}
+ if app.app_type == 'docker' and app.root_path and app.compose_file:
+ return DockerService.compose_up(app.root_path, detach=True, compose_file=app.compose_file)
+ if app.container_id:
+ return DockerService.start_container(app.container_id)
+ return {'success': False, 'error': 'No container or compose project to start'}
+
+ @classmethod
+ def sleep_app(cls, application_id):
+ app = Application.query.get(application_id)
+ if not app:
+ return {'success': False, 'error': 'Application not found'}
+ result = cls._stop(app)
+ if not result.get('success'):
+ return result
+ policy = cls.get_or_create_policy(application_id)
+ policy.asleep = True
+ app.status = 'stopped'
+ db.session.commit()
+ logger.info('Container auto-sleep: %s asleep', app.name)
+ return {'success': True, 'policy': policy.to_dict()}
+
+ @classmethod
+ def wake_app(cls, application_id):
+ app = Application.query.get(application_id)
+ if not app:
+ return {'success': False, 'error': 'Application not found'}
+ result = cls._start(app)
+ if not result.get('success'):
+ return result
+ policy = cls.get_or_create_policy(application_id)
+ policy.asleep = False
+ policy.last_activity_at = datetime.utcnow()
+ app.status = 'running'
+ db.session.commit()
+ logger.info('Container auto-sleep: %s awake', app.name)
+ return {'success': True, 'policy': policy.to_dict()}
+
+ @classmethod
+ def sweep_idle(cls):
+ """Sleep every enabled, awake app whose recorded activity is older than
+ its idle timeout. Meant to run periodically (cron/scheduler)."""
+ now = datetime.utcnow()
+ slept = []
+ policies = ContainerSleepPolicy.query.filter_by(enabled=True, asleep=False).all()
+ for policy in policies:
+ if not policy.last_activity_at:
+ continue # no activity baseline yet — never sleep blind
+ if now - policy.last_activity_at < timedelta(minutes=policy.idle_timeout_minutes):
+ continue
+ if cls.sleep_app(policy.application_id).get('success'):
+ slept.append(policy.application_id)
+ return {'success': True, 'slept': slept}
diff --git a/backend/tests/test_container_sleep.py b/backend/tests/test_container_sleep.py
new file mode 100644
index 00000000..7d0a2307
--- /dev/null
+++ b/backend/tests/test_container_sleep.py
@@ -0,0 +1,106 @@
+"""Tests for container auto-sleep (policy, manual sleep/wake, idle sweep)."""
+import uuid
+from datetime import datetime, timedelta
+
+from app import db
+from app.models import Application
+from app.models.container_sleep_policy import ContainerSleepPolicy
+from app.services.docker_service import DockerService
+from app.services.container_sleep_service import ContainerSleepService
+
+
+def _seed_app(**kw):
+ from app.models import User
+ uid = uuid.uuid4().hex[:8]
+ user = User(email=f'{uid}@t.local', username=f'u{uid}',
+ password_hash='x', role=User.ROLE_ADMIN, is_active=True)
+ db.session.add(user)
+ db.session.commit()
+ defaults = dict(name='web', app_type='docker', source='manual', root_path='/tmp/web',
+ compose_file='docker-compose.yml', docker_image='nginx:latest', user_id=user.id)
+ defaults.update(kw)
+ row = Application(**defaults)
+ db.session.add(row)
+ db.session.commit()
+ return row
+
+
+def _mock_docker(monkeypatch, ok=True):
+ monkeypatch.setattr(DockerService, 'compose_down', lambda *a, **k: {'success': ok})
+ monkeypatch.setattr(DockerService, 'compose_up', lambda *a, **k: {'success': ok})
+
+
+class TestSleepPolicy:
+ def test_set_and_get_policy(self, app):
+ a = _seed_app()
+ p = ContainerSleepService.set_policy(a.id, enabled=True, idle_timeout_minutes=15)
+ assert p.enabled is True and p.idle_timeout_minutes == 15
+ assert ContainerSleepService.get_or_create_policy(a.id).enabled is True
+
+ def test_timeout_has_a_floor_of_one(self, app):
+ a = _seed_app()
+ p = ContainerSleepService.set_policy(a.id, idle_timeout_minutes=0)
+ assert p.idle_timeout_minutes == 1
+
+
+class TestSleepWake:
+ def test_sleep_then_wake(self, app, monkeypatch):
+ _mock_docker(monkeypatch)
+ a = _seed_app()
+ r = ContainerSleepService.sleep_app(a.id)
+ assert r['success'] and r['policy']['asleep'] is True
+ assert Application.query.get(a.id).status == 'stopped'
+ r2 = ContainerSleepService.wake_app(a.id)
+ assert r2['success'] and r2['policy']['asleep'] is False
+ assert Application.query.get(a.id).status == 'running'
+
+ def test_sleep_propagates_docker_failure(self, app, monkeypatch):
+ _mock_docker(monkeypatch, ok=False)
+ a = _seed_app()
+ assert ContainerSleepService.sleep_app(a.id)['success'] is False
+
+ def test_remote_app_is_guarded(self, app):
+ a = _seed_app(server_id='srv-1')
+ r = ContainerSleepService.sleep_app(a.id)
+ assert r['success'] is False and 'remote' in r['error'].lower()
+
+
+class TestSweep:
+ def test_sweeps_only_idle_enabled_awake(self, app, monkeypatch):
+ _mock_docker(monkeypatch)
+ idle, active, disabled = _seed_app(), _seed_app(), _seed_app()
+
+ ContainerSleepService.set_policy(idle.id, enabled=True, idle_timeout_minutes=30)
+ ContainerSleepPolicy.query.filter_by(application_id=idle.id).first().last_activity_at = \
+ datetime.utcnow() - timedelta(minutes=60)
+ ContainerSleepService.set_policy(active.id, enabled=True, idle_timeout_minutes=30) # activity just now
+ ContainerSleepService.set_policy(disabled.id, enabled=False, idle_timeout_minutes=1)
+ ContainerSleepPolicy.query.filter_by(application_id=disabled.id).first().last_activity_at = \
+ datetime.utcnow() - timedelta(minutes=60)
+ db.session.commit()
+
+ slept = ContainerSleepService.sweep_idle()['slept']
+ assert idle.id in slept
+ assert active.id not in slept
+ assert disabled.id not in slept
+
+ def test_sweep_skips_without_activity_baseline(self, app, monkeypatch):
+ _mock_docker(monkeypatch)
+ a = _seed_app()
+ p = ContainerSleepService.set_policy(a.id, enabled=True, idle_timeout_minutes=30)
+ p.last_activity_at = None
+ db.session.commit()
+ assert a.id not in ContainerSleepService.sweep_idle()['slept']
+
+
+class TestSleepApi:
+ def test_sleep_and_wake_endpoints(self, client, auth_headers, app, monkeypatch):
+ _mock_docker(monkeypatch)
+ from app.models import User
+ admin = User.query.filter_by(username='testadmin').first()
+ a = _seed_app(user_id=admin.id)
+ assert client.post(f'/api/v1/apps/{a.id}/sleep', headers=auth_headers).status_code == 200
+ assert client.post(f'/api/v1/apps/{a.id}/wake', headers=auth_headers).status_code == 200
+
+ def test_sweep_requires_admin_auth(self, client, app):
+ assert client.post('/api/v1/apps/sweep-idle').status_code == 401