containers.py 3.85 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
import signal
8
from subprograms import ChrtClient, NodeOSClient, resources
9 10
import sys

11
logger = logging.getLogger('nrm')
12 13
Container = namedtuple('Container', ['uuid', 'manifest', 'pid'])

14 15 16 17 18 19

class ContainerManager(object):

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

20
    def __init__(self, rm):
21
        self.containers = dict()
22 23 24 25
        self.pids = dict()
        self.resourcemanager = rm
        self.nodeos = NodeOSClient()
        self.chrt = ChrtClient()
26 27 28 29 30 31 32 33

    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']
34 35 36
        logger.info("run: manifest file: %s", manifestfile)
        logger.info("run: command:       %s", command)
        logger.info("run: args:          %r", args)
37 38
        manifest = ImageManifest()
        if not manifest.load(manifestfile):
39
            logger.error("Manifest is invalid")
40 41
            return -1

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)
46
        logger.info("run: allocation: %r", allocation)
47 48 49 50 51 52 53 54

        # 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'
55
        logger.info("run: environ: %r", environ)
56 57 58

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

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

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

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

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

98 99 100 101 102 103 104 105 106 107
    def kill(self, uuid):
        """Kill all the processes of a container."""
        if uuid in self.containers:
            c = self.containers[uuid]
            self.logger.debug("killing %r:", c)
            try:
                os.kill(c.pid, signal.SIGKILL)
            except OSError:
                pass

108 109 110 111 112
    def list(self):
        """List the containers in the system."""
        fields = ['uuid', 'pid']
        ret = [c._asdict() for c in self.containers.values()]
        return [{k: d[k] for k in fields} for d in ret]