|
| 1 | +import logging |
| 2 | + |
| 3 | +from django.conf import settings |
| 4 | +from django.db import models |
| 5 | + |
| 6 | +from api.models import UuidAuditedModel, log_event |
| 7 | + |
| 8 | +logger = logging.getLogger(__name__) |
| 9 | + |
| 10 | + |
| 11 | +def close_db_connections(func, *args, **kwargs): |
| 12 | + """ |
| 13 | + Decorator to explicitly close db connections during threaded execution |
| 14 | +
|
| 15 | + Note this is necessary to work around: |
| 16 | + https://code.djangoproject.com/ticket/22420 |
| 17 | + """ |
| 18 | + def _close_db_connections(*args, **kwargs): |
| 19 | + ret = None |
| 20 | + try: |
| 21 | + ret = func(*args, **kwargs) |
| 22 | + finally: |
| 23 | + from django.db import connections |
| 24 | + for conn in connections.all(): |
| 25 | + conn.close() |
| 26 | + return ret |
| 27 | + return _close_db_connections |
| 28 | + |
| 29 | + |
| 30 | +class Container(UuidAuditedModel): |
| 31 | + """ |
| 32 | + Docker container used to securely host an application process. |
| 33 | + """ |
| 34 | + |
| 35 | + owner = models.ForeignKey(settings.AUTH_USER_MODEL) |
| 36 | + app = models.ForeignKey('App') |
| 37 | + release = models.ForeignKey('Release') |
| 38 | + type = models.CharField(max_length=128, blank=False) |
| 39 | + num = models.PositiveIntegerField() |
| 40 | + |
| 41 | + @property |
| 42 | + def state(self): |
| 43 | + return self._scheduler.state(self.job_id).name |
| 44 | + |
| 45 | + def short_name(self): |
| 46 | + return "{}.{}.{}".format(self.app.id, self.type, self.num) |
| 47 | + short_name.short_description = 'Name' |
| 48 | + |
| 49 | + def __str__(self): |
| 50 | + return self.short_name() |
| 51 | + |
| 52 | + class Meta: |
| 53 | + get_latest_by = '-created' |
| 54 | + ordering = ['created'] |
| 55 | + |
| 56 | + @property |
| 57 | + def job_id(self): |
| 58 | + version = "v{}".format(self.release.version) |
| 59 | + return "{self.app.id}_{version}.{self.type}.{self.num}".format(**locals()) |
| 60 | + |
| 61 | + def _get_command(self): |
| 62 | + try: |
| 63 | + # if this is not procfile-based app, ensure they cannot break out |
| 64 | + # and run arbitrary commands on the host |
| 65 | + # FIXME: remove slugrunner's hardcoded entrypoint |
| 66 | + if self.release.build.dockerfile or not self.release.build.sha: |
| 67 | + return "bash -c '{}'".format(self.release.build.procfile[self.type]) |
| 68 | + else: |
| 69 | + return 'start {}'.format(self.type) |
| 70 | + # if the key is not present or if a parent attribute is None |
| 71 | + except (KeyError, TypeError, AttributeError): |
| 72 | + # handle special case for Dockerfile deployments |
| 73 | + return '' if self.type == 'cmd' else 'start {}'.format(self.type) |
| 74 | + |
| 75 | + _command = property(_get_command) |
| 76 | + |
| 77 | + def clone(self, release): |
| 78 | + c = Container.objects.create(owner=self.owner, |
| 79 | + app=self.app, |
| 80 | + release=release, |
| 81 | + type=self.type, |
| 82 | + num=self.num) |
| 83 | + return c |
| 84 | + |
| 85 | + @close_db_connections |
| 86 | + def create(self): |
| 87 | + image = self.release.image |
| 88 | + kwargs = {'memory': self.release.config.memory, |
| 89 | + 'cpu': self.release.config.cpu, |
| 90 | + 'tags': self.release.config.tags, |
| 91 | + 'envs': self.release.config.values} |
| 92 | + try: |
| 93 | + self._scheduler.create( |
| 94 | + name=self.job_id, |
| 95 | + image=image, |
| 96 | + command=self._command, |
| 97 | + **kwargs |
| 98 | + ) |
| 99 | + except Exception as e: |
| 100 | + err = '{} (create): {}'.format(self.job_id, e) |
| 101 | + log_event(self.app, err, logging.ERROR) |
| 102 | + raise |
| 103 | + |
| 104 | + @close_db_connections |
| 105 | + def start(self): |
| 106 | + try: |
| 107 | + self._scheduler.start(self.job_id) |
| 108 | + except Exception as e: |
| 109 | + err = '{} (start): {}'.format(self.job_id, e) |
| 110 | + log_event(self.app, err, logging.WARNING) |
| 111 | + raise |
| 112 | + |
| 113 | + @close_db_connections |
| 114 | + def stop(self): |
| 115 | + try: |
| 116 | + self._scheduler.stop(self.job_id) |
| 117 | + except Exception as e: |
| 118 | + err = '{} (stop): {}'.format(self.job_id, e) |
| 119 | + log_event(self.app, err, logging.ERROR) |
| 120 | + raise |
| 121 | + |
| 122 | + @close_db_connections |
| 123 | + def destroy(self): |
| 124 | + try: |
| 125 | + self._scheduler.destroy(self.job_id) |
| 126 | + except Exception as e: |
| 127 | + err = '{} (destroy): {}'.format(self.job_id, e) |
| 128 | + log_event(self.app, err, logging.ERROR) |
| 129 | + raise |
| 130 | + |
| 131 | + def run(self, command): |
| 132 | + """Run a one-off command""" |
| 133 | + if self.release.build is None: |
| 134 | + raise EnvironmentError('No build associated with this release ' |
| 135 | + 'to run this command') |
| 136 | + image = self.release.image |
| 137 | + entrypoint = '/bin/bash' |
| 138 | + # if this is a procfile-based app, switch the entrypoint to slugrunner's default |
| 139 | + # FIXME: remove slugrunner's hardcoded entrypoint |
| 140 | + if self.release.build.procfile and \ |
| 141 | + self.release.build.sha and not \ |
| 142 | + self.release.build.dockerfile: |
| 143 | + entrypoint = '/runner/init' |
| 144 | + command = "'{}'".format(command) |
| 145 | + else: |
| 146 | + command = "-c '{}'".format(command) |
| 147 | + try: |
| 148 | + rc, output = self._scheduler.run(self.job_id, image, entrypoint, command) |
| 149 | + return rc, output |
| 150 | + except Exception as e: |
| 151 | + err = '{} (run): {}'.format(self.job_id, e) |
| 152 | + log_event(self.app, err, logging.ERROR) |
| 153 | + raise |
0 commit comments