summaryrefslogtreecommitdiff
path: root/heat/tests/openstack/nova/fakes.py
blob: 17628a985df0fd7627f689b87f24adc1e2419ae6 (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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2011 OpenStack Foundation
#
# 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 mock
from novaclient import client as base_client
from novaclient import exceptions as nova_exceptions
import requests
from urllib import parse as urlparse

from heat.tests import fakes


NOVA_API_VERSION = "2.1"

Client = base_client.Client(NOVA_API_VERSION).__class__


def fake_exception(status_code=404, message=None, details=None):
    resp = mock.Mock()
    resp.status_code = status_code
    resp.headers = None
    body = {'error': {'message': message, 'details': details}}
    return nova_exceptions.from_response(resp, body, None)


class FakeClient(fakes.FakeClient, Client):

    def __init__(self, *args, **kwargs):
        super(FakeClient, self).__init__(direct_use=False)
        self.client = FakeSessionClient(session=mock.Mock(), **kwargs)


class FakeSessionClient(base_client.SessionClient):

    def __init__(self, *args, **kwargs):
        super(FakeSessionClient, self).__init__(*args, **kwargs)
        self.callstack = []

    def request(self, url, method, **kwargs):
        # Check that certain things are called correctly
        if method in ['GET', 'DELETE']:
            if 'body' in kwargs:
                raise AssertionError('Request body in %s' % method)
        elif method == 'PUT':
            if 'body' not in kwargs:
                raise AssertionError('No request body in %s' % method)

        # Call the method
        args = urlparse.parse_qsl(urlparse.urlparse(url)[4])
        kwargs.update(args)
        munged_url = url.rsplit('?', 1)[0]
        munged_url = munged_url.strip('/').replace('/', '_').replace(
            '.', '_').replace(' ', '_')
        munged_url = munged_url.replace('-', '_')

        callback = "%s_%s" % (method.lower(), munged_url)

        if not hasattr(self, callback):
            raise AssertionError('Called unknown API method: %s %s, '
                                 'expected fakes method name: %s' %
                                 (method, url, callback))

        # Note the call
        self.callstack.append((method, url, kwargs.get('body')))

        status, body = getattr(self, callback)(**kwargs)
        response = requests.models.Response()
        if isinstance(status, dict):
            response.status_code = status.pop("status")
            response.headers = status
        else:
            response.status_code = status
        return response, body

    #
    # Servers
    #
    def get_servers_detail(self, **kw):
        if kw.get('marker') == '56789':
            return (200, {"servers": []})

        return (
            200,
            {"servers": [{"id": "1234",
                          "name": "sample-server",
                          "OS-EXT-SRV-ATTR:instance_name":
                          "sample-server",
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "e4d909c290d0fb1ca068ffaddf22cbd0",
                          "status": "BUILD",
                          "progress": 60,
                          "addresses": {"public": [{"version": 4,
                                                    "addr": "1.2.3.4"},
                                                   {"version": 4,
                                                    "addr": "5.6.7.8"}],
                                        "private": [{"version": 4,
                                                     "addr": "10.11.12.13"}]},
                          "accessIPv4": "",
                          "accessIPv6": "",
                          "metadata": {"Server Label": "Web Head 1",
                                       "Image Version": "2.1"}},

                         # 1
                         {"id": "5678",
                          "name": "sample-server2",
                          "OS-EXT-AZ:availability_zone": "nova2",
                          "OS-EXT-SRV-ATTR:instance_name":
                          "sample-server2",
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "9e107d9d372bb6826bd81d3542a419d6",
                          "status": "ACTIVE",
                          "accessIPv4": "192.0.2.0",
                          "accessIPv6": "::babe:4317:0A83",
                          "addresses": {"public": [{"version": 4,
                                                    "addr": "4.5.6.7",
                                                    "OS-EXT-IPS-MAC:mac_addr":
                                                    "fa:16:3e:8c:22:aa"},
                                                   {"version": 4,
                                                    "addr": "5.6.9.8",
                                                    "OS-EXT-IPS-MAC:mac_addr":
                                                    "fa:16:3e:8c:33:bb"}],
                                        "private": [{"version": 4,
                                                     "addr": "10.13.12.13",
                                                     "OS-EXT-IPS-MAC:mac_addr":
                                                     "fa:16:3e:8c:44:cc"}]},
                          "metadata": {}},
                         # 2
                         {"id": "9101",
                          "name": "hard-reboot",
                          "OS-EXT-SRV-ATTR:instance_name":
                          "hard-reboot",
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "9e44d8d435c43dd8d96bb63ed995605f",
                          "status": "HARD_REBOOT",
                          "accessIPv4": "",
                          "accessIPv6": "",
                          "addresses": {"public": [{"version": 4,
                                                    "addr": "172.17.1.2"},
                                                   {"version": 4,
                                                    "addr": "10.20.30.40"}],
                                        "private": [{"version": 4,
                                                     "addr": "10.13.12.13"}]},
                          "metadata": {"Server Label": "DB 1"}},
                         # 3
                         {"id": "9102",
                          "name": "server-with-no-ip",
                          "OS-EXT-SRV-ATTR:instance_name":
                          "server-with-no-ip",
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "c1365ba78c624df9b2ff446515a682f5",
                          "status": "ACTIVE",
                          "accessIPv4": "",
                          "accessIPv6": "",
                          "addresses": {"empty_net": []},
                          "metadata": {"Server Label": "DB 1"}},
                         # 4
                         {"id": "9999",
                          "name": "sample-server3",
                          "OS-EXT-SRV-ATTR:instance_name":
                          "sample-server3",
                          "OS-EXT-AZ:availability_zone": "nova3",
                          "image": {"id": 3, "name": "sample image"},
                          "flavor": {"id": 3, "name": "m1.large"},
                          "hostId": "9e107d9d372bb6826bd81d3542a419d6",
                          "status": "ACTIVE",
                          "accessIPv4": "",
                          "accessIPv6": "",
                          "addresses": {
                              "public": [{"version": 4, "addr": "4.5.6.7"},
                                         {"version": 4, "addr": "5.6.9.8"}],
                              "private": [{"version": 4,
                                           "addr": "10.13.12.13"}]},
                          "metadata": {"Server Label": "DB 1"},
                          "os-extended-volumes:volumes_attached":
                              [{"id":
                                    "66359157-dace-43ab-a7ed-a7e7cd7be59d"}]},
                         # 5
                         {"id": 56789,
                          "name": "server-with-metadata",
                          "OS-EXT-SRV-ATTR:instance_name":
                          "sample-server2",
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "9e107d9d372bb6826bd81d3542a419d6",
                          "status": "ACTIVE",
                          "accessIPv4": "192.0.2.0",
                          "accessIPv6": "::babe:4317:0A83",
                          "addresses": {"public": [{"version": 4,
                                                    "addr": "4.5.6.7"},
                                                   {"version": 4,
                                                    "addr": "5.6.9.8"}],
                                        "private": [{"version": 4,
                                                     "addr": "10.13.12.13"}]},
                          "metadata": {'test': '123', 'this': 'that'}},
                         # 6
                         {"id": "WikiDatabase",
                          "name": "server-with-metadata",
                          "OS-EXT-STS:task_state": None,
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "9e107d9d372bb6826bd81d3542a419d6",
                          "status": "ACTIVE",
                          "accessIPv4": "192.0.2.0",
                          "accessIPv6": "::babe:4317:0A83",
                          "addresses": {"public": [{"version": 4,
                                                    "addr": "4.5.6.7"},
                                                   {"version": 4,
                                                    "addr": "5.6.9.8"}],
                                        "private": [{"version": 4,
                                                     "addr": "10.13.12.13"}]},
                          "metadata": {'test': '123', 'this': 'that'}},
                         # 7
                         {"id": "InstanceInResize",
                          "name": "server-with-metadata",
                          "OS-EXT-STS:task_state": 'resize_finish',
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "9e107d9d372bb6826bd81d3542a419d6",
                          "status": "ACTIVE",
                          "accessIPv4": "192.0.2.0",
                          "accessIPv6": "::babe:4317:0A83",
                          "addresses": {"public": [{"version": 4,
                                                    "addr": "4.5.6.7"},
                                                   {"version": 4,
                                                    "addr": "5.6.9.8"}],
                                        "private": [{"version": 4,
                                                     "addr": "10.13.12.13"}]},
                          "metadata": {'test': '123', 'this': 'that'}},
                         # 8
                         {"id": "InstanceInActive",
                          "name": "server-with-metadata",
                          "OS-EXT-STS:task_state": 'active',
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "9e107d9d372bb6826bd81d3542a419d6",
                          "status": "ACTIVE",
                          "accessIPv4": "192.0.2.0",
                          "accessIPv6": "::babe:4317:0A83",
                          "addresses": {"public": [{"version": 4,
                                                    "addr": "4.5.6.7"},
                                                   {"version": 4,
                                                    "addr": "5.6.9.8"}],
                                        "private": [{"version": 4,
                                                     "addr": "10.13.12.13"}]},
                          "metadata": {'test': '123', 'this': 'that'}},
                         # 9
                         {"id": "AnotherServer",
                          "name": "server-with-metadata",
                          "OS-EXT-STS:task_state": 'active',
                          "image": {"id": 2, "name": "sample image"},
                          "flavor": {"id": 1, "name": "256 MB Server"},
                          "hostId": "9e107d9d372bb6826bd81d3542a419d6",
                          "status": "ACTIVE",
                          "accessIPv4": "192.0.2.0",
                          "accessIPv6": "::babe:4317:0A83",
                          "addresses": {"public": [{"version": 4,
                                                    "addr": "4.5.6.7"},
                                                   {"version": 4,
                                                    "addr": "5.6.9.8"}],
                                        "private": [{"version": 4,
                                                     "addr": "10.13.12.13"}]},
                          "metadata": {'test': '123', 'this': 'that'}}]})

    def get_servers_1234(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][0]}
        return (200, r)

    def get_servers_56789(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][5]}
        return (200, r)

    def get_servers_WikiServerOne(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][0]}
        return (200, r)

    def get_servers_WikiDatabase(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][6]}
        return (200, r)

    def get_servers_InstanceInResize(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][7]}
        return (200, r)

    def get_servers_InstanceInActive(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][8]}
        return (200, r)

    def get_servers_AnotherServer(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][9]}
        return (200, r)

    def get_servers_WikiServerOne1(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][0]}
        return (200, r)

    def get_servers_WikiServerOne2(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][3]}
        return (200, r)

    def get_servers_5678(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][1]}
        return (200, r)

    def delete_servers_1234(self, **kw):
        return (202, None)

    def get_servers_9999(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][4]}
        return (200, r)

    def get_servers_9102(self, **kw):
        r = {'server': self.get_servers_detail()[1]['servers'][3]}
        return (200, r)

    #
    # Server actions
    #

    def post_servers_1234_action(self, body, **kw):
        _body = None
        resp = 202
        if len(body.keys()) != 1:
            raise AssertionError('No keys in request body')
        action = next(iter(body))
        keys = list(body[action].keys()) if body[action] is not None else None
        if action == 'reboot':
            if keys != ['type']:
                raise AssertionError('Unexpection action keys for %s: %s',
                                     action, keys)
            if body[action]['type'] not in ['HARD', 'SOFT']:
                raise AssertionError('Unexpected reboot type %s',
                                     body[action]['type'])
        elif action == 'rebuild':
            if 'adminPass' in keys:
                keys.remove('adminPass')
            if keys != ['imageRef']:
                raise AssertionError('Unexpection action keys for %s: %s',
                                     action, keys)
            _body = self.get_servers_1234()[1]
        elif action == 'confirmResize':
            if body[action] is not None:
                raise AssertionError('Unexpected data for confirmResize: %s',
                                     body[action])
            # This one method returns a different response code
            return (204, None)
        elif action in ['revertResize',
                        'migrate',
                        'rescue', 'unrescue',
                        'suspend', 'resume',
                        'lock', 'unlock',
                        'forceDelete']:
            if body[action] is not None:
                raise AssertionError('Unexpected data for %s: %s',
                                     action, body[action])
        else:
            expected_keys = {
                'resize': {'flavorRef'},
                'addFixedIp': {'networkId'},
                'removeFixedIp': {'address'},
                'addFloatingIp': {'address'},
                'removeFloatingp': {'address'},
                'createImage': {'name', 'metadata'},
                'changePassword': {'adminPass'},
                'os-getConsoleOutput': {'length'},
                'os-getVNCConsole': {'type'},
                'os-migrateLive': {'host', 'block_migration',
                                   'disk_over_commit'},
            }

            if action in expected_keys:
                if set(keys) != set(expected_keys[action]):
                    raise AssertionError('Unexpection action keys for %s: %s',
                                         action, keys)
            else:
                raise AssertionError("Unexpected server action: %s" % action)

            if action == 'createImage':
                resp = {"status": 202,
                        "location": "http://blah/images/456"}
            if action == 'os-getConsoleOutput':
                return (202, {'output': 'foo'})

        return (resp, _body)

    def post_servers_5678_action(self, body, **kw):
        _body = None
        resp = 202
        if len(body.keys()) != 1:
            raise AssertionError("No action in body")
        action = next(iter(body))
        if action in ['addFloatingIp',
                      'removeFloatingIp',
                      ]:
            keys = list(body[action].keys())
            if keys != ['address']:
                raise AssertionError('Unexpection action keys for %s: %s',
                                     action, keys)

        return (resp, _body)

    #
    # Flavors
    #

    def get_flavors(self, **kw):
        return (200, {'flavors': [
            {'id': 1, 'name': '256 MB Server', 'ram': 256, 'disk': 10,
             'OS-FLV-EXT-DATA:ephemeral': 10},
            {'id': 2, 'name': 'm1.small', 'ram': 512, 'disk': 20,
             'OS-FLV-EXT-DATA:ephemeral': 20},
            {'id': 3, 'name': 'm1.large', 'ram': 512, 'disk': 20,
             'OS-FLV-EXT-DATA:ephemeral': 30}
        ]})

    def get_flavors_256_MB_Server(self, **kw):
        raise fake_exception()

    def get_flavors_m1_small(self, **kw):
        raise fake_exception()

    def get_flavors_m1_large(self, **kw):
        raise fake_exception()

    def get_flavors_1(self, **kw):
        return (200, {'flavor': {
            'id': 1, 'name': '256 MB Server', 'ram': 256, 'disk': 10,
            'OS-FLV-EXT-DATA:ephemeral': 10}})

    def get_flavors_2(self, **kw):
        return (200, {'flavor': {
            'id': 2, 'name': 'm1.small', 'ram': 512, 'disk': 20,
            'OS-FLV-EXT-DATA:ephemeral': 20}})

    def get_flavors_3(self, **kw):
        return (200, {'flavor': {
            'id': 3, 'name': 'm1.large', 'ram': 512, 'disk': 20,
            'OS-FLV-EXT-DATA:ephemeral': 30}})

    #
    # Interfaces
    #

    def get_servers_5678_os_interface(self, **kw):
        return (200, {'interfaceAttachments':
                      [{"fixed_ips":
                        [{"ip_address": "10.0.0.1",
                          "subnet_id": "f8a6e8f8-c2ec-497c-9f23-da9616de54ef"
                          }],
                        "port_id": "ce531f90-199f-48c0-816c-13e38010b442"
                        }]})

    #
    # Floating ips
    #

    def get_os_floating_ips_1(self, **kw):
        return (200, {'floating_ip': {'id': 1,
                                      'fixed_ip': '10.0.0.1',
                                      'ip': '11.0.0.1'}})

    def post_os_floating_ips(self, body, **kw):
        return (202, self.get_os_floating_ips_1()[1])

    def delete_os_floating_ips_1(self, **kw):
        return (204, None)

    #
    # Images
    #
    def get_images_detail(self, **kw):
        return (200, {'images': [{'id': 1,
                                  'name': 'CentOS 5.2',
                                  "updated": "2010-10-10T12:00:00Z",
                                  "created": "2010-08-10T12:00:00Z",
                                  "status": "ACTIVE",
                                  "metadata": {"test_key": "test_value"},
                                  "links": {}},
                                 {"id": 743,
                                  "name": "My Server Backup",
                                  "serverId": 1234,
                                  "updated": "2010-10-10T12:00:00Z",
                                  "created": "2010-08-10T12:00:00Z",
                                  "status": "SAVING",
                                  "progress": 80,
                                  "links": {}},
                                 {"id": 744,
                                  "name": "F17-x86_64-gold",
                                  "serverId": 9999,
                                  "updated": "2010-10-10T12:00:00Z",
                                  "created": "2010-08-10T12:00:00Z",
                                  "status": "SAVING",
                                  "progress": 80,
                                  "links": {}},
                                 {"id": 745,
                                  "name": "F17-x86_64-cfntools",
                                  "serverId": 9998,
                                  "updated": "2010-10-10T12:00:00Z",
                                  "created": "2010-08-10T12:00:00Z",
                                  "status": "SAVING",
                                  "progress": 80,
                                  "links": {}},
                                 {"id": 746,
                                  "name": "F20-x86_64-cfntools",
                                  "serverId": 9998,
                                  "updated": "2010-10-10T12:00:00Z",
                                  "created": "2010-08-10T12:00:00Z",
                                  "status": "SAVING",
                                  "progress": 80,
                                  "links": {}}]})

    def get_images_1(self, **kw):
        return (200, {'image': self.get_images_detail()[1]['images'][0]})

    get_images_456 = get_images_1
    get_images_image_name = get_images_1

    #
    # Keypairs
    #
    def get_os_keypairs(self, *kw):
        return (200, {"keypairs": [{'fingerprint': 'FAKE_KEYPAIR',
                                    'name': 'test',
                                    'public_key': 'foo'}]})

    def get_os_keypairs_test(self, *kw):
        return (200, {"keypair": {'fingerprint': 'FAKE_KEYPAIR',
                                  'name': 'test',
                                  'public_key': 'foo'}})

    def get_os_keypairs_test2(self, *kw):
        raise fake_exception()

    def get_os_availability_zone(self, *kw):
        return (200, {"availabilityZoneInfo": [{'zoneName': 'nova1'}]})

    def get_os_networks(self, **kw):
        return (200, {'networks':
                [{'label': 'public',
                  'id': 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'},
                 {'label': 'foo',
                  'id': '42'},
                 {'label': 'foo',
                  'id': '42'}]})

    #
    # Limits
    #
    def get_limits(self, *kw):
        return (200, {'limits': {'absolute': {'maxServerMeta': 3,
                                              'maxPersonalitySize': 10240,
                                              'maxPersonality': 5}}})