authentik.outposts.controllers.docker
Docker controller
1"""Docker controller""" 2 3from time import sleep 4from urllib.parse import urlparse 5 6from django.conf import settings 7from django.utils.text import slugify 8from docker import DockerClient as UpstreamDockerClient 9from docker.errors import DockerException, NotFound 10from docker.models.containers import Container 11from docker.utils.utils import kwargs_from_env 12from paramiko.ssh_exception import SSHException 13from structlog.stdlib import get_logger 14from yaml import safe_dump 15 16from authentik import authentik_version 17from authentik.outposts.apps import MANAGED_OUTPOST 18from authentik.outposts.controllers.base import BaseClient, BaseController, ControllerException 19from authentik.outposts.docker_ssh import DockerInlineSSH, SSHManagedExternallyException 20from authentik.outposts.docker_tls import DockerInlineTLS 21from authentik.outposts.models import ( 22 DockerServiceConnection, 23 Outpost, 24 OutpostServiceConnectionState, 25 OutpostType, 26 ServiceConnectionInvalid, 27) 28 29DOCKER_MAX_ATTEMPTS = 10 30 31 32class DockerClient(UpstreamDockerClient, BaseClient): 33 """Custom docker client, which can handle TLS and SSH from a database.""" 34 35 tls: DockerInlineTLS | None 36 ssh: DockerInlineSSH | None 37 38 def __init__(self, connection: DockerServiceConnection): 39 self.tls = None 40 self.ssh = None 41 self.logger = get_logger() 42 if connection.local: 43 # Same result as DockerClient.from_env 44 super().__init__(**kwargs_from_env()) 45 else: 46 parsed_url = urlparse(connection.url) 47 tls_config = False 48 if parsed_url.scheme == "ssh": 49 try: 50 self.ssh = DockerInlineSSH(parsed_url.hostname, connection.tls_authentication) 51 self.ssh.write() 52 except SSHManagedExternallyException as exc: 53 # SSH config is managed externally 54 self.logger.info(f"SSH Managed externally: {exc}") 55 else: 56 self.tls = DockerInlineTLS( 57 verification_kp=connection.tls_verification, 58 authentication_kp=connection.tls_authentication, 59 ) 60 tls_config = self.tls.write() 61 try: 62 super().__init__( 63 base_url=connection.url, 64 tls=tls_config, 65 ) 66 except SSHException as exc: 67 if self.ssh: 68 self.ssh.cleanup() 69 raise ServiceConnectionInvalid(exc) from exc 70 # Ensure the client actually works 71 self.containers.list() 72 73 def fetch_state(self) -> OutpostServiceConnectionState: 74 try: 75 return OutpostServiceConnectionState(version=self.info()["ServerVersion"], healthy=True) 76 except ServiceConnectionInvalid, DockerException: 77 return OutpostServiceConnectionState(version="", healthy=False) 78 79 def __exit__(self, exc_type, exc_value, traceback): 80 # This overrides docker.DockerClient.__exit__, which is what closes the 81 # connection; without it every ssh:// client leaks a paramiko session 82 self.close() 83 if self.tls: 84 self.logger.debug("Cleaning up TLS") 85 self.tls.cleanup() 86 if self.ssh: 87 self.logger.debug("Cleaning up SSH") 88 self.ssh.cleanup() 89 90 91class DockerController(BaseController): 92 """Docker controller""" 93 94 client: DockerClient 95 96 container: Container 97 connection: DockerServiceConnection 98 99 def __init__(self, outpost: Outpost, connection: DockerServiceConnection) -> None: 100 super().__init__(outpost, connection) 101 if outpost.managed == MANAGED_OUTPOST: 102 return 103 try: 104 self.client = DockerClient(connection) 105 except DockerException as exc: 106 self.logger.warning(exc) 107 raise ControllerException from exc 108 109 @property 110 def name(self) -> str: 111 """Get the name of the object this reconciler manages""" 112 return ( 113 self.outpost.config.object_naming_template 114 % { 115 "name": slugify(self.outpost.name), 116 "uuid": self.outpost.uuid.hex, 117 } 118 ).lower() 119 120 def _get_labels(self) -> dict[str, str]: 121 labels = { 122 "io.goauthentik.outpost-uuid": self.outpost.pk.hex, 123 } 124 if self.outpost.config.docker_labels: 125 labels.update(self.outpost.config.docker_labels) 126 return labels 127 128 def _get_env(self) -> dict[str, str]: 129 return { 130 "AUTHENTIK_HOST": self.outpost.config.authentik_host.lower(), 131 "AUTHENTIK_INSECURE": str(self.outpost.config.authentik_host_insecure).lower(), 132 "AUTHENTIK_TOKEN": self.outpost.token.key, 133 "AUTHENTIK_HOST_BROWSER": self.outpost.config.authentik_host_browser, 134 } 135 136 def _comp_env(self, container: Container) -> bool: 137 """Check if container's env is equal to what we would set. Return true if container needs 138 to be rebuilt.""" 139 should_be = self._get_env() 140 container_env = container.attrs.get("Config", {}).get("Env", []) 141 for key, expected_value in should_be.items(): 142 entry = f"{key.upper()}={expected_value}" 143 if entry not in container_env: 144 return True 145 return False 146 147 def _comp_labels(self, container: Container) -> bool: 148 """Check if container's labels is equal to what we would set. Return true if container needs 149 to be rebuilt.""" 150 should_be = self._get_labels() 151 for key, expected_value in should_be.items(): 152 if key not in container.labels: 153 return True 154 if container.labels[key] != expected_value: 155 return True 156 return False 157 158 def _comp_ports(self, container: Container) -> bool: 159 """Check that the container has the correct ports exposed. Return true if container needs 160 to be rebuilt.""" 161 # with TEST enabled, we use host-network 162 if settings.TEST: 163 return False 164 # When the container isn't running, the API doesn't report any port mappings 165 if container.status != "running": 166 return False 167 # {'3389/tcp': [ 168 # {'HostIp': '0.0.0.0', 'HostPort': '389'}, 169 # {'HostIp': '::', 'HostPort': '389'} 170 # ]} 171 # If no ports are mapped (either mapping disabled, or host network) 172 if not container.ports or not self.outpost.config.docker_map_ports: 173 return False 174 for port in self.deployment_ports: 175 key = f"{port.inner_port or port.port}/{port.protocol.lower()}" 176 if not container.ports.get(key, None): 177 return True 178 host_matching = False 179 for host_port in container.ports[key]: 180 host_matching = host_port.get("HostPort") == str(port.port) 181 if not host_matching: 182 return True 183 return False 184 185 def try_pull_image(self): 186 """Try to pull the image needed for this outpost based on the CONFIG 187 `outposts.container_image_base`, but fall back to known-good images""" 188 image = self.get_container_image() 189 try: 190 self.client.images.pull(image) 191 except DockerException: # pragma: no cover 192 image = f"ghcr.io/goauthentik/{self.outpost.type}:{authentik_version()}" 193 self.client.images.pull(image) 194 return image 195 196 def _get_container(self) -> tuple[Container, bool]: 197 try: 198 return self.client.containers.get(self.name), False 199 except NotFound: 200 self.logger.info("(Re-)creating container...") 201 image_name = self.try_pull_image() 202 # Go outposts have a different syntax for this than the rust proxy outpost 203 healthcheck_cmd = [f"/{self.outpost.type}", "healthcheck"] 204 if self.outpost.type == OutpostType.PROXY: 205 healthcheck_cmd = ["/authentik", "healthcheck", self.outpost.type] 206 container_args = { 207 "image": image_name, 208 "name": self.name, 209 "detach": True, 210 "environment": self._get_env(), 211 "labels": self._get_labels(), 212 "restart_policy": {"Name": "unless-stopped"}, 213 "network": self.outpost.config.docker_network, 214 "healthcheck": { 215 "test": ["CMD", *healthcheck_cmd], 216 "interval": 5 * 1_000 * 1_000_000, 217 "retries": 20, 218 "start_period": 3 * 1_000 * 1_000_000, 219 }, 220 } 221 if self.outpost.config.docker_map_ports: 222 container_args["ports"] = { 223 f"{port.inner_port or port.port}/{port.protocol.lower()}": str(port.port) 224 for port in self.deployment_ports 225 } 226 if settings.TEST: 227 del container_args["ports"] 228 del container_args["network"] 229 container_args["network_mode"] = "host" 230 return ( 231 self.client.containers.create(**container_args), 232 True, 233 ) 234 235 def _migrate_container_name(self): # pragma: no cover 236 """Migrate 2021.9 to 2021.10+""" 237 old_name = f"authentik-proxy-{self.outpost.uuid.hex}" 238 try: 239 old_container: Container = self.client.containers.get(old_name) 240 old_container.kill() 241 old_container.remove() 242 except NotFound: 243 return 244 245 def up(self, depth=1): 246 if self.outpost.managed == MANAGED_OUTPOST: 247 return None 248 if depth >= DOCKER_MAX_ATTEMPTS: 249 raise ControllerException("Giving up since we exceeded recursion limit.") 250 self._migrate_container_name() 251 try: 252 container, has_been_created = self._get_container() 253 if has_been_created: 254 container.start() 255 return None 256 # Check if the container is out of date, delete it and retry 257 if len(container.image.tags) > 0: 258 should_image = self.try_pull_image() 259 if should_image not in container.image.tags: # pragma: no cover 260 self.logger.info( 261 "Container has mismatched image, re-creating...", 262 has=container.image.tags, 263 should=should_image, 264 ) 265 self.down() 266 return self.up(depth + 1) 267 # Check container's ports 268 if self._comp_ports(container): 269 self.logger.info("Container has mis-matched ports, re-creating...") 270 self.down() 271 return self.up(depth + 1) 272 # Check that container values match our values 273 if self._comp_env(container): 274 self.logger.info("Container has outdated config, re-creating...") 275 self.down() 276 return self.up(depth + 1) 277 # Check that container values match our values 278 if self._comp_labels(container): 279 self.logger.info("Container has outdated labels, re-creating...") 280 self.down() 281 return self.up(depth + 1) 282 if ( 283 container.attrs.get("HostConfig", {}) 284 .get("RestartPolicy", {}) 285 .get("Name", "") 286 .lower() 287 != "unless-stopped" 288 ): 289 self.logger.info("Container has mis-matched restart policy, re-creating...") 290 self.down() 291 return self.up(depth + 1) 292 # Check that container is healthy 293 if container.status == "running" and container.attrs.get("State", {}).get( 294 "Health", {} 295 ).get("Status", "") not in ["healthy", "starting"]: 296 # At this point we know the config is correct, but the container isn't healthy, 297 # so we just restart it with the same config 298 if has_been_created: 299 # Since we've just created the container, give it some time to start. 300 # If its still not up by then, restart it 301 self.logger.info("Container is unhealthy and new, giving it time to boot.") 302 sleep(60) 303 self.logger.info("Container is unhealthy, restarting...") 304 container.restart() 305 return None 306 # Check that container is running 307 if container.status != "running": 308 self.logger.info("Container is not running, restarting...") 309 container.start() 310 return None 311 self.logger.info("Container is running") 312 return None 313 except DockerException as exc: 314 raise ControllerException(str(exc)) from exc 315 316 def down(self): 317 if self.outpost.managed == MANAGED_OUTPOST: 318 return 319 try: 320 container, _ = self._get_container() 321 if container.status == "running": 322 self.logger.info("Stopping container.") 323 container.kill() 324 self.logger.info("Removing container.") 325 container.remove(force=True) 326 except DockerException as exc: 327 raise ControllerException(str(exc)) from exc 328 329 def get_static_deployment(self) -> str: 330 """Generate docker-compose yaml for proxy, version 3.5""" 331 ports = [ 332 f"{port.port}:{port.inner_port or port.port}/{port.protocol.lower()}" 333 for port in self.deployment_ports 334 ] 335 image_name = self.get_container_image() 336 compose = { 337 "version": "3.5", 338 "services": { 339 f"authentik_{self.outpost.type}": { 340 "image": image_name, 341 "ports": ports, 342 "environment": { 343 "AUTHENTIK_HOST": self.outpost.config.authentik_host, 344 "AUTHENTIK_INSECURE": str(self.outpost.config.authentik_host_insecure), 345 "AUTHENTIK_TOKEN": self.outpost.token.key, 346 "AUTHENTIK_HOST_BROWSER": self.outpost.config.authentik_host_browser, 347 }, 348 "labels": self._get_labels(), 349 } 350 }, 351 } 352 return safe_dump(compose, default_flow_style=False)
DOCKER_MAX_ATTEMPTS =
10
33class DockerClient(UpstreamDockerClient, BaseClient): 34 """Custom docker client, which can handle TLS and SSH from a database.""" 35 36 tls: DockerInlineTLS | None 37 ssh: DockerInlineSSH | None 38 39 def __init__(self, connection: DockerServiceConnection): 40 self.tls = None 41 self.ssh = None 42 self.logger = get_logger() 43 if connection.local: 44 # Same result as DockerClient.from_env 45 super().__init__(**kwargs_from_env()) 46 else: 47 parsed_url = urlparse(connection.url) 48 tls_config = False 49 if parsed_url.scheme == "ssh": 50 try: 51 self.ssh = DockerInlineSSH(parsed_url.hostname, connection.tls_authentication) 52 self.ssh.write() 53 except SSHManagedExternallyException as exc: 54 # SSH config is managed externally 55 self.logger.info(f"SSH Managed externally: {exc}") 56 else: 57 self.tls = DockerInlineTLS( 58 verification_kp=connection.tls_verification, 59 authentication_kp=connection.tls_authentication, 60 ) 61 tls_config = self.tls.write() 62 try: 63 super().__init__( 64 base_url=connection.url, 65 tls=tls_config, 66 ) 67 except SSHException as exc: 68 if self.ssh: 69 self.ssh.cleanup() 70 raise ServiceConnectionInvalid(exc) from exc 71 # Ensure the client actually works 72 self.containers.list() 73 74 def fetch_state(self) -> OutpostServiceConnectionState: 75 try: 76 return OutpostServiceConnectionState(version=self.info()["ServerVersion"], healthy=True) 77 except ServiceConnectionInvalid, DockerException: 78 return OutpostServiceConnectionState(version="", healthy=False) 79 80 def __exit__(self, exc_type, exc_value, traceback): 81 # This overrides docker.DockerClient.__exit__, which is what closes the 82 # connection; without it every ssh:// client leaks a paramiko session 83 self.close() 84 if self.tls: 85 self.logger.debug("Cleaning up TLS") 86 self.tls.cleanup() 87 if self.ssh: 88 self.logger.debug("Cleaning up SSH") 89 self.ssh.cleanup()
Custom docker client, which can handle TLS and SSH from a database.
DockerClient(connection: authentik.outposts.models.DockerServiceConnection)
39 def __init__(self, connection: DockerServiceConnection): 40 self.tls = None 41 self.ssh = None 42 self.logger = get_logger() 43 if connection.local: 44 # Same result as DockerClient.from_env 45 super().__init__(**kwargs_from_env()) 46 else: 47 parsed_url = urlparse(connection.url) 48 tls_config = False 49 if parsed_url.scheme == "ssh": 50 try: 51 self.ssh = DockerInlineSSH(parsed_url.hostname, connection.tls_authentication) 52 self.ssh.write() 53 except SSHManagedExternallyException as exc: 54 # SSH config is managed externally 55 self.logger.info(f"SSH Managed externally: {exc}") 56 else: 57 self.tls = DockerInlineTLS( 58 verification_kp=connection.tls_verification, 59 authentication_kp=connection.tls_authentication, 60 ) 61 tls_config = self.tls.write() 62 try: 63 super().__init__( 64 base_url=connection.url, 65 tls=tls_config, 66 ) 67 except SSHException as exc: 68 if self.ssh: 69 self.ssh.cleanup() 70 raise ServiceConnectionInvalid(exc) from exc 71 # Ensure the client actually works 72 self.containers.list()
tls: authentik.outposts.docker_tls.DockerInlineTLS | None
ssh: authentik.outposts.docker_ssh.DockerInlineSSH | None
74 def fetch_state(self) -> OutpostServiceConnectionState: 75 try: 76 return OutpostServiceConnectionState(version=self.info()["ServerVersion"], healthy=True) 77 except ServiceConnectionInvalid, DockerException: 78 return OutpostServiceConnectionState(version="", healthy=False)
Get state, version info
92class DockerController(BaseController): 93 """Docker controller""" 94 95 client: DockerClient 96 97 container: Container 98 connection: DockerServiceConnection 99 100 def __init__(self, outpost: Outpost, connection: DockerServiceConnection) -> None: 101 super().__init__(outpost, connection) 102 if outpost.managed == MANAGED_OUTPOST: 103 return 104 try: 105 self.client = DockerClient(connection) 106 except DockerException as exc: 107 self.logger.warning(exc) 108 raise ControllerException from exc 109 110 @property 111 def name(self) -> str: 112 """Get the name of the object this reconciler manages""" 113 return ( 114 self.outpost.config.object_naming_template 115 % { 116 "name": slugify(self.outpost.name), 117 "uuid": self.outpost.uuid.hex, 118 } 119 ).lower() 120 121 def _get_labels(self) -> dict[str, str]: 122 labels = { 123 "io.goauthentik.outpost-uuid": self.outpost.pk.hex, 124 } 125 if self.outpost.config.docker_labels: 126 labels.update(self.outpost.config.docker_labels) 127 return labels 128 129 def _get_env(self) -> dict[str, str]: 130 return { 131 "AUTHENTIK_HOST": self.outpost.config.authentik_host.lower(), 132 "AUTHENTIK_INSECURE": str(self.outpost.config.authentik_host_insecure).lower(), 133 "AUTHENTIK_TOKEN": self.outpost.token.key, 134 "AUTHENTIK_HOST_BROWSER": self.outpost.config.authentik_host_browser, 135 } 136 137 def _comp_env(self, container: Container) -> bool: 138 """Check if container's env is equal to what we would set. Return true if container needs 139 to be rebuilt.""" 140 should_be = self._get_env() 141 container_env = container.attrs.get("Config", {}).get("Env", []) 142 for key, expected_value in should_be.items(): 143 entry = f"{key.upper()}={expected_value}" 144 if entry not in container_env: 145 return True 146 return False 147 148 def _comp_labels(self, container: Container) -> bool: 149 """Check if container's labels is equal to what we would set. Return true if container needs 150 to be rebuilt.""" 151 should_be = self._get_labels() 152 for key, expected_value in should_be.items(): 153 if key not in container.labels: 154 return True 155 if container.labels[key] != expected_value: 156 return True 157 return False 158 159 def _comp_ports(self, container: Container) -> bool: 160 """Check that the container has the correct ports exposed. Return true if container needs 161 to be rebuilt.""" 162 # with TEST enabled, we use host-network 163 if settings.TEST: 164 return False 165 # When the container isn't running, the API doesn't report any port mappings 166 if container.status != "running": 167 return False 168 # {'3389/tcp': [ 169 # {'HostIp': '0.0.0.0', 'HostPort': '389'}, 170 # {'HostIp': '::', 'HostPort': '389'} 171 # ]} 172 # If no ports are mapped (either mapping disabled, or host network) 173 if not container.ports or not self.outpost.config.docker_map_ports: 174 return False 175 for port in self.deployment_ports: 176 key = f"{port.inner_port or port.port}/{port.protocol.lower()}" 177 if not container.ports.get(key, None): 178 return True 179 host_matching = False 180 for host_port in container.ports[key]: 181 host_matching = host_port.get("HostPort") == str(port.port) 182 if not host_matching: 183 return True 184 return False 185 186 def try_pull_image(self): 187 """Try to pull the image needed for this outpost based on the CONFIG 188 `outposts.container_image_base`, but fall back to known-good images""" 189 image = self.get_container_image() 190 try: 191 self.client.images.pull(image) 192 except DockerException: # pragma: no cover 193 image = f"ghcr.io/goauthentik/{self.outpost.type}:{authentik_version()}" 194 self.client.images.pull(image) 195 return image 196 197 def _get_container(self) -> tuple[Container, bool]: 198 try: 199 return self.client.containers.get(self.name), False 200 except NotFound: 201 self.logger.info("(Re-)creating container...") 202 image_name = self.try_pull_image() 203 # Go outposts have a different syntax for this than the rust proxy outpost 204 healthcheck_cmd = [f"/{self.outpost.type}", "healthcheck"] 205 if self.outpost.type == OutpostType.PROXY: 206 healthcheck_cmd = ["/authentik", "healthcheck", self.outpost.type] 207 container_args = { 208 "image": image_name, 209 "name": self.name, 210 "detach": True, 211 "environment": self._get_env(), 212 "labels": self._get_labels(), 213 "restart_policy": {"Name": "unless-stopped"}, 214 "network": self.outpost.config.docker_network, 215 "healthcheck": { 216 "test": ["CMD", *healthcheck_cmd], 217 "interval": 5 * 1_000 * 1_000_000, 218 "retries": 20, 219 "start_period": 3 * 1_000 * 1_000_000, 220 }, 221 } 222 if self.outpost.config.docker_map_ports: 223 container_args["ports"] = { 224 f"{port.inner_port or port.port}/{port.protocol.lower()}": str(port.port) 225 for port in self.deployment_ports 226 } 227 if settings.TEST: 228 del container_args["ports"] 229 del container_args["network"] 230 container_args["network_mode"] = "host" 231 return ( 232 self.client.containers.create(**container_args), 233 True, 234 ) 235 236 def _migrate_container_name(self): # pragma: no cover 237 """Migrate 2021.9 to 2021.10+""" 238 old_name = f"authentik-proxy-{self.outpost.uuid.hex}" 239 try: 240 old_container: Container = self.client.containers.get(old_name) 241 old_container.kill() 242 old_container.remove() 243 except NotFound: 244 return 245 246 def up(self, depth=1): 247 if self.outpost.managed == MANAGED_OUTPOST: 248 return None 249 if depth >= DOCKER_MAX_ATTEMPTS: 250 raise ControllerException("Giving up since we exceeded recursion limit.") 251 self._migrate_container_name() 252 try: 253 container, has_been_created = self._get_container() 254 if has_been_created: 255 container.start() 256 return None 257 # Check if the container is out of date, delete it and retry 258 if len(container.image.tags) > 0: 259 should_image = self.try_pull_image() 260 if should_image not in container.image.tags: # pragma: no cover 261 self.logger.info( 262 "Container has mismatched image, re-creating...", 263 has=container.image.tags, 264 should=should_image, 265 ) 266 self.down() 267 return self.up(depth + 1) 268 # Check container's ports 269 if self._comp_ports(container): 270 self.logger.info("Container has mis-matched ports, re-creating...") 271 self.down() 272 return self.up(depth + 1) 273 # Check that container values match our values 274 if self._comp_env(container): 275 self.logger.info("Container has outdated config, re-creating...") 276 self.down() 277 return self.up(depth + 1) 278 # Check that container values match our values 279 if self._comp_labels(container): 280 self.logger.info("Container has outdated labels, re-creating...") 281 self.down() 282 return self.up(depth + 1) 283 if ( 284 container.attrs.get("HostConfig", {}) 285 .get("RestartPolicy", {}) 286 .get("Name", "") 287 .lower() 288 != "unless-stopped" 289 ): 290 self.logger.info("Container has mis-matched restart policy, re-creating...") 291 self.down() 292 return self.up(depth + 1) 293 # Check that container is healthy 294 if container.status == "running" and container.attrs.get("State", {}).get( 295 "Health", {} 296 ).get("Status", "") not in ["healthy", "starting"]: 297 # At this point we know the config is correct, but the container isn't healthy, 298 # so we just restart it with the same config 299 if has_been_created: 300 # Since we've just created the container, give it some time to start. 301 # If its still not up by then, restart it 302 self.logger.info("Container is unhealthy and new, giving it time to boot.") 303 sleep(60) 304 self.logger.info("Container is unhealthy, restarting...") 305 container.restart() 306 return None 307 # Check that container is running 308 if container.status != "running": 309 self.logger.info("Container is not running, restarting...") 310 container.start() 311 return None 312 self.logger.info("Container is running") 313 return None 314 except DockerException as exc: 315 raise ControllerException(str(exc)) from exc 316 317 def down(self): 318 if self.outpost.managed == MANAGED_OUTPOST: 319 return 320 try: 321 container, _ = self._get_container() 322 if container.status == "running": 323 self.logger.info("Stopping container.") 324 container.kill() 325 self.logger.info("Removing container.") 326 container.remove(force=True) 327 except DockerException as exc: 328 raise ControllerException(str(exc)) from exc 329 330 def get_static_deployment(self) -> str: 331 """Generate docker-compose yaml for proxy, version 3.5""" 332 ports = [ 333 f"{port.port}:{port.inner_port or port.port}/{port.protocol.lower()}" 334 for port in self.deployment_ports 335 ] 336 image_name = self.get_container_image() 337 compose = { 338 "version": "3.5", 339 "services": { 340 f"authentik_{self.outpost.type}": { 341 "image": image_name, 342 "ports": ports, 343 "environment": { 344 "AUTHENTIK_HOST": self.outpost.config.authentik_host, 345 "AUTHENTIK_INSECURE": str(self.outpost.config.authentik_host_insecure), 346 "AUTHENTIK_TOKEN": self.outpost.token.key, 347 "AUTHENTIK_HOST_BROWSER": self.outpost.config.authentik_host_browser, 348 }, 349 "labels": self._get_labels(), 350 } 351 }, 352 } 353 return safe_dump(compose, default_flow_style=False)
Docker controller
DockerController( outpost: authentik.outposts.models.Outpost, connection: authentik.outposts.models.DockerServiceConnection)
100 def __init__(self, outpost: Outpost, connection: DockerServiceConnection) -> None: 101 super().__init__(outpost, connection) 102 if outpost.managed == MANAGED_OUTPOST: 103 return 104 try: 105 self.client = DockerClient(connection) 106 except DockerException as exc: 107 self.logger.warning(exc) 108 raise ControllerException from exc
client: DockerClient
name: str
110 @property 111 def name(self) -> str: 112 """Get the name of the object this reconciler manages""" 113 return ( 114 self.outpost.config.object_naming_template 115 % { 116 "name": slugify(self.outpost.name), 117 "uuid": self.outpost.uuid.hex, 118 } 119 ).lower()
Get the name of the object this reconciler manages
def
try_pull_image(self):
186 def try_pull_image(self): 187 """Try to pull the image needed for this outpost based on the CONFIG 188 `outposts.container_image_base`, but fall back to known-good images""" 189 image = self.get_container_image() 190 try: 191 self.client.images.pull(image) 192 except DockerException: # pragma: no cover 193 image = f"ghcr.io/goauthentik/{self.outpost.type}:{authentik_version()}" 194 self.client.images.pull(image) 195 return image
Try to pull the image needed for this outpost based on the CONFIG
outposts.container_image_base, but fall back to known-good images
def
up(self, depth=1):
246 def up(self, depth=1): 247 if self.outpost.managed == MANAGED_OUTPOST: 248 return None 249 if depth >= DOCKER_MAX_ATTEMPTS: 250 raise ControllerException("Giving up since we exceeded recursion limit.") 251 self._migrate_container_name() 252 try: 253 container, has_been_created = self._get_container() 254 if has_been_created: 255 container.start() 256 return None 257 # Check if the container is out of date, delete it and retry 258 if len(container.image.tags) > 0: 259 should_image = self.try_pull_image() 260 if should_image not in container.image.tags: # pragma: no cover 261 self.logger.info( 262 "Container has mismatched image, re-creating...", 263 has=container.image.tags, 264 should=should_image, 265 ) 266 self.down() 267 return self.up(depth + 1) 268 # Check container's ports 269 if self._comp_ports(container): 270 self.logger.info("Container has mis-matched ports, re-creating...") 271 self.down() 272 return self.up(depth + 1) 273 # Check that container values match our values 274 if self._comp_env(container): 275 self.logger.info("Container has outdated config, re-creating...") 276 self.down() 277 return self.up(depth + 1) 278 # Check that container values match our values 279 if self._comp_labels(container): 280 self.logger.info("Container has outdated labels, re-creating...") 281 self.down() 282 return self.up(depth + 1) 283 if ( 284 container.attrs.get("HostConfig", {}) 285 .get("RestartPolicy", {}) 286 .get("Name", "") 287 .lower() 288 != "unless-stopped" 289 ): 290 self.logger.info("Container has mis-matched restart policy, re-creating...") 291 self.down() 292 return self.up(depth + 1) 293 # Check that container is healthy 294 if container.status == "running" and container.attrs.get("State", {}).get( 295 "Health", {} 296 ).get("Status", "") not in ["healthy", "starting"]: 297 # At this point we know the config is correct, but the container isn't healthy, 298 # so we just restart it with the same config 299 if has_been_created: 300 # Since we've just created the container, give it some time to start. 301 # If its still not up by then, restart it 302 self.logger.info("Container is unhealthy and new, giving it time to boot.") 303 sleep(60) 304 self.logger.info("Container is unhealthy, restarting...") 305 container.restart() 306 return None 307 # Check that container is running 308 if container.status != "running": 309 self.logger.info("Container is not running, restarting...") 310 container.start() 311 return None 312 self.logger.info("Container is running") 313 return None 314 except DockerException as exc: 315 raise ControllerException(str(exc)) from exc
Called by scheduled task to reconcile deployment/service/etc
def
down(self):
317 def down(self): 318 if self.outpost.managed == MANAGED_OUTPOST: 319 return 320 try: 321 container, _ = self._get_container() 322 if container.status == "running": 323 self.logger.info("Stopping container.") 324 container.kill() 325 self.logger.info("Removing container.") 326 container.remove(force=True) 327 except DockerException as exc: 328 raise ControllerException(str(exc)) from exc
Handler to delete everything we've created
def
get_static_deployment(self) -> str:
330 def get_static_deployment(self) -> str: 331 """Generate docker-compose yaml for proxy, version 3.5""" 332 ports = [ 333 f"{port.port}:{port.inner_port or port.port}/{port.protocol.lower()}" 334 for port in self.deployment_ports 335 ] 336 image_name = self.get_container_image() 337 compose = { 338 "version": "3.5", 339 "services": { 340 f"authentik_{self.outpost.type}": { 341 "image": image_name, 342 "ports": ports, 343 "environment": { 344 "AUTHENTIK_HOST": self.outpost.config.authentik_host, 345 "AUTHENTIK_INSECURE": str(self.outpost.config.authentik_host_insecure), 346 "AUTHENTIK_TOKEN": self.outpost.token.key, 347 "AUTHENTIK_HOST_BROWSER": self.outpost.config.authentik_host_browser, 348 }, 349 "labels": self._get_labels(), 350 } 351 }, 352 } 353 return safe_dump(compose, default_flow_style=False)
Generate docker-compose yaml for proxy, version 3.5