containers.py 3.34 KB
Newer Older
1 2 3
from __future__ import print_function

from aci import ImageManifest
4
from collections import namedtuple
5 6
import logging
import os
7
from subprograms import ChrtClient, NodeOSClient, resources
8 9
import sys

10 11
Container = namedtuple('Container', ['uuid', 'manifest', 'pid'])

12 13 14 15 16 17

class ContainerManager(object):

    """Manages the creation, listing and deletion of containers, using a
    container runtime underneath."""

18
    def __init__(self, rm):
19
        self.containers = dict()
20
        self.pids = dict()
21
        self.logger = logging.getLogger(__name__)
22 23 24
        self.resourcemanager = rm
        self.nodeos = NodeOSClient()
        self.chrt = ChrtClient()
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

    def create(self, request):
        """Create a container according to the request.

        Returns the pid of the container or a negative number for errors."""
        manifestfile = request['manifest']
        command = request['file']
        args = request['args']
        self.logger.info("run: manifest file: %s", manifestfile)
        self.logger.info("run: command:       %s", command)
        self.logger.info("run: args:          %r", args)
        manifest = ImageManifest()
        if not manifest.load(manifestfile):
            self.logger.error("Manifest is invalid")
            return -1

41 42 43 44 45
        # ask the resource manager for resources
        req = resources(int(manifest.app.isolators.container.cpus.value),
                        int(manifest.app.isolators.container.mems.value))
        allocation = self.resourcemanager.schedule(request['uuid'], req)
        self.logger.info("run: allocation: %r", allocation)
46 47 48 49 50 51 52 53 54 55 56 57 58

        # build context to execute
        environ = os.environ
        environ['PATH'] = ("/usr/local/sbin:"
                           "/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")
        environ['AC_APP_NAME'] = manifest.name
        environ['AC_METADATA_URL'] = "localhost"
        environ['container'] = 'argo'
        self.logger.info("run: environ: %r", environ)

        # create container
        container_name = request['uuid']
        self.logger.info("creating container %s", container_name)
59
        self.nodeos.create(container_name, allocation)
60 61 62 63 64 65 66
        self.logger.info("created container %s", container_name)

        newpid = os.fork()
        self.logger.info("forked: new pid: %s", newpid)
        if newpid == 0:
            # move myself to that container
            mypid = os.getpid()
67
            self.nodeos.attach(container_name, mypid)
68 69 70 71
            self.logger.info("child: attached to container %s", container_name)

            # run my command
            if hasattr(manifest.app.isolators, 'scheduler'):
72 73
                sched = manifest.app.isolators.scheduler
                argv = self.chrt.getwrappedcmd(sched)
74
            else:
75
                argv = []
76

77 78 79 80
            argv.append(command)
            argv.extend(args)
            self.logger.debug("execvpe %r", argv)
            os.execvpe(argv[0], argv, environ)
81 82 83
            # should never happen
            sys.exit(1)
        else:
84 85 86
            c = Container(container_name, manifest, newpid)
            self.pids[newpid] = c
            self.containers[container_name] = c
87 88 89 90
            return newpid

    def delete(self, uuid):
        """Delete a container and kill all related processes."""
91 92 93 94
        self.nodeos.delete(uuid, kill=True)
        c = self.containers[uuid]
        del self.containers[uuid]
        del self.pids[c.pid]