odata.py 13.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
from __future__ import absolute_import, division, print_function, unicode_literals
try:
    from urllib.parse import urlencode  # pylint: disable=F0401,E0611
except ImportError:
    from urllib import urlencode  # pylint: disable=F0401,E0611

import requests
from requests.auth import HTTPBasicAuth

from lxml import etree
try:
    from configparser import SafeConfigParser  # pylint: disable=F0401
except ImportError:
    from ConfigParser import SafeConfigParser  # pylint: disable=F0401
import uuid
from dateutil.parser import parse as tsparse

namespaces = {
    'b': "http://www.w3.org/2007/app",
    'atom': "http://www.w3.org/2005/Atom",
    'ds': "http://schemas.microsoft.com/ado/2007/08/dataservices",
    'm': "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
    }

25 26
ODATA_SUFFIX = "/Microsoft.Management.Odata.svc"

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

def namespace_split(tagname):
    if not '}' in tagname:
        return ('', tagname)
    namespace, tag = tagname.split('}')
    namespace = namespace[1:]
    return (namespace, tag)


def ns(namespace, name):
    return "{" + namespaces[namespace] + "}" + name


def is_string(value):
    try:
        return isinstance(value, basestring)  # pylint: disable=E0602
    except NameError:
        return isinstance(value, str)  # pylint: disable=E0602


def type_encode_argvalue(value):
    if type(value) == uuid.UUID:
        return "guid'{}'".format(value)
50 51 52 53 54
    if type(value) == bool:
        if value:
            return "true"
        else:
            return "false"
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    if is_string(value):
        return "'{}'".format(value)
    return value


class ODataException(Exception):
    def __init__(self, error_type, error_message, full_error):
        self.error_type = error_type
        self.error_message = error_message
        self.full_error = full_error


class Client(object):
    passman = None

70
    def __init__(self, baseurl, username, password, subscription=None,
Sigmund Augdal's avatar
Sigmund Augdal committed
71
                 principal=None):
72 73 74 75
        if baseurl.endswith("/"):
            baseurl = baseurl[:-1]
        if baseurl.endswith(ODATA_SUFFIX):
            baseurl = baseurl[:-len(ODATA_SUFFIX)]
76 77
        self.baseurl = baseurl
        self.auth = HTTPBasicAuth(username, password)
78
        self.session = requests.Session()
79
        self.subscription = subscription
Sigmund Augdal's avatar
Sigmund Augdal committed
80
        self.principal = principal
81

Sigmund Augdal's avatar
Sigmund Augdal committed
82 83
    def _format_url(self, resource, query=None, args=None, subresource=None,
                    expand=None):
84
        url = self.baseurl
85 86 87
        if self.subscription:
            url += "/" + self.subscription
        url += ODATA_SUFFIX
88 89 90 91 92 93 94 95 96 97 98
        fragments = {}
        if resource:
            url += "/" + resource
        if args:
            argstr = ",".join(("{key}={value}".format(key=key, value=type_encode_argvalue(value)) for key, value in args.items()))
            url = "{url}({argstr})".format(url=url, argstr=argstr)
        if subresource:
            url += "/" + subresource
        if query:
            argstr = " and ".join(("{key} eq {value}".format(key=key, value=type_encode_argvalue(query[key])) for key in query))
            fragments["$filter"] = argstr
99 100
        if expand:
            fragments["$expand"] = expand
101 102 103 104 105 106 107 108
        if fragments:
            url += "?" + urlencode(fragments)
        return url

    def _do_request(self, url, method="GET", reqdata=None):
        headers = {}
        if reqdata:
            headers["content-type"] = "application/atom+xml;type=entry"
Sigmund Augdal's avatar
Sigmund Augdal committed
109
        if self.principal:
110
            headers["x-ms-principal-id"] = self.principal
Sigmund Augdal's avatar
Sigmund Augdal committed
111 112
        resp = self.session.request(method, url, data=reqdata, headers=headers,
                                    auth=self.auth, verify=False)
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
        data = resp.content
        if not data:
            return None
        if resp.status_code >= 300:
            try:
                error_doc = etree.fromstring(data)
                errtype = ", ".join(error_doc.xpath('/m:error/m:innererror/m:type/text()', namespaces=namespaces))
                errmsg = ", ".join(error_doc.xpath('/m:error/m:innererror/m:message/text()', namespaces=namespaces))
                if not errmsg:
                    errmsg = error_doc.xpath('/m:error/m:message/text()', namespaces=namespaces)[0]
                print("Request failed with error: " + errtype)
                print(errmsg)
                print(data)
                raise ODataException(errtype, errmsg, error_doc)
            except etree.XMLSyntaxError as e2:
                print("Did not get xml error from SPF")
                print(data)
                raise e2
            except AttributeError as e2:
                print(e2)
        try:
            return etree.fromstring(data)
        except etree.XMLSyntaxError as e:
            print(e)
            print("Content that caused the issue:")
            print(data)
            print()
            raise e

    def get_collections(self):
        url = self._format_url(resource="")
        collections = self._do_request(url)
        return (collection for collection in collections.xpath('/b:service/b:workspace/b:collection/atom:title/text()', namespaces=namespaces))

147 148
    def query_collection(self, collection, query=None, expand=None, **kw_args):
        url = self._format_url(collection, query, kw_args, expand=expand)
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        collection = self._do_request(url)
        result = []
        for entry in collection.xpath('/atom:feed/atom:entry', namespaces=namespaces):
            result.append(Entry(entry, self))
        return result

    def get_from_collection(self, collection, subresource=None, **kw_args):
        url = self._format_url(collection, query=None, args=kw_args, subresource=subresource)
        collection = self._do_request(url)
        for entry in collection.xpath('/atom:entry', namespaces=namespaces):
            return Entry(entry, self)
        return None

    def delete_from_collection(self, collection, subresource=None, **kw_args):
        url = self._format_url(collection, query=None, args=kw_args, subresource=subresource)
        self._do_request(url, method="DELETE")

    def delete_resource(self, res):
        url = self.baseurl + "/" + res
        self._do_request(url, method="DELETE")

170 171 172 173 174 175 176
    def get_resource(self, resource):
        url = self.baseurl
        if self.subscription:
            url += "/" + self.subscription
        url += ODATA_SUFFIX
        url += "/" + resource
        repl = self._do_request(url)
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        if repl is None:
            return []
        if repl.tag == ns('atom', 'feed'):
            return [Entry(entry, self) for entry in repl.xpath('/atom:feed/atom:entry', namespaces=namespaces)]
        else:
            return Entry(repl, self)

    def create_link(self, links_collection, target):
        url = self.baseurl + "/" + links_collection
        entry, obj = create_entry()
        add_property(obj, "ID", target)
        res = self._do_request(url, "POST", etree.tostring(entry))
        return res


class Entry(object):
    def __init__(self, element, vmm_client):
        self.vmm_client = vmm_client
        self.element = element
196
        self.inline_resources = {}
197 198 199 200 201 202 203 204 205 206 207
        self.properties = self.parse_properties(element)
        self.resources = self.parse_resources(element)

    def get_resource(self, resource):
        return self.vmm_client.get_resource(self.resources[resource])

    def parse_resources(self, element):
        resources = {}
        for link in element.xpath("atom:link", namespaces=namespaces):
            rel = link.get('rel')
            if rel == "edit":
208
                continue
209 210 211
            title = link.get('title')
            href = link.get('href')
            resources[title] = href
212 213 214 215 216 217
            inline_resources = []
            for entry in link.xpath('m:inline/atom:feed/atom:entry', namespaces=namespaces):
                inline_resources.append(Entry(entry, self))
            if inline_resources:
                self.inline_resources[title] = inline_resources

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        return resources

    def parse_property(self, prop):
        inttypes = set(("Edm.Int32", "Edm.Int64", "Edm.Byte", "Edm.Int16"))
        collectiontypes = set(("VMM.ErrorInfo", "VMM.UserAndRole", "VMM.VPNVMNetworkGateway"))
        if prop.get(ns("m", "null")) == "true":
            return None
        property_type = prop.get(ns("m", "type"))
        if not property_type:
            return prop.text
        if property_type == "Edm.Boolean":
            if prop.text == "true":
                return True
            return False
        if property_type in inttypes:
            return int(prop.text)
        if property_type == "Edm.Guid":
            return uuid.UUID(prop.text)
        if property_type == "Edm.DateTime":
            return tsparse(prop.text)
        if property_type in collectiontypes or property_type.startswith("Collection("):
            return self.parse_properties(prop, "*")

    def parse_properties(self, prop, xpath="atom:content/m:properties/*"):
        element = {}
        for tag in prop.xpath(xpath, namespaces=namespaces):
            (namespace, tagname) = namespace_split(tag.tag)
            if namespace == namespaces['ds']:
                key = tagname
            else:
                key = tag.tag
            element[key] = self.parse_property(tag)
        return element


def create_entry():
    entry = etree.Element(ns('atom', 'entry'))
    content = etree.SubElement(entry, ns('atom', 'content'))
    content.set("type", "application/xml")
    vm = etree.SubElement(content, ns('m', "properties"))
    return entry, vm


def add_property(tag, key, value, datatype=None):
    prop = etree.SubElement(tag, ns('ds', key))
    if type(value) == uuid.UUID:
        prop.set(ns('m', 'type'), "Edm.Guid")
        prop.text = str(value)
    elif type(value) == bool:
        prop.set(ns('m', 'type'), "Edm.Boolean")
        if value:
            prop.text = "true"
        else:
            prop.text = "false"
    elif type(value) == int:
        prop.set(ns('m', 'type'), "Edm.Int64")
Sigmund Augdal's avatar
Sigmund Augdal committed
274
        prop.text = str(value)
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    else:
        prop.text = value
    if datatype:
        prop.set(ns('m', 'type'), datatype)
    return prop


class VMMClient(Client):
    def create_vm(self, StampId, Name, CloudId, **kwargs):
        entry, vm = create_entry()
        add_property(vm, "StampId", StampId)
        add_property(vm, "CloudId", CloudId)
        add_property(vm, "Name", Name)
        add_property(vm, "NewVirtualNetworkAdapterInput", "", datatype="Collection(VMM.NewVMVirtualNetworkAdapterInput)")
        for key, value in kwargs.items():
            if value == "":
                print("skipping empty value")
            else:
                add_property(vm, key, value)
#        print(etree.tostring(entry, pretty_print=True))
        result = Entry(self._do_request(self._format_url("VirtualMachines"), method="POST", reqdata=etree.tostring(entry)), self)
        return result

    def get_vm(self, stampid, vmid):
        return self.get_from_collection("VirtualMachines", StampId=stampid, ID=vmid)

    def delete_vm(self, stampid, vmid):
        self.delete_from_collection("VirtualMachines", StampId=stampid, ID=vmid)

304 305 306 307 308 309 310 311 312
    def update_vm(self, stampid, vmid, **kw_args):
        url = self._format_url("VirtualMachines", args={"StampId": stampid, "ID": vmid})
        entry, vm = create_entry()
        add_property(vm, "StampId", stampid)
        add_property(vm, "ID", vmid)
        for key, value in kw_args.items():
            add_property(vm, key, value)
        self._do_request(url, method="PATCH", reqdata=etree.tostring(entry))

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    def vm_operation(self, stampid, vmid, operation):
        url = self._format_url("VirtualMachines", args={"StampId": stampid, "ID": vmid})
        entry, vm = create_entry()
        add_property(vm, "StampId", stampid)
        add_property(vm, "ID", vmid)
        add_property(vm, "Operation", operation)
        self._do_request(url, method="PATCH", reqdata=etree.tostring(entry))

    def get_vm_addresses(self, stampid, vmid):
        addresses = []
        try:
            guest_infos = self.query_collection("GuestInfos", query={"StampId": stampid, "VMId": vmid})
            for guest_info in guest_infos:
                addresses += guest_info.properties["IPv4Addresses"].split(";")
                print(addresses)
        except:
            pass
        addresses = [a for a in addresses if a]
        addresses = [a for a in addresses if a != "127.0.0.1"]
        return addresses

    def get_job(self, stampid, jobid):
        return self.get_from_collection("Jobs", StampId=stampid, ID=jobid)


def get_config():
    cfg = SafeConfigParser()
    cfg.read("nova.cfg")
    return cfg

ALL_COLLECTIONS = (
    'ApplicationHostTemplates',
    'ApplicationHosts',
    'BasicStatistics',
    'CapabilityProfiles',
    'CloudCapacities',
    'Clouds',
    'ComputerTierTemplates',
    'ComputerTiers',
    'GuestInfos',
    'HardwareProfiles',
    'ISOs',
    'Jobs',
    'LibraryShares',
    'LogicalNetworks',
    'PerformanceData',
    'QuotaAndUsageComponents',
    'RunAsAccounts',
    'ServiceTemplates',
    'Services',
    'StaticIPAddressPools',
    'UserRoles',
    'VMCheckPoints',
    'VMNetworks',
    'VMSubnets',
    'VMTemplates',
    'VirtualDVDDrives',
    'VirtualDiskDrives',
    'VirtualHardDisks',
    'VirtualMachines',
    'VirtualNetworkAdapters',
    'VirtualSCSIAdapters',
    )

NO_NEEDED_PARAMETER = (
    "BasicStatistics",
    "Clouds",
    "ComputerTierTemplates",
    "ComputerTiers",
    "HardwareProfiles",
    "ServiceTemplates",
    "Services",
    "UserRoles",
    "VMNetworks",
    "VMTemplates"
    "VirtualMachines",
    )
NEED_STAMPID = (
    "CapabilityProfiles",
    "CloudCapacities",
    "Jobs",
    "LibraryShares",
    "LogicalNetworks",
    'RunAsAccounts',
    "StaticIPAddressPools",
    "VMCheckPoints",
    "VMSubnets",
    'VirtualHardDisks',
    "VirtualDiskDrives",
    'VirtualNetworkAdapters',
    )
NEEDS_STAMPID_VMID = ("GuestInfos", "PerformanceData", )
NEED_MORE = ("QuotaAndUsageComponents",)