containers.py 4.81 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
logger = logging.getLogger('nrm')
10
Container = namedtuple('Container', ['uuid', 'manifest', 'process'])
11

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 21 22 23
        self.pids = dict()
        self.resourcemanager = rm
        self.nodeos = NodeOSClient()
        self.chrt = ChrtClient()
24 25 26 27 28 29 30 31

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

40 41 42 43
        # 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)
44
        logger.info("run: allocation: %r", allocation)
45 46 47

        # build context to execute
        environ = os.environ
48 49
        # environ['PATH'] = ("/usr/local/sbin:"
        #                   "/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")
50 51
        environ['AC_APP_NAME'] = manifest.name
        environ['AC_METADATA_URL'] = "localhost"
52
        logger.info("run: environ: %r", environ)
53 54 55

        # create container
        container_name = request['uuid']
56
        environ['ARGO_CONTAINER_UUID'] = container_name
57
        logger.info("creating container %s", container_name)
58
        self.nodeos.create(container_name, allocation)
59
        logger.info("created container %s", container_name)
60

61 62 63 64 65 66 67 68
        # Container power policy information
        container_powerpolicy = dict()
        container_powerpolicy['policy'] = None
        container_powerpolicy['damper'] = None
        container_powerpolicy['slowdown'] = None
        # TODO: Application library to load must be set during configuration
        applicationpreloadlibrary = ''

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

76 77 78 79 80 81 82 83
        # It would've been better if argo-perf-wrapper wrapped around
        # argo-nodeos-config and not the final command -- that way it would
        # be running outside of the container.  However, because
        # argo-nodeos-config is suid root, perf can't monitor it.
        if hasattr(manifest.app.isolators, 'perfwrapper'):
            if hasattr(manifest.app.isolators.perfwrapper, 'enabled'):
                if manifest.app.isolators.perfwrapper.enabled in ["1", "True"]:
                    argv.append('argo-perf-wrapper')
84

85 86
        if hasattr(manifest.app.isolators, 'powerpolicy'):
            if hasattr(manifest.app.isolators.powerpolicy, 'enabled'):
87 88 89 90 91 92 93
                    pp = manifest.app.isolators.powerpolicy
                    if pp.enabled in ["1", "True"]:
                        if pp.policy != "NONE":
                            container_powerpolicy['policy'] = pp.policy
                            container_powerpolicy['damper'] = pp.damper
                            container_powerpolicy['slowdown'] = pp.slowdown
                            environ['LD_PRELOAD'] = applicationpreloadlibrary
94

95 96 97 98 99 100
        argv.append(command)
        argv.extend(args)
        process = self.nodeos.execute(container_name, argv, environ)
        c = Container(container_name, manifest, process)
        self.pids[process.pid] = c
        self.containers[container_name] = c
101
        return c
102 103 104

    def delete(self, uuid):
        """Delete a container and kill all related processes."""
105
        self.nodeos.delete(uuid, kill=True)
106
        self.resourcemanager.update(uuid)
107 108
        c = self.containers[uuid]
        del self.containers[uuid]
109
        del self.pids[c.process.pid]
110

Swann Perarnau's avatar
Swann Perarnau committed
111 112 113 114
    def kill(self, uuid):
        """Kill all the processes of a container."""
        if uuid in self.containers:
            c = self.containers[uuid]
115
            logger.debug("killing %r:", c)
Swann Perarnau's avatar
Swann Perarnau committed
116
            try:
117
                c.process.proc.terminate()
Swann Perarnau's avatar
Swann Perarnau committed
118 119 120
            except OSError:
                pass

121 122
    def list(self):
        """List the containers in the system."""
123
        return [{'uuid': c.uuid, 'pid': c.process.pid} for c in
124
                self.containers.values()]