Ubuntu Pastebin

Paste from dimitern at Tue, 19 Apr 2016 10:19:07 +0000

Download as text
  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
#!/usr/bin/env python3

from apiclient.maas_client import (
    MAASClient,
    MAASDispatcher,
    MAASOAuth,
)
from collections import OrderedDict
import json, sys, random
from urllib.error import HTTPError as HTTPError

#### maas-19
#maas_url = 'http://10.10.19.2/MAAS/api/1.0/' # maas-19
#maas_key = 'mnWnPRwzSEFwe73cs2:ERmjYBtrWzSZWKPRzJ:zgTfZmma9gaG8dAVrx3Dtrz2Bau9kHye' # 19-root
#maas_key = 'zmtA5XNxm9QWg795nd:AxtqnqgJVqWUThjRPU:BHq5QW34HHh4DL4VRpnAXrATHMjmzghN' # 19-juju
#### ~maas-19

#### maas-hw
maas_url = 'http://10.14.0.1/MAAS/api/2.0/' # maas-hw
maas_key = '2WAF3wT9tHNEtTa9kV:A9CWR2ytFHwkN2mxN9:fTnk777tTFcV8xCUpTf85RfQLTeNcX7B' # hw-root
#### ~maas-hw

consumer_key, key, secret = maas_key.split(':')

class NoGzipMAASDispatcher:
    def __init__(self):
        self.dispatcher = MAASDispatcher()

    def dispatch_query(self, request_url, headers, method="GET", data=None):
        headers['accept-encoding'] = 'identity'
        return self.dispatcher.dispatch_query(request_url, headers, method, data)

def make_client(base_url, consumer_key, resource_token, resource_secret):
    maas_oauth = MAASOAuth(consumer_key, resource_token, resource_secret)
    nogzip_dispatcher = NoGzipMAASDispatcher()
    maas_client = MAASClient(maas_oauth, nogzip_dispatcher, base_url)
    return maas_client

def make_path(*items):
    if len(items) == 0:
        return tuple("",)
    items = list(items)
    items.append("")
    return tuple(items)

def client_request(method, path, op=None, **kwargs):
    try:
        client_method = client.__getattribute__(method)
    except AttributeError as e:
        print(('No such client method %q' % method))
        return {}
    try:
        if method == 'delete':
            response = client_method(make_path(*path))
        elif method == 'put':
            response = client_method(make_path(*path), **kwargs)
        else:
            response = client_method(make_path(*path), op, **kwargs)
        try:
            response_as_string = response.read().decode('utf-8')
            return json.loads(response_as_string)
        except ValueError:
            return response
    except HTTPError as e:
        print(('REQUEST %s FAILED:\nHTTP %s %s\n' % (e.geturl(), e.code, e.reason)))
        print((e.info()))
        body = e.read().decode('utf-8')
        try:
            return json.loads(body)
        except ValueError:
            return body

client = make_client(maas_url, consumer_key, key, secret)

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

def devices_new(mac_addresses, parent, hostname):
    params = dict(parent=parent)
    if hostname is not None:
        params['hostname'] = hostname
    if mac_addresses is not None:
        params['mac_addresses'] = mac_addresses

    #response = client_request('post', ['devices'], 'new', **params) # maas 1.9
    response = client_request('post', ['devices'], '', **params) # maas 2.0
    if 'system_id' in response:
        return response
    print('device creation failed:')
    print((json.dumps(response, indent=2)))
    return None

def devices_list():
    #return client_request('get', ['devices'], 'list') # maas 1.9
    return client_request('get', ['devices'], '') # maas 2.0

def fabrics_list():
    return client_request('get', ['fabrics'])

def subnets_read():
    return client_request('get', ['subnets'])

def device_delete(system_id):
    return client_request('delete', ['devices', system_id])

def interfaces_read(system_id):
    return client_request('get', ['nodes', system_id, 'interfaces'])

def interfaces_create(system_id, create_kind, **params):
    response = client_request('post', ['nodes', system_id, 'interfaces'], create_kind, **params)
    if 'id' in response:
        return response
    print('interface creation failed:')
    print((json.dumps(response, indent=2)))
    return None

def interfaces_update(system_id, interface_id, **params):
    response = client_request('put', ['nodes', system_id, 'interfaces', interface_id], **params)
    if 'id' in response:
        return response
    print('interface update failed:')
    print((json.dumps(response, indent=2)))
    return None

def interface_post(system_id, interface_id, op, **params):
    response = client_request('post', ['nodes', system_id, 'interfaces', interface_id], op, **params)
    if 'id' in response:
        return response
    print(('interface %s operation failed:' % op))
    print((json.dumps(response, indent=2)))
    return None

def interfaces_create_physical(system_id, name, mac_address, vlan):
    params = dict(name=name, mac_address=mac_address, vlan=vlan)
    return interfaces_create(system_id, 'create_physical', **params)

def interfaces_update_physical(system_id, interface_id, name, mac_address, vlan):
    params = dict(name=name, mac_address=mac_address, vlan=vlan)
    return interfaces_update(system_id, interface_id, **params)

def interfaces_create_vlan(system_id, vlan, parent):
    params = dict(vlan=vlan, parent=parent)
    return interfaces_create(system_id, 'create_vlan', **params)

def interface_link_subnet(system_id, interface_id, mode, subnet, ip_address=None):
    params = dict(mode=mode, subnet=subnet)
    if ip_address is not None:
        params['ip_address'] = ip_address
    return interface_post(system_id, interface_id, 'link_subnet', **params)

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

def list_interfaces(system_id):
    interfaces = interfaces_read(system_id)
    names2ids = {}
    print(('\nlisting existing interfaces on node %s' % system_id))
    for i in interfaces:
        names2ids[i['name']] = i['id']
        print(('\tname=%s, id=%s, vlan.vid=%s, vlan.id=%s, mac_address=%s, children=%r, links:' % (i['name'], i['id'], i['vlan']['vid'], i['vlan']['id'], i['mac_address'], i['children'])))
        for l in i['links']:
            subnet = {} if 'subnet' not in l else l['subnet']
            print(('\t\tid=%s, mode=%s, ip_address=%s, subnet={id=%s, name=%s, space=%s, vlan.vid=%s, gateway_ip=%s, cidr=%s}' % (l['id'], l['mode'], l.get('ip_address'), subnet.get('id'), subnet.get('name'), subnet.get('space'), subnet.get('vlan',{}).get('vid'), subnet.get('gateway_ip'), subnet.get('cidr'))))
    return names2ids

managed_fabric_id = ''
vlan_untagged_id = ''
vlan_admin_id = ''
vlan_public_id = ''
vlan_internal_id = ''
vlan_storage_id = ''
vlan_demo_internal_id = ''
vlan_demo_public_id = ''
vlan_demo_db_id = ''

def list_all_fabrics_and_vlans():
    global managed_fabric_id
    global vlan_untagged_id
    global vlan_admin_id
    global vlan_public_id
    global vlan_internal_id
    global vlan_storage_id
    global vlan_demo_internal_id
    global vlan_demo_public_id
    global vlan_demo_db_id

    print('\nlisting all fabrics and their vlans')
    fabrics = fabrics_list()
    for f in fabrics:
        print(('\tname=%s, id=%s, vlans:' % (f['name'], f['id'])))
        for v in f['vlans']:
            print(('\t\tname=%s, id=%s, vid=%s, mtu=%s' % (v['name'], v['id'], v['vid'], v['mtu'])))
            if f['name'] in ('managed', 'maas-management'):
                managed_fabric_id = f['id']
                vlan_vid, vlan_id = v['vid'], ('%s' % v['id'])
                if vlan_vid == 0: # untagged
                    vlan_untagged_id = vlan_id
                elif vlan_vid == 50: # public
                    vlan_public_id = vlan_id
                elif vlan_vid == 100: # internal
                    vlan_internal_id = vlan_id
                elif vlan_vid == 150: # admin
                    vlan_admin_id = vlan_id
                elif vlan_vid == 200: # storage
                    vlan_storage_id = vlan_id
                elif vlan_vid == 11: # demo-internal
                    vlan_demo_internal_id = vlan_id
                elif vlan_vid == 12: # demo-public
                    vlan_demo_public_id = vlan_id
                elif vlan_vid == 13: # demo-db
                    vlan_demo_db_id = vlan_id

    print(('\ndiscovered vlan ids of managed fabric %s:' % managed_fabric_id))
    print(('\tvlan_untagged_id=%s' % vlan_untagged_id))
    print(('\tvlan_admin_id=%s' % vlan_admin_id))
    print(('\tvlan_internal_id=%s' % vlan_internal_id))
    print(('\tvlan_public_id=%s' % vlan_public_id))
    print(('\tvlan_storage_id=%s' % vlan_storage_id))
    print(('\tvlan_demo_internal_id=%s' % vlan_demo_internal_id))
    print(('\tvlan_demo_public_id=%s' % vlan_demo_public_id))
    print(('\tvlan_demo_db_id=%s' % vlan_demo_db_id))

subnet_pxe = ''
subnet_admin = ''
subnet_internal = ''
subnet_public = ''
subnet_storage = ''
subnet_demo_internal = ''
subnet_demo_public = ''
subnet_demo_db = ''

def list_all_subnets():
    global subnet_pxe
    global subnet_admin
    global subnet_internal
    global subnet_public
    global subnet_storage
    global subnet_demo_internal
    global subnet_demo_public
    global subnet_demo_db

    print('\nlisting all subnets')
    subnets = subnets_read()
    for s in subnets:
        print(('\tname=%s, id=%s, space=%s, cidr=%s, vlan.name=%s. vlan.vid=%s' % (s['name'], s['id'], s['space'], s['cidr'], s['vlan']['name'], s['vlan']['vid'])))
        subnet_name, subnet_cidr = s['name'], ('cidr:%s' % s['cidr'])
        if subnet_name in ('pxe', 'maas-management'):
            subnet_pxe = subnet_cidr
        elif subnet_name in ('admin', 'admin-api'):
            subnet_admin = subnet_cidr
        elif subnet_name in ('internal', 'internal-api'):
            subnet_internal = subnet_cidr
        elif subnet_name in ('public', 'public-api'):
            subnet_public = subnet_cidr
        elif subnet_name in ('storage', 'storage-data'):
            subnet_storage = subnet_cidr
        elif subnet_name == 'demo-internal':
            subnet_demo_internal = subnet_cidr
        elif subnet_name == 'demo-public':
            subnet_demo_public = subnet_cidr
        elif subnet_name == 'demo-db':
            subnet_demo_db = subnet_cidr

    print('\ndiscovered subnet cidrs:')
    print(('\tsubnet_pxe=%s' % subnet_pxe))
    print(('\tsubnet_admin=%s' % subnet_admin))
    print(('\tsubnet_internal=%s' % subnet_internal))
    print(('\tsubnet_public=%s' % subnet_public))
    print(('\tsubnet_storage=%s' % subnet_storage))
    print(('\tsubnet_demo_internal=%s' % subnet_demo_internal))
    print(('\tsubnet_demo_public=%s' % subnet_demo_public))
    print(('\tsubnet_demo_db=%s' % subnet_demo_db))

def devices_delete_by_parent_ids(parent_ids):
    print(('\ndeleting all devices on parents %r' % parent_ids))
    devices = devices_list()
    for d in devices:
        device_id = d['system_id']
        if d['parent'] in parent_ids:
            device_delete(device_id)
            print(('\tdeleted device %s' % device_id))

def generate_mac_address():
    mac_address_template = '00:16:3e:xx:xx:xx'
    mac_address = ''
    for ch in mac_address_template:
        if ch == 'x':
            random_ch = '%x' % random.randint(0x0, 0x7)
            mac_address += random_ch
        else:
            mac_address += ch
    return mac_address

def create_physical_interface_and_link_subnet_mode_static(device_id, interface_name, vlan_id, subnet_cidr):
    print(('\ncreating new %s physical interface' % interface_name))
    mac_address = generate_mac_address()
    interface = interfaces_create_physical(device_id, interface_name, mac_address, vlan_id)
    if interface is not None:
        print(('\tcreated %s with id=%s; linking to subnet %s with mode=static' % (interface['name'], interface['id'], subnet_cidr)))
        interface = interface_link_subnet(device_id, interface['id'], 'static', subnet_cidr)
        if 'id' in interface:
            for l in interface['links']:
                print(('\t\tlink id=%s, mode=%s, ip_address=%s, subnet.cidr=%s, subnet.vlan.vid=%s' % (l['id'], l['mode'], l['ip_address'], l['subnet']['cidr'], l['subnet']['vlan']['vid'])))
    return interface

def create_multi_nic_device_with_parent(parent_id, interfaces_dict):
    eth0_mac_address = generate_mac_address()
    device = devices_new(eth0_mac_address, parent_id, None)
    if device is not None:
        device_id = device['system_id']
        print(('\tcreated device with system_id=%s, parent=%s, macaddress_set=%r' % (device['system_id'], device['parent'], device['macaddress_set'] if 'macaddress_set' in device else None)))

        names2ids = list_interfaces(device_id)

        for interface_name, vlan_id_subnet_cidr in list(interfaces_dict.items()):
            vlan_id, subnet_cidr = vlan_id_subnet_cidr
            if interface_name == 'eth0':
                print('\nupdating device eth0 linked vlan and subnet')
                eth0 = interfaces_update_physical(device_id, names2ids['eth0'], 'eth0', eth0_mac_address, vlan_id)
                if eth0 is None:
                    sys.exit(0)
                eth0 = interface_link_subnet(device_id, eth0['id'], 'static', subnet_cidr)
                if 'id' in eth0:
                    for l in eth0['links']:
                        print(('\t\tlink id=%s, mode=%s, ip_address=%s, subnet.cidr=%s, subnet.vlan.vid=%s' % (l['id'], l['mode'], l['ip_address'], l['subnet']['cidr'], l['subnet']['vlan']['vid'])))
            else:
                create_physical_interface_and_link_subnet_mode_static(device_id, interface_name, vlan_id, subnet_cidr)

        list_interfaces(device_id)

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

def main():
    list_all_fabrics_and_vlans()
    list_all_subnets()

    #parent_ids = ['node-d7b96c1c-9762-11e5-8e2e-00163e40c3b6', 'node-18489434-9eb0-11e5-bdef-00163e40c3b6'] # maas-19: node-1, node-3
    parent_ids = ['4y3h7p', '4y3h7r'] # maas-hw: node-11, node-21
    devices_delete_by_parent_ids(parent_ids)
    interfaces_dict = OrderedDict([
        ('eth0', (vlan_untagged_id, subnet_pxe)),
        ('eth1', (vlan_admin_id, subnet_admin)),
        ('eth2', (vlan_internal_id, subnet_internal)),
        ('eth3', (vlan_public_id, subnet_public)),
        ('eth4', (vlan_storage_id, subnet_storage)),
    ])

    print(('\ncreating new 2 multi-nic devices on parents: %r\n\twith interfaces: %r\n' % (parent_ids, interfaces_dict)))
    for parent_id in parent_ids:
        create_multi_nic_device_with_parent(parent_id, interfaces_dict)
        create_multi_nic_device_with_parent(parent_id, interfaces_dict)

    devices_delete_by_parent_ids(parent_ids)

if __name__ == '__main__':
    main()
Download as text