Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / logic / tests.py @ 1d04ef8b

History | View | Annotate | Download (25.3 kB)

1
# vim: set fileencoding=utf-8 :
2
# Copyright 2012 GRNET S.A. All rights reserved.
3
#
4
# Redistribution and use in source and binary forms, with or without
5
# modification, are permitted provided that the following conditions
6
# are met:
7
#
8
#   1. Redistributions of source code must retain the above copyright
9
#      notice, this list of conditions and the following disclaimer.
10
#
11
#  2. Redistributions in binary form must reproduce the above copyright
12
#     notice, this list of conditions and the following disclaimer in the
13
#     documentation and/or other materials provided with the distribution.
14
#
15
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
16
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25
# SUCH DAMAGE.
26
#
27
# The views and conclusions contained in the software and documentation are
28
# those of the authors and should not be interpreted as representing official
29
# policies, either expressed or implied, of GRNET S.A.
30

    
31
# Provides automated tests for logic module
32

    
33
from random import randint
34

    
35
from django.test import TestCase
36

    
37
from synnefo.db.models import *
38
from synnefo.db import models_factory as mfactory
39
from synnefo.logic import reconciliation
40
from synnefo.lib.utils import split_time
41
from datetime import datetime
42
from mock import patch
43
from synnefo.api.util import allocate_resource
44
from synnefo.logic.callbacks import (update_db, update_net, update_network,
45
                                     update_build_progress)
46
from snf_django.utils.testing import mocked_quotaholder
47

    
48
now = datetime.now
49
from time import time
50
import json
51

    
52
## Test Callbacks
53

    
54

    
55
@patch('synnefo.lib.amqp.AMQPClient')
56
class UpdateDBTest(TestCase):
57
    def create_msg(self, **kwargs):
58
        """Create snf-ganeti-eventd message"""
59
        msg = {'event_time': split_time(time())}
60
        msg['type'] = 'ganeti-op-status'
61
        msg['status'] = 'success'
62
        msg['jobId'] = 1
63
        msg['logmsg'] = 'Dummy Log'
64
        for key, val in kwargs.items():
65
            msg[key] = val
66
        message = {'body': json.dumps(msg)}
67
        return message
68

    
69
    def test_missing_attribute(self, client):
70
        update_db(client, json.dumps({'body': {}}))
71
        client.basic_nack.assert_called_once()
72

    
73
    def test_unhandled_exception(self, client):
74
        update_db(client, {})
75
        client.basic_reject.assert_called_once()
76

    
77
    def test_missing_instance(self, client):
78
        msg = self.create_msg(operation='OP_INSTANCE_STARTUP',
79
                              instance='foo')
80
        update_db(client, msg)
81
        client.basic_nack.assert_called_once()
82

    
83
    def test_wrong_type(self, client):
84
        msg = self.create_msg(type="WRONG_TYPE")
85
        update_db(client, msg)
86
        client.basic_ack.assert_called_once()
87

    
88
    def test_old_msg(self, client):
89
        from time import sleep
90
        from datetime import datetime
91
        old_time = time()
92
        sleep(0.01)
93
        new_time = datetime.fromtimestamp(time())
94
        vm = mfactory.VirtualMachineFactory(backendtime=new_time)
95
        vm.operstate = 'STOPPED'
96
        vm.save()
97
        msg = self.create_msg(operation='OP_INSTANCE_STARTUP',
98
                              event_time=split_time(old_time),
99
                              instance=vm.backend_vm_id)
100
        update_db(client, msg)
101
        client.basic_ack.assert_called_once()
102
        db_vm = VirtualMachine.objects.get(id=vm.id)
103
        self.assertEquals(db_vm.operstate, "STOPPED")
104
        self.assertEquals(db_vm.backendtime, new_time)
105

    
106
    def test_start(self, client):
107
        vm = mfactory.VirtualMachineFactory()
108
        msg = self.create_msg(operation='OP_INSTANCE_STARTUP',
109
                              instance=vm.backend_vm_id)
110
        update_db(client, msg)
111
        client.basic_ack.assert_called_once()
112
        db_vm = VirtualMachine.objects.get(id=vm.id)
113
        self.assertEqual(db_vm.operstate, 'STARTED')
114

    
115
    def test_stop(self, client):
116
        vm = mfactory.VirtualMachineFactory()
117
        msg = self.create_msg(operation='OP_INSTANCE_SHUTDOWN',
118
                              instance=vm.backend_vm_id)
119
        update_db(client, msg)
120
        client.basic_ack.assert_called_once()
121
        db_vm = VirtualMachine.objects.get(id=vm.id)
122
        self.assertEqual(db_vm.operstate, 'STOPPED')
123

    
124
    def test_reboot(self, client):
125
        vm = mfactory.VirtualMachineFactory()
126
        msg = self.create_msg(operation='OP_INSTANCE_REBOOT',
127
                              instance=vm.backend_vm_id)
128
        update_db(client, msg)
129
        client.basic_ack.assert_called_once()
130
        db_vm = VirtualMachine.objects.get(id=vm.id)
131
        self.assertEqual(db_vm.operstate, 'STARTED')
132

    
133
    def test_remove(self, client):
134
        vm = mfactory.VirtualMachineFactory()
135
        # Also create a NIC
136
        mfactory.NetworkInterfaceFactory(machine=vm)
137
        msg = self.create_msg(operation='OP_INSTANCE_REMOVE',
138
                              instance=vm.backend_vm_id)
139
        with mocked_quotaholder():
140
            update_db(client, msg)
141
        client.basic_ack.assert_called_once()
142
        db_vm = VirtualMachine.objects.get(id=vm.id)
143
        self.assertEqual(db_vm.operstate, 'DESTROYED')
144
        self.assertTrue(db_vm.deleted)
145
        # Check that nics are deleted
146
        self.assertFalse(db_vm.nics.all())
147

    
148
    def test_create(self, client):
149
        vm = mfactory.VirtualMachineFactory()
150
        msg = self.create_msg(operation='OP_INSTANCE_CREATE',
151
                              instance=vm.backend_vm_id)
152
        update_db(client, msg)
153
        client.basic_ack.assert_called_once()
154
        db_vm = VirtualMachine.objects.get(id=vm.id)
155
        self.assertEqual(db_vm.operstate, 'STARTED')
156

    
157
    def test_create_error(self, client):
158
        """Test that error create sets vm to ERROR state"""
159
        vm = mfactory.VirtualMachineFactory()
160
        msg = self.create_msg(operation='OP_INSTANCE_CREATE',
161
                              instance=vm.backend_vm_id,
162
                              status='error')
163
        update_db(client, msg)
164
        client.basic_ack.assert_called_once()
165
        db_vm = VirtualMachine.objects.get(id=vm.id)
166
        self.assertEqual(db_vm.operstate, 'ERROR')
167

    
168
    def test_remove_from_error(self, client):
169
        """Test that error removes delete error builds"""
170
        vm = mfactory.VirtualMachineFactory(operstate='ERROR')
171
        # Also create a NIC
172
        mfactory.NetworkInterfaceFactory(machine=vm)
173
        msg = self.create_msg(operation='OP_INSTANCE_REMOVE',
174
                              instance=vm.backend_vm_id)
175
        with mocked_quotaholder():
176
            update_db(client, msg)
177
        client.basic_ack.assert_called_once()
178
        db_vm = VirtualMachine.objects.get(id=vm.id)
179
        self.assertEqual(db_vm.operstate, 'DESTROYED')
180
        self.assertTrue(db_vm.deleted)
181
        # Check that nics are deleted
182
        self.assertFalse(db_vm.nics.all())
183

    
184
    def test_other_error(self, client):
185
        """Test that other error messages do no affect the VM"""
186
        vm = mfactory.VirtualMachineFactory()
187
        msg = self.create_msg(operation='OP_INSTANCE_STARTUP',
188
                              instance=vm.backend_vm_id,
189
                              status='error')
190
        update_db(client, msg)
191
        client.basic_ack.assert_called_once()
192
        db_vm = VirtualMachine.objects.get(id=vm.id)
193
        self.assertEqual(db_vm.operstate, vm.operstate)
194
        self.assertEqual(db_vm.backendtime, vm.backendtime)
195

    
196

    
197
@patch('synnefo.lib.amqp.AMQPClient')
198
class UpdateNetTest(TestCase):
199
    def create_msg(self, **kwargs):
200
        """Create snf-ganeti-hook message"""
201
        msg = {'event_time': split_time(time())}
202
        msg['type'] = 'ganeti-net-status'
203
        msg['status'] = 'success'
204
        msg['jobId'] = 1
205
        msg['logmsg'] = 'Dummy Log'
206
        for key, val in kwargs.items():
207
            msg[key] = val
208
        message = {'body': json.dumps(msg)}
209
        return message
210

    
211
    def test_missing_attribute(self, client):
212
        update_net(client, json.dumps({'body': {}}))
213
        client.basic_nack.assert_called_once()
214

    
215
    def test_unhandled_exception(self, client):
216
        update_net(client, {})
217
        client.basic_reject.assert_called_once()
218

    
219
    def test_wrong_type(self, client):
220
        msg = self.create_msg(type="WRONG_TYPE")
221
        update_net(client, msg)
222
        client.basic_ack.assert_called_once()
223

    
224
    def test_missing_instance(self, client):
225
        msg = self.create_msg(operation='OP_INSTANCE_STARTUP',
226
                              instance='foo')
227
        update_net(client, msg)
228
        client.basic_nack.assert_called_once()
229

    
230
    def test_no_nics(self, client):
231
        vm = mfactory.VirtualMachineFactory(operstate='ERROR')
232
        mfactory.NetworkInterfaceFactory(machine=vm)
233
        mfactory.NetworkInterfaceFactory(machine=vm)
234
        mfactory.NetworkInterfaceFactory(machine=vm)
235
        self.assertEqual(len(vm.nics.all()), 3)
236
        msg = self.create_msg(nics=[],
237
                              instance=vm.backend_vm_id)
238
        update_net(client, msg)
239
        client.basic_ack.assert_called_once()
240
        db_vm = VirtualMachine.objects.get(id=vm.id)
241
        self.assertEqual(len(db_vm.nics.all()), 0)
242

    
243
    def test_empty_nic(self, client):
244
        vm = mfactory.VirtualMachineFactory(operstate='ERROR')
245
        for public in [True, False]:
246
            net = mfactory.NetworkFactory(public=public)
247
            msg = self.create_msg(nics=[{'network': net.backend_id}],
248
                                  instance=vm.backend_vm_id)
249
            update_net(client, msg)
250
            client.basic_ack.assert_called_once()
251
            db_vm = VirtualMachine.objects.get(id=vm.id)
252
            nics = db_vm.nics.all()
253
            self.assertEqual(len(nics), 1)
254
            self.assertEqual(nics[0].index, 0)
255
            self.assertEqual(nics[0].ipv4, '')
256
            self.assertEqual(nics[0].ipv6, '')
257
            self.assertEqual(nics[0].mac, '')
258
            if public:
259
                self.assertEqual(nics[0].firewall_profile,
260
                                 settings.DEFAULT_FIREWALL_PROFILE)
261
            else:
262
                self.assertEqual(nics[0].firewall_profile, '')
263

    
264
    def test_full_nic(self, client):
265
        vm = mfactory.VirtualMachineFactory(operstate='ERROR')
266
        net = mfactory.NetworkFactory(subnet='10.0.0.0/24')
267
        pool = net.get_pool()
268
        self.assertTrue(pool.is_available('10.0.0.22'))
269
        pool.save()
270
        msg = self.create_msg(nics=[{'network': net.backend_id,
271
                                     'ip': '10.0.0.22',
272
                                     'mac': 'aa:bb:cc:00:11:22'}],
273
                              instance=vm.backend_vm_id)
274
        update_net(client, msg)
275
        client.basic_ack.assert_called_once()
276
        db_vm = VirtualMachine.objects.get(id=vm.id)
277
        nics = db_vm.nics.all()
278
        self.assertEqual(len(nics), 1)
279
        self.assertEqual(nics[0].index, 0)
280
        self.assertEqual(nics[0].ipv4, '10.0.0.22')
281
        self.assertEqual(nics[0].ipv6, '')
282
        self.assertEqual(nics[0].mac, 'aa:bb:cc:00:11:22')
283
        pool = net.get_pool()
284
        self.assertFalse(pool.is_available('10.0.0.22'))
285
        pool.save()
286

    
287

    
288
@patch('synnefo.lib.amqp.AMQPClient')
289
class UpdateNetworkTest(TestCase):
290
    def create_msg(self, **kwargs):
291
        """Create snf-ganeti-eventd message"""
292
        msg = {'event_time': split_time(time())}
293
        msg['type'] = 'ganeti-network-status'
294
        msg['status'] = 'success'
295
        msg['jobId'] = 1
296
        msg['logmsg'] = 'Dummy Log'
297
        for key, val in kwargs.items():
298
            msg[key] = val
299
        message = {'body': json.dumps(msg)}
300
        return message
301

    
302
    def test_missing_attribute(self, client):
303
        update_network(client, json.dumps({'body': {}}))
304
        client.basic_nack.assert_called_once()
305

    
306
    def test_unhandled_exception(self, client):
307
        update_network(client, {})
308
        client.basic_reject.assert_called_once()
309

    
310
    def test_wrong_type(self, client):
311
        msg = self.create_msg(type="WRONG_TYPE")
312
        update_network(client, msg)
313
        client.basic_ack.assert_called_once()
314

    
315
    def test_missing_network(self, client):
316
        msg = self.create_msg(operation='OP_NETWORK_CREATE',
317
                              network='foo')
318
        update_network(client, msg)
319
        client.basic_nack.assert_called_once()
320

    
321
    def test_create(self, client):
322
        back_network = mfactory.BackendNetworkFactory(operstate='PENDING')
323
        net = back_network.network
324
        net.state = 'ACTIVE'
325
        net.save()
326
        back1 = back_network.backend
327

    
328
        back_network2 = mfactory.BackendNetworkFactory(operstate='PENDING',
329
                                                       network=net)
330
        back2 = back_network2.backend
331
        # Message from first backend network
332
        msg = self.create_msg(operation='OP_NETWORK_CONNECT',
333
                              network=net.backend_id,
334
                              cluster=back1.clustername)
335
        update_network(client, msg)
336
        client.basic_ack.assert_called_once()
337

    
338
        back_net = BackendNetwork.objects.get(id=back_network.id)
339
        self.assertEqual(back_net.operstate, 'ACTIVE')
340
        db_net = Network.objects.get(id=net.id)
341
        self.assertEqual(db_net.state, 'ACTIVE')
342
        # msg from second backend network
343
        msg = self.create_msg(operation='OP_NETWORK_CONNECT',
344
                              network=net.backend_id,
345
                              cluster=back2.clustername)
346
        update_network(client, msg)
347
        client.basic_ack.assert_called_once()
348

    
349
        db_net = Network.objects.get(id=net.id)
350
        self.assertEqual(db_net.state, 'ACTIVE')
351
        back_net = BackendNetwork.objects.get(id=back_network.id)
352
        self.assertEqual(back_net.operstate, 'ACTIVE')
353

    
354
    def test_create_offline_backend(self, client):
355
        """Test network creation when a backend is offline"""
356
        net = mfactory.NetworkFactory(state='ACTIVE')
357
        bn1 = mfactory.BackendNetworkFactory(network=net)
358
        bn2 = mfactory.BackendNetworkFactory(network=net,
359
                                             backend__offline=True)
360
        msg = self.create_msg(operation='OP_NETWORK_CONNECT',
361
                              network=net.backend_id,
362
                              cluster=bn1.backend.clustername)
363
        update_network(client, msg)
364
        client.basic_ack.assert_called_once()
365
        new_net = Network.objects.get(id=net.id)
366
        self.assertEqual(new_net.state, 'ACTIVE')
367

    
368
    def test_disconnect(self, client):
369
        bn1 = mfactory.BackendNetworkFactory(operstate='ACTIVE')
370
        net1 = bn1.network
371
        net1.state = "ACTIVE"
372
        net1.state = 'ACTIVE'
373
        net1.save()
374
        bn2 = mfactory.BackendNetworkFactory(operstate='ACTIVE',
375
                                             network=net1)
376
        msg = self.create_msg(operation='OP_NETWORK_DISCONNECT',
377
                              network=net1.backend_id,
378
                              cluster=bn2.backend.clustername)
379
        update_network(client, msg)
380
        client.basic_ack.assert_called_once()
381
        self.assertEqual(Network.objects.get(id=net1.id).state, 'ACTIVE')
382
        self.assertEqual(BackendNetwork.objects.get(id=bn2.id).operstate,
383
                         'PENDING')
384

    
385
    def test_remove(self, client):
386
        mfactory.MacPrefixPoolTableFactory()
387
        mfactory.BridgePoolTableFactory()
388
        bn = mfactory.BackendNetworkFactory(operstate='ACTIVE')
389
        for old_state in ['success', 'canceled', 'error']:
390
            for flavor in Network.FLAVORS.keys():
391
                bn.operstate = old_state
392
                bn.save()
393
                net = bn.network
394
                net.state = 'ACTIVE'
395
                net.flavor = flavor
396
                if flavor == 'PHYSICAL_VLAN':
397
                    net.link = allocate_resource('bridge')
398
                if flavor == 'MAC_FILTERED':
399
                    net.mac_prefix = allocate_resource('mac_prefix')
400
                net.save()
401
                msg = self.create_msg(operation='OP_NETWORK_REMOVE',
402
                                      network=net.backend_id,
403
                                      cluster=bn.backend.clustername)
404
                with mocked_quotaholder():
405
                    update_network(client, msg)
406
                client.basic_ack.assert_called_once()
407
                db_bnet = BackendNetwork.objects.get(id=bn.id)
408
                self.assertEqual(db_bnet.operstate,
409
                                 'DELETED')
410
                db_net = Network.objects.get(id=net.id)
411
                self.assertEqual(db_net.state, 'DELETED', flavor)
412
                self.assertTrue(db_net.deleted)
413
                if flavor == 'PHYSICAL_VLAN':
414
                    pool = BridgePoolTable.get_pool()
415
                    self.assertTrue(pool.is_available(net.link))
416
                if flavor == 'MAC_FILTERED':
417
                    pool = MacPrefixPoolTable.get_pool()
418
                    self.assertTrue(pool.is_available(net.mac_prefix))
419

    
420
    def test_remove_offline_backend(self, client):
421
        """Test network removing when a backend is offline"""
422
        mfactory.BridgePoolTableFactory()
423
        net = mfactory.NetworkFactory(flavor='PHYSICAL_VLAN',
424
                                      state='ACTIVE',
425
                                      link='prv12')
426
        bn1 = mfactory.BackendNetworkFactory(network=net)
427
        mfactory.BackendNetworkFactory(network=net,
428
                                       backend__offline=True)
429
        msg = self.create_msg(operation='OP_NETWORK_REMOVE',
430
                              network=net.backend_id,
431
                              cluster=bn1.backend.clustername)
432
        with mocked_quotaholder():
433
            update_network(client, msg)
434
        client.basic_ack.assert_called_once()
435
        new_net = Network.objects.get(id=net.id)
436
        self.assertEqual(new_net.state, 'ACTIVE')
437
        self.assertFalse(new_net.deleted)
438

    
439
    def test_error_opcode(self, client):
440
        for state, _ in Network.OPER_STATES:
441
            bn = mfactory.BackendNetworkFactory()
442
            bn.operstate = state
443
            bn.save()
444
            network = bn.network
445
            network.state = state
446
            network.save()
447
            for opcode, _ in BackendNetwork.BACKEND_OPCODES:
448
                if opcode in ['OP_NETWORK_REMOVE', 'OP_NETWORK_ADD']:
449
                    continue
450
                msg = self.create_msg(operation=opcode,
451
                                      network=bn.network.backend_id,
452
                                      status='error',
453
                                      cluster=bn.backend.clustername)
454
                update_network(client, msg)
455
                client.basic_ack.assert_called_once()
456
                db_bnet = BackendNetwork.objects.get(id=bn.id)
457
                self.assertEqual(bn.operstate, db_bnet.operstate)
458
                self.assertEqual(bn.network.state, db_bnet.network.state)
459

    
460
    def test_ips(self, client):
461
        network = mfactory.NetworkFactory(subnet='10.0.0.0/24')
462
        bn = mfactory.BackendNetworkFactory(network=network)
463
        msg = self.create_msg(operation='OP_NETWORK_SET_PARAMS',
464
                              network=network.backend_id,
465
                              cluster=bn.backend.clustername,
466
                              status='success',
467
                              add_reserved_ips=['10.0.0.10', '10.0.0.20'],
468
                              remove_reserved_ips=[])
469
        update_network(client, msg)
470
        client.basic_ack.assert_called_once()
471
        pool = network.get_pool()
472
        self.assertTrue(pool.is_reserved('10.0.0.10'))
473
        self.assertTrue(pool.is_reserved('10.0.0.20'))
474
        pool.save()
475
        # Release them
476
        msg = self.create_msg(operation='OP_NETWORK_SET_PARAMS',
477
                              network=network.backend_id,
478
                              cluster=bn.backend.clustername,
479
                              add_reserved_ips=[],
480
                              remove_reserved_ips=['10.0.0.10', '10.0.0.20'])
481
        update_network(client, msg)
482
        client.basic_ack.assert_called_once()
483
        pool = network.get_pool()
484
        self.assertFalse(pool.is_reserved('10.0.0.10'))
485
        self.assertFalse(pool.is_reserved('10.0.0.20'))
486

    
487

    
488
@patch('synnefo.lib.amqp.AMQPClient')
489
class UpdateBuildProgressTest(TestCase):
490
    def setUp(self):
491
        self.vm = mfactory.VirtualMachineFactory()
492

    
493
    def get_db_vm(self):
494
        return VirtualMachine.objects.get(id=self.vm.id)
495

    
496
    def create_msg(self, **kwargs):
497
        """Create snf-progress-monitor message"""
498
        msg = {'event_time': split_time(time())}
499
        msg['type'] = 'image-copy-progress'
500
        msg['progress'] = 0
501
        for key, val in kwargs.items():
502
            msg[key] = val
503
        message = {'body': json.dumps(msg)}
504
        return message
505

    
506
    def test_missing_attribute(self, client):
507
        update_build_progress(client, json.dumps({'body': {}}))
508
        client.basic_nack.assert_called_once()
509

    
510
    def test_unhandled_exception(self, client):
511
        update_build_progress(client, {})
512
        client.basic_reject.assert_called_once()
513

    
514
    def test_missing_instance(self, client):
515
        msg = self.create_msg(instance='foo')
516
        update_build_progress(client, msg)
517
        client.basic_nack.assert_called_once()
518

    
519
    def test_wrong_type(self, client):
520
        msg = self.create_msg(type="WRONG_TYPE")
521
        update_build_progress(client, msg)
522
        client.basic_ack.assert_called_once()
523

    
524
    def test_progress_update(self, client):
525
        rprogress = randint(10, 100)
526
        msg = self.create_msg(progress=rprogress,
527
                              instance=self.vm.backend_vm_id)
528
        update_build_progress(client, msg)
529
        client.basic_ack.assert_called_once()
530
        vm = self.get_db_vm()
531
        self.assertEqual(vm.buildpercentage, rprogress)
532

    
533
    def test_invalid_value(self, client):
534
        old = self.vm.buildpercentage
535
        for rprogress in [0, -1, 'a']:
536
            msg = self.create_msg(progress=rprogress,
537
                                  instance=self.vm.backend_vm_id)
538
            update_build_progress(client, msg)
539
            client.basic_ack.assert_called_once()
540
            vm = self.get_db_vm()
541
            self.assertEqual(vm.buildpercentage, old)
542

    
543

    
544
class ReconciliationTest(TestCase):
545
    SERVERS = 1000
546
    fixtures = ['db_test_data']
547

    
548
    def test_get_servers_from_db(self):
549
        """Test getting a dictionary from each server to its operstate"""
550
        self.assertEquals(reconciliation.get_servers_from_db(),
551
                          {30000: 'STARTED', 30001: 'STOPPED', 30002: 'BUILD'})
552

    
553
    def test_stale_servers_in_db(self):
554
        """Test discovery of stale entries in DB"""
555

    
556
        D = {1: 'STARTED', 2: 'STOPPED', 3: 'STARTED', 30000: 'BUILD',
557
             30002: 'STOPPED'}
558
        G = {1: True, 3: True, 30000: True}
559
        self.assertEquals(reconciliation.stale_servers_in_db(D, G),
560
                          set([2, 30002]))
561

    
562
    @patch("synnefo.db.models.get_rapi_client")
563
    def test_stale_building_vm(self, client):
564
        vm = mfactory.VirtualMachineFactory()
565
        vm.state = 'BUILD'
566
        vm.backendjobid = 42
567
        vm.save()
568
        D = {vm.id: 'BUILD'}
569
        G = {}
570
        for status in ['queued', 'waiting', 'running']:
571
            client.return_value.GetJobStatus.return_value = {'status': status}
572
            self.assertEqual(reconciliation.stale_servers_in_db(D, G), set([]))
573
            client.return_value.GetJobStatus\
574
                               .assert_called_once_with(vm.backendjobid)
575
            client.reset_mock()
576
        for status in ['success', 'error', 'canceled']:
577
            client.return_value.GetJobStatus.return_value = {'status': status}
578
            self.assertEqual(reconciliation.stale_servers_in_db(D, G), set([]))
579
            client.return_value.GetInstance\
580
                               .assert_called_once_with(vm.backend_vm_id)
581
            client.return_value.GetJobStatus\
582
                               .assert_called_once_with(vm.backendjobid)
583
            client.reset_mock()
584
        from synnefo.logic.rapi import GanetiApiError
585
        client.return_value.GetJobStatus.side_effect = GanetiApiError('Foo')
586
        self.assertEqual(reconciliation.stale_servers_in_db(D, G),
587
                         set([vm.id]))
588

    
589
    def test_orphan_instances_in_ganeti(self):
590
        """Test discovery of orphan instances in Ganeti, without a DB entry"""
591

    
592
        G = {1: True, 2: False, 3: False, 4: True, 50: True}
593
        D = {1: True, 3: False}
594
        self.assertEquals(reconciliation.orphan_instances_in_ganeti(D, G),
595
                          set([2, 4, 50]))
596

    
597
    def test_unsynced_operstate(self):
598
        """Test discovery of unsynced operstate between the DB and Ganeti"""
599

    
600
        G = {1: True, 2: False, 3: True, 4: False, 50: True}
601
        D = {1: 'STARTED', 2: 'STARTED', 3: 'BUILD', 4: 'STARTED', 50: 'BUILD'}
602
        self.assertEquals(reconciliation.unsynced_operstate(D, G),
603
                          set([(2, 'STARTED', False),
604
                               (3, 'BUILD', True), (4, 'STARTED', False),
605
                               (50, 'BUILD', True)]))
606

    
607
from synnefo.logic.test.rapi_pool_tests import *
608
from synnefo.logic.test.utils_tests import *