aboutsummaryrefslogtreecommitdiffstats
path: root/lcm/pub/nfvi/vim/api/multivim/api.py
blob: 82e42913f5350eb8eefbff47e94f83b928d927fd (plain)
1
2
3
4
5
6
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
60
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
128
129
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
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
207
208
209
210
211
212
213
214
215
216
217
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
274
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
304
305
306
307
308
309
310
311
312
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
# Copyright 2017 ZTE Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import logging

from lcm.pub.nfvi.vim.lib.vimexception import VimException
from lcm.pub.utils.restcall import req_by_msb
from lcm.pub.nfvi.vim import const

logger = logging.getLogger(__name__)

VIM_DRIVER_BASE_URL = "api/multicloud/v0"


def call(vim_id, tenant_id, res, method, data=''):
    if data and not isinstance(data, str):
        data = json.JSONEncoder().encode(data)
    vim_id = json.JSONDecoder().decode(vim_id) if isinstance(vim_id, str) else vim_id
    vim_id = "%s_%s" % (vim_id['cloud_owner'], vim_id['cloud_regionid'])
    url = "{base_url}/{vim_id}{tenant_id}/{res}".format(
        base_url=VIM_DRIVER_BASE_URL,
        vim_id=vim_id,
        tenant_id="/" + tenant_id if tenant_id else "",
        res=res)
    # url = "{base_url}/{cloud_owner}/{cloud_regionid}{tenant_id}/{res}".format(
    #    base_url=VIM_DRIVER_BASE_URL,
    #    cloud_owner=cloud_owner,
    #    cloud_regionid=cloud_regionid,
    #    tenant_id="/" + tenant_id if tenant_id else "",
    #    res=res)
    ret = req_by_msb(url, method, data)
    if ret[0] > 0:
        raise VimException(ret[1], ret[2])
    return json.JSONDecoder().decode(ret[1]) if ret[1] else {}


#######################################################################


def create_image(vim_id, tenant_id, data):
    return call(vim_id, tenant_id, "images", "POST", data)


def delete_image(vim_id, tenant_id, image_id):
    return call(vim_id, tenant_id, "images/%s" % image_id, "DELETE")


def get_image(vim_id, tenant_id, image_id):
    return call(vim_id, tenant_id, "images/%s" % image_id, "GET")


def list_image(vim_id, tenant_id):
    return call(vim_id, tenant_id, "images", "GET")


######################################################################


def create_network(vim_id, tenant_id, data):
    return call(vim_id, tenant_id, "networks", "POST", data)


def delete_network(vim_id, tenant_id, network_id):
    return call(vim_id, tenant_id, "networks/%s" % network_id, "DELETE")


def get_network(vim_id, tenant_id, network_id):
    return call(vim_id, tenant_id, "networks/%s" % network_id, "GET")


def list_network(vim_id, tenant_id):
    return call(vim_id, tenant_id, "networks", "GET")


######################################################################


def create_subnet(vim_id, tenant_id, data):
    return call(vim_id, tenant_id, "subnets", "POST", data)


def delete_subnet(vim_id, tenant_id, subnet_id):
    return call(vim_id, tenant_id, "subnets/%s" % subnet_id, "DELETE")


def get_subnet(vim_id, tenant_id, subnet_id):
    return call(vim_id, tenant_id, "subnets/%s" % subnet_id, "GET")


def list_subnet(vim_id, tenant_id):
    return call(vim_id, tenant_id, "subnets", "GET")


######################################################################


def create_port(vim_id, tenant_id, data):
    return call(vim_id, tenant_id, "ports", "POST", data)


def delete_port(vim_id, tenant_id, port_id):
    return call(vim_id, tenant_id, "ports/%s" % port_id, "DELETE")


def get_port(vim_id, tenant_id, port_id):
    return call(vim_id, tenant_id, "ports/%s" % port_id, "GET")


def list_port(vim_id, tenant_id):
    return call(vim_id, tenant_id, "ports", "GET")


######################################################################


def create_flavor(vim_id, tenant_id, data):
    return call(vim_id, tenant_id, "flavors", "POST", data)


def delete_flavor(vim_id, tenant_id, flavor_id):
    return call(vim_id, tenant_id, "flavors/%s" % flavor_id, "DELETE")


def get_flavor(vim_id, tenant_id, flavor_id):
    return call(vim_id, tenant_id, "flavors/%s" % flavor_id, "GET")


def list_flavor(vim_id, tenant_id):
    return call(vim_id, tenant_id, "flavors", "GET")


######################################################################


def create_vm(vim_id, tenant_id, data):
    return call(vim_id, tenant_id, "servers", "POST", data)


def delete_vm(vim_id, tenant_id, vm_id):
    return call(vim_id, tenant_id, "servers/%s" % vm_id, "DELETE")


def get_vm(vim_id, tenant_id, vm_id):
    return call(vim_id, tenant_id, "servers/%s" % vm_id, "GET")


def list_vm(vim_id, tenant_id):
    return call(vim_id, tenant_id, "servers", "GET")


######################################################################


def create_volume(vim_id, tenant_id, data):
    return call(vim_id, tenant_id, "volumes", "POST", data)


def delete_volume(vim_id, tenant_id, volume_id):
    return call(vim_id, tenant_id, "volumes/%s" % volume_id, "DELETE")


def get_volume(vim_id, tenant_id, volume_id):
    return call(vim_id, tenant_id, "volumes/%s" % volume_id, "GET")


def list_volume(vim_id, tenant_id):
    return call(vim_id, tenant_id, "volumes", "GET")


######################################################################


def list_tenant(vim_id, tenant_name=""):
    res = "tenants"
    if tenant_name:
        res = "%s?name=%s" % (res, tenant_name)
    return call(vim_id, "", res, "GET")


######################################################################


class MultiVimApi:

    def login(self, connect_info):
        self.vim_id = connect_info["vimid"]
        self.tenant_name = connect_info["tenant"]
        tenants = list_tenant(self.vim_id)
        for tenant in tenants["tenants"]:
            if self.tenant_name == tenant["name"]:
                self.tenant_id = tenant["id"]
                return [0, connect_info]
        raise VimException(1, "Tenant(%s) not exist" % self.tenant_name)

    def query_net(self, auth_info, net_id):
        net = get_network(self.vim_id, self.tenant_id, net_id)
        return [0, {
            "id": net.get("id", ""),
            "name": net.get("name", ""),
            "status": net.get("status", ""),
            "admin_state_up": net.get("admin_state_up", True),
            "network_type": net.get("networkType", ""),
            "physical_network": net.get("physicalNetwork", ""),
            "segmentation_id": net.get("segmentationId", ""),
            "tenant_id": self.tenant_id,
            "tenant_name": self.tenant_name,
            "subnets": net.get("subnets", []),
            "shared": net.get("shared", True),
            "router_external": net.get("routerExternal", "")
        }]

    def query_nets(self, auth_info):
        nets = list_network(self.vim_id, self.tenant_id)
        return [0, {"networks": [{
            "id": net.get("id", ""),
            "name": net.get("name", ""),
            "status": net.get("status", ""),
            "admin_state_up": net.get("admin_state_up", True),
            "network_type": net.get("networkType", ""),
            "physical_network": net.get("physicalNetwork", ""),
            "segmentation_id": net.get("segmentationId", ""),
            "tenant_id": self.tenant_id,
            "tenant_name": self.tenant_name,
            "subnets": net.get("subnets", []),
            "shared": net.get("shared", True),
            "router_external": net.get("routerExternal", "")
        } for net in nets["networks"]]}]

    def query_subnet(self, auth_info, subnet_id):
        subnet_info = get_subnet(self.vim_id, self.tenant_id, subnet_id)
        ret = [0, {}]
        ret[1]["id"] = subnet_id
        ret[1]["name"] = subnet_info.get("name", "")
        ret[1]["status"] = ""
        ret[1]["ip_version"] = subnet_info.get("ipVersion", 4)
        ret[1]["cidr"] = subnet_info.get("cidr", "")
        ret[1]["allocation_pools"] = subnet_info.get("allocationPools", [])
        ret[1]["enable_dhcp"] = subnet_info.get("enableDhcp", False)
        ret[1]["gateway_ip"] = subnet_info.get("gatewayIp", "")
        ret[1]["host_routes"] = subnet_info.get("hostRoutes", [])
        ret[1]["dns_nameservers"] = subnet_info.get("dnsNameservers", [])
        return ret

    def query_port(self, auth_info, port_id):
        port_info = get_port(self.vim_id, self.tenant_id, port_id)
        ret = [0, {}]
        ret[1]["id"] = port_id
        ret[1]["name"] = port_info.get("name", "")
        ret[1]["network_id"] = port_info.get("networkId", "")
        ret[1]["tenant_id"] = self.tenant_id,
        ret[1]["ip"] = port_info.get("ip", "")
        ret[1]["subnet_id"] = port_info.get("subnetId", "")
        ret[1]["mac_address"] = port_info.get("macAddress", "")
        ret[1]["status"] = port_info.get("status", "")
        ret[1]["admin_state_up"] = port_info.get("admin_state_up", True)
        ret[1]["device_id"] = port_info.get("device_id", "")
        return ret

    def create_port(self, auth_info, data):
        return [0, data]

    def delete_port(self, auth_info, port_id):
        return [0, ""]

    def create_image(self, auth_info, data):
        image_data = {
            "name": data["image_name"],
            "imagePath": data["image_url"],
            "imageType": data["image_type"],
            "containerFormat": "bare",
            "visibility": "public",
            "properties": []
        }
        image = create_image(self.vim_id, self.tenant_id, image_data)
        return [0, {
            "id": image["id"],
            "name": image["name"],
            const.RES_TYPE_KEY: image["returnCode"]}
        ]

    def get_image(self, auth_info, image_id):
        image = get_image(self.vim_id, self.tenant_id, image_id)
        return [0, {
            "id": image["id"],
            "name": image["name"],
            "size": image["size"],
            "status": image["status"]}
        ]

    def get_images(self, auth_info):
        images = list_image(self.vim_id, self.tenant_id)
        return [0, {"image_list": [{
            "id": img["id"],
            "name": img["name"],
            "size": img["size"],
            "status": img["status"]
        } for img in images["images"]]}]

    def delete_image(self, auth_info, image_id):
        return [0, ""]

    def create_network(self, auth_info, data):
        net_data = {
            "name": data["network_name"],
            "shared": True,
            "networkType": data["network_type"]
        }
        if "physical_network" in data and data['physical_network']:
            net_data["physicalNetwork"] = data['physical_network']
        if "vlan_transparent" in data and data["vlan_transparent"]:
            net_data["vlanTransparent"] = data["vlan_transparent"]
        if "segmentation_id" in data and data['segmentation_id']:
            net_data["segmentationId"] = data["segmentation_id"]
        if "routerExternal" in data and data['routerExternal']:
            net_data["routerExternal"] = data["routerExternal"]
        net = create_network(self.vim_id, self.tenant_id, net_data)
        network_id = net["id"]
        ret_net = {
            "status": net.get("status", ""),
            "id": network_id,
            "name": net.get("name", ""),
            "provider:segmentation_id": net.get("segmentationId", ""),
            "provider:network_type": net.get("networkType", ""),
            const.RES_TYPE_KEY: net["returnCode"],
            "subnet_list": []
        }
        if "subnet_list" in data and data["subnet_list"]:
            subnet = data["subnet_list"][0]
            subnet_data = {
                "networkId": network_id,
                "name": subnet["subnet_name"],
                "cidr": subnet["cidr"],
                "ipVersion": const.IPV4,
                "enableDhcp": False
            }
            if "ip_version" in subnet and subnet["ip_version"]:
                subnet_data["ipVersion"] = int(subnet["ip_version"])
            if "enable_dhcp" in subnet and subnet["enable_dhcp"]:
                if isinstance(subnet["enable_dhcp"], str):
                    subnet["enable_dhcp"] = (subnet["enable_dhcp"]).strip().lower() in "true"
                subnet_data["enableDhcp"] = int(subnet["enable_dhcp"]) == const.ENABLE_DHCP
            if "gateway_ip" in subnet and subnet["gateway_ip"]:
                subnet_data["gatewayIp"] = subnet["gateway_ip"]
            if "dns_nameservers" in subnet and subnet["dns_nameservers"]:
                subnet_data["dnsNameservers"] = subnet["dns_nameservers"]
            if "allocation_pools" in subnet and subnet["allocation_pools"]:
                subnet_data["allocationPools"] = subnet["allocation_pools"]
            if "host_routes" in subnet and subnet["host_routes"]:
                subnet_data["hostRoutes"] = subnet["host_routes"]
            subnet_create = create_subnet(self.vim_id, self.tenant_id, subnet_data)
            ret_net["subnet_list"].append({
                "id": subnet_create["id"],
                "name": subnet_create["name"],
                const.RES_TYPE_KEY: net["returnCode"]})
        return [0, ret_net]

    def delete_network(self, auth_info, network_id):
        return delete_network(self.vim_id, self.tenant_id, network_id)

    def delete_subnet(self, auth_info, subnet_id):
        return delete_subnet(self.vim_id, self.tenant_id, subnet_id)