aci.py 5.64 KB
Newer Older
1 2 3 4 5
"""Parse and Represent the APPC ACI specification."""
import collections
import logging
import json

6
logger = logging.getLogger('nrm')
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
spec = collections.namedtuple('Field', ['cls', 'required'])


class SpecField(object):

    """Object part of the ACI Image Manifest fields."""

    fields = {}

    def __init__(self):
        """Create empty field."""
        pass

    def load(self, data):
        """Load fields."""
        for key in self.fields:
            spec = self.fields[key]
            if key not in data:
                if spec.required:
                    logger.error("Missing key from manifest: %s", key)
                    return False
            else:
                ok, v = self.loadfield(data[key], spec.cls)
                if not ok:
                    logger.error("Error for key %s in %s", key, self.__class__)
                    return False
                setattr(self, key, v)
        return True

    def loadfield(self, data, cls):
        """load data as if from a field of the provided cls.

        Make sure the basic types are also respected.
        """
        ret = cls()
        if not hasattr(ret, 'load'):
            if not isinstance(data, cls):
                logger.error("Wrong data type %s, expected: %s", cls,
                             data.__class__)
                return (False, None)
            else:
                return (True, data)
        else:
            return (ret.load(data), ret)


class Scheduler(SpecField):

    """Scheduler information for a container."""

    classes = ['SCHED_FIFO', 'SCHED_HPC', 'SCHED_OTHER']

    fields = {"policy": spec(unicode, True),
60
              "priority": spec(unicode, False),
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
              }

    def __init__(self):
        """Create scheduler object."""
        pass

    def load(self, data):
        """Load configuration from json text."""
        ret = super(Scheduler, self).load(data)
        if not ret:
            return ret
        # check scheduler class & prio
        if self.policy not in self.classes:
            logger.error("Wrong scheduling class %s, not any of %r", data,
                         Scheduler.classes)
            return False
        if self.policy != "SCHED_OTHER":
            logger.warning("scheduler priority forced as 0 " +
                           "for non default policies")
            self.priority = "0"
        return True


class CPUSet(SpecField):

    """Represent a CPUSet field."""

    def __init__(self):
        """Create an empty set."""
        pass

    def load(self, data):
        """Load from json object."""
        self.value = data
        return True


class MemSet(SpecField):

    """Represent a MemSet field."""

    def __init__(self):
        """Create an empty set."""
        pass

    def load(self, data):
        """Load from json object."""
        self.value = data
        return True


class Container(SpecField):

    """Container Information."""

    fields = {"cpus": spec(CPUSet, True),
              "mems": spec(MemSet, True)
              }

    def __init__(self):
        """Create empty container."""
        pass

    def load(self, data):
        """Load container information."""
        return super(Container, self).load(data)

128

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
class PerfWrapper(SpecField):

    """Information on whether to use perf for a container."""

    fields = {"enabled": spec(unicode, False)
              }

    def __init__(self):
        """Create empty perf wrapper."""
        pass

    def load(self, data):
        """Load perf wrapper information."""
        ret = super(PerfWrapper, self).load(data)
        if not ret:
            return ret
        if self.enabled not in ["0", "False", "1", "True"]:
            logger.error("Invalid value of perfwrapper enabled: %s",
                         self.enabled)
            return False
        return True
150

151

152 153 154 155 156
class IsolatorList(SpecField):

    """Represent the list of isolator in a Manifest."""

    types = {"argo/scheduler": spec(Scheduler, False),
157 158
             "argo/container": spec(Container, True),
             "argo/perfwrapper": spec(PerfWrapper, False)
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
             }

    def __init__(self):
        """Create empty list."""
        pass

    def load(self, data):
        """Load from json struct."""
        for e in data:
            name = e['name']
            if name in self.types:
                t = self.types[name]
                ok, v = super(IsolatorList, self).loadfield(e['value'], t.cls)
                if not ok:
                    logger.error("Error with %s in %s", name, self.__class__)
                    return False
                setattr(self, name.lstrip("argo/"), v)
        for k in self.types:
            if self.types[k].required:
                assert name.lstrip("argo/") in self.__dict__
        return True


class App(SpecField):

    """Represent the App part of an Image Manifest."""

    # attribute, subclass, required
    fields = {"environment": spec(list, False),
              "isolators": spec(IsolatorList, True),
              }

    def __init__(self):
        """Create empty container."""
        pass

    def load(self, data):
        """Load from json dict."""
        return super(App, self).load(data)


class ImageManifest(SpecField):

    """Represent an ACI Image Manifest."""

    fields = {"acKind": spec(unicode, True),
              "acVersion": spec(unicode, True),
              "name": spec(unicode, True),
207
              "app": spec(App, True),
208 209 210 211 212 213 214 215 216 217 218
              }

    def __init__(self):
        """Create empty manifest."""
        pass

    def load(self, filename):
        """Load a manifest from JSON file."""
        with open(filename, 'r') as f:
            data = json.load(f)
        return super(ImageManifest, self).load(data)