odata.py 14.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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
17
import re
18 19 20 21 22 23 24 25

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"
    }

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

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

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)
51 52 53 54 55
    if type(value) == bool:
        if value:
            return "true"
        else:
            return "false"
56 57 58 59 60
    if is_string(value):
        return "'{}'".format(value)
    return value


61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
def convert_property_value(property_type, property_value):
    inttypes = set(("Edm.Int32", "Edm.Int64", "Edm.Byte", "Edm.Int16"))
    if not property_type:
        return property_value
    if property_type == "Edm.Boolean":
        if property_value == "true":
            return True
        return False
    if property_type in inttypes:
        return int(property_value)
    if property_type == "Edm.Guid":
        return uuid.UUID(property_value)
    if property_type == "Edm.DateTime":
        return tsparse(property_value)


77 78 79 80 81 82 83 84 85 86
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

87
    def __init__(self, baseurl, username, password, subscription=None,
Sigmund Augdal's avatar
Sigmund Augdal committed
88
                 principal=None):
89 90 91 92
        if baseurl.endswith("/"):
            baseurl = baseurl[:-1]
        if baseurl.endswith(ODATA_SUFFIX):
            baseurl = baseurl[:-len(ODATA_SUFFIX)]
93 94
        self.baseurl = baseurl
        self.auth = HTTPBasicAuth(username, password)
95
        self.session = requests.Session()
96
        self.subscription = subscription
Sigmund Augdal's avatar
Sigmund Augdal committed
97
        self.principal = principal
98

Sigmund Augdal's avatar
Sigmund Augdal committed
99 100
    def _format_url(self, resource, query=None, args=None, subresource=None,
                    expand=None):
101
        url = self.baseurl
102 103 104
        if self.subscription:
            url += "/" + self.subscription
        url += ODATA_SUFFIX
105 106 107 108 109 110 111 112 113 114 115
        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
116 117
        if expand:
            fragments["$expand"] = expand
118 119 120 121 122 123 124 125
        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
126
        if self.principal:
127
            headers["x-ms-principal-id"] = self.principal
Sigmund Augdal's avatar
Sigmund Augdal committed
128 129
        resp = self.session.request(method, url, data=reqdata, headers=headers,
                                    auth=self.auth, verify=False)
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        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]
                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))

161 162
    def query_collection(self, collection, query=None, expand=None, **kw_args):
        url = self._format_url(collection, query, kw_args, expand=expand)
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
        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")

184 185 186 187 188 189 190
    def get_resource(self, resource):
        url = self.baseurl
        if self.subscription:
            url += "/" + self.subscription
        url += ODATA_SUFFIX
        url += "/" + resource
        repl = self._do_request(url)
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        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
210
        self.inline_resources = {}
211 212 213 214 215 216 217 218 219 220 221
        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":
222
                continue
223 224 225
            title = link.get('title')
            href = link.get('href')
            resources[title] = href
226 227 228 229 230 231
            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

232 233 234
        return resources

    def parse_property(self, prop):
235 236
        collectiontypes = set(("VMM.ErrorInfo", "VMM.UserAndRole",
                               "VMM.VPNVMNetworkGateway"))
237 238 239
        if prop.get(ns("m", "null")) == "true":
            return None
        property_type = prop.get(ns("m", "type"))
240 241 242 243 244 245 246 247 248 249
        property_value = prop.text

        if property_type:
            if property_type in collectiontypes:
                return self.parse_properties(prop, "*")
            if property_type.startswith("Collection("):
                subtype = re.search('\((.*)\)', property_type).group(1)
                return [convert_property_value(subtype, el.text) for el in
                        prop.xpath('ds:element', namespaces=namespaces)]
        return convert_property_value(property_type, property_value)
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

    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
284
        prop.text = str(value)
285 286 287
    elif type(value) == dict:
        for key, value in value.items():
            add_property(prop, key, value)
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
    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)

317 318 319 320 321
    def update_entry(self, collection, stampid, _id, **kw_args):
        url = self._format_url(collection, args={"StampId": stampid, "ID": _id})
        entry, props = create_entry()
        add_property(props, "StampId", stampid)
        add_property(props, "ID", _id)
322
        for key, value in kw_args.items():
323
            add_property(props, key, value)
324 325
        self._do_request(url, method="PATCH", reqdata=etree.tostring(entry))

326 327 328
    def update_vm(self, stampid, vmid, **kw_args):
        self.update_entry("VirtualMachines", stampid, vmid, **kw_args)

329 330 331 332 333 334 335 336 337
    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):
338
        return self.get_all_vm_addresses(stampid, vmid)['v4']
339 340

    def get_vm_addresses_v6(self, stampid, vmid):
341
        return self.get_all_vm_addresses(stampid, vmid)['v6']
342 343 344

    def get_all_vm_addresses(self, stampid, vmid):
        addresses = {'v4': [], 'v6': []}
345 346 347
        try:
            guest_infos = self.query_collection("GuestInfos", query={"StampId": stampid, "VMId": vmid})
            for guest_info in guest_infos:
348 349
                addresses['v4'] += guest_info.properties["IPv4Addresses"].split(";")
                addresses['v6'] += guest_info.properties["IPv6Addresses"].split(";")
350 351
        except:
            pass
352 353 354 355 356
        addresses['v4'] = [a for a in addresses['v4'] if a]
        addresses['v4'] = [a for a in addresses['v4'] if a != "127.0.0.1"]
        addresses['v6'] = [a for a in addresses['v6'] if a]
        addresses['v6'] = [a for a in addresses['v6'] if a != "::1"]

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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        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",)