~ubuntu-branches/ubuntu/utopic/heat/utopic-updates

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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
#
#    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 copy
import mox
from neutronclient.v2_0 import client as neutronclient
from novaclient import exceptions as nova_exceptions
import six

from heat.common import exception
from heat.common import template_format
from heat.engine.clients.os import nova
from heat.engine import parser
from heat.engine.resources import eip
from heat.engine import rsrc_defn
from heat.engine import scheduler
from heat.tests.common import HeatTestCase
from heat.tests import utils
from heat.tests.v1_1 import fakes


eip_template = '''
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "EIP Test",
  "Parameters" : {},
  "Resources" : {
    "IPAddress" : {
      "Type" : "AWS::EC2::EIP",
      "Properties" : {
        "InstanceId" : { "Ref" : "WebServer" }
      }
    },
    "WebServer": {
      "Type": "AWS::EC2::Instance",
    }
  }
}
'''

eip_template_ipassoc = '''
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "EIP Test",
  "Parameters" : {},
  "Resources" : {
    "IPAddress" : {
      "Type" : "AWS::EC2::EIP"
    },
    "IPAssoc" : {
      "Type" : "AWS::EC2::EIPAssociation",
      "Properties" : {
        "InstanceId" : { "Ref" : "WebServer" },
        "EIP" : { "Ref" : "IPAddress" }
      }
    },
    "WebServer": {
      "Type": "AWS::EC2::Instance",
    }
  }
}
'''

eip_template_ipassoc2 = '''
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "EIP Test",
  "Parameters" : {},
  "Resources" : {
    "the_eip" : {
      "Type" : "AWS::EC2::EIP",
      "Properties" : {
        "Domain": "vpc"
      }
    },
    "IPAssoc" : {
      "Type" : "AWS::EC2::EIPAssociation",
      "Properties" : {
        "AllocationId" : 'fc68ea2c-b60b-4b4f-bd82-94ec81110766',
        "NetworkInterfaceId" : { "Ref" : "the_nic" }
      }
    },
    "the_vpc" : {
      "Type" : "AWS::EC2::VPC",
      "Properties" : {
        "CidrBlock" : "10.0.0.0/16"
      }
    },
    "the_subnet" : {
      "Type" : "AWS::EC2::Subnet",
      "Properties" : {
        "CidrBlock" : "10.0.0.0/24",
        "VpcId" : { "Ref" : "the_vpc" }
      }
    },
    "the_nic" : {
      "Type" : "AWS::EC2::NetworkInterface",
      "Properties" : {
        "PrivateIpAddress": "10.0.0.100",
        "SubnetId": { "Ref": "the_subnet" }
      }
    },
  }
}
'''

eip_template_ipassoc3 = '''
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "EIP Test",
  "Parameters" : {},
  "Resources" : {
    "the_eip" : {
      "Type" : "AWS::EC2::EIP",
      "Properties" : {
        "Domain": "vpc"
      }
    },
    "IPAssoc" : {
      "Type" : "AWS::EC2::EIPAssociation",
      "Properties" : {
        "AllocationId" : 'fc68ea2c-b60b-4b4f-bd82-94ec81110766',
        "InstanceId" : '1fafbe59-2332-4f5f-bfa4-517b4d6c1b65'
      }
    }
  }
}
'''

ipassoc_template_validate = '''
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "EIP Test",
  "Parameters" : {},
  "Resources" : {
    "IPAssoc" : {
      "Type" : "AWS::EC2::EIPAssociation",
      "Properties" : {
        "EIP" : '11.0.0.1',
        "InstanceId" : '1fafbe59-2332-4f5f-bfa4-517b4d6c1b65'
      }
    }
  }
}
'''


class EIPTest(HeatTestCase):
    def setUp(self):
        # force Nova, will test Neutron below
        super(EIPTest, self).setUp()
        self.fc = fakes.FakeClient()
        self.m.StubOutWithMock(nova.NovaClientPlugin, '_create')
        self.m.StubOutWithMock(self.fc.servers, 'get')

    def create_eip(self, t, stack, resource_name):
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = eip.ElasticIp(resource_name,
                             resource_defns[resource_name],
                             stack)
        self.assertIsNone(rsrc.validate())
        scheduler.TaskRunner(rsrc.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
        return rsrc

    def create_association(self, t, stack, resource_name):
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = eip.ElasticIpAssociation(resource_name,
                                        resource_defns[resource_name],
                                        stack)
        self.assertIsNone(rsrc.validate())
        scheduler.TaskRunner(rsrc.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
        return rsrc

    def test_eip(self):
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        self.fc.servers.get('WebServer').AndReturn(self.fc.servers.list()[0])
        self.fc.servers.get('WebServer')

        self.m.ReplayAll()

        t = template_format.parse(eip_template)
        stack = utils.parse_stack(t)

        rsrc = self.create_eip(t, stack, 'IPAddress')

        try:
            self.assertEqual('11.0.0.1', rsrc.FnGetRefId())
            rsrc.refid = None
            self.assertEqual('11.0.0.1', rsrc.FnGetRefId())

            self.assertEqual('1', rsrc.FnGetAtt('AllocationId'))

            self.assertRaises(exception.InvalidTemplateAttribute,
                              rsrc.FnGetAtt, 'Foo')

        finally:
            scheduler.TaskRunner(rsrc.destroy)()

        self.m.VerifyAll()

    def test_eip_update(self):
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        server_old = self.fc.servers.list()[0]
        self.fc.servers.get('WebServer').AndReturn(server_old)

        server_update = self.fc.servers.list()[1]
        self.fc.servers.get('5678').MultipleTimes().AndReturn(server_update)

        self.m.ReplayAll()
        t = template_format.parse(eip_template)
        stack = utils.parse_stack(t)

        rsrc = self.create_eip(t, stack, 'IPAddress')
        self.assertEqual('11.0.0.1', rsrc.FnGetRefId())
        # update with the new InstanceId
        props = copy.deepcopy(rsrc.properties.data)
        update_server_id = '5678'
        props['InstanceId'] = update_server_id
        update_snippet = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(),
                                                      props)
        scheduler.TaskRunner(rsrc.update, update_snippet)()
        self.assertEqual((rsrc.UPDATE, rsrc.COMPLETE), rsrc.state)
        self.assertEqual('11.0.0.1', rsrc.FnGetRefId())
        # update without InstanceId
        props = copy.deepcopy(rsrc.properties.data)
        props.pop('InstanceId')
        update_snippet = rsrc_defn.ResourceDefinition(rsrc.name, rsrc.type(),
                                                      props)
        scheduler.TaskRunner(rsrc.update, update_snippet)()
        self.assertEqual((rsrc.UPDATE, rsrc.COMPLETE), rsrc.state)
        self.m.VerifyAll()

    def test_association_eip(self):
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        self.fc.servers.get('WebServer').MultipleTimes() \
            .AndReturn(self.fc.servers.list()[0])

        self.m.ReplayAll()

        t = template_format.parse(eip_template_ipassoc)
        stack = utils.parse_stack(t)

        rsrc = self.create_eip(t, stack, 'IPAddress')
        association = self.create_association(t, stack, 'IPAssoc')

        try:
            self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
            self.assertEqual((association.CREATE, association.COMPLETE),
                             association.state)

            self.assertEqual(utils.PhysName(stack.name, association.name),
                             association.FnGetRefId())
            self.assertEqual('11.0.0.1', association.properties['EIP'])
        finally:
            scheduler.TaskRunner(association.delete)()
            scheduler.TaskRunner(rsrc.delete)()

        self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state)
        self.assertEqual((association.DELETE, association.COMPLETE),
                         association.state)

        self.m.VerifyAll()

    def test_eip_with_exception(self):
        self.m.StubOutWithMock(self.fc.floating_ips, 'create')
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        self.fc.floating_ips.create().AndRaise(fakes.fake_exception())
        self.m.ReplayAll()

        t = template_format.parse(eip_template)
        stack = utils.parse_stack(t)
        resource_name = 'IPAddress'
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = eip.ElasticIp(resource_name,
                             resource_defns[resource_name],
                             stack)

        self.assertRaises(nova_exceptions.NotFound,
                          rsrc.handle_create)
        self.m.VerifyAll()

    def test_delete_eip_with_exception(self):
        self.m.StubOutWithMock(self.fc.floating_ips, 'delete')
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        self.fc.floating_ips.delete(mox.IsA(object)).AndRaise(
            fakes.fake_exception())
        self.fc.servers.get(mox.IsA(object)).AndReturn(False)
        self.m.ReplayAll()

        t = template_format.parse(eip_template)
        stack = utils.parse_stack(t)
        resource_name = 'IPAddress'
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = eip.ElasticIp(resource_name,
                             resource_defns[resource_name],
                             stack)
        rsrc.resource_id = 'fake_id'
        rsrc.handle_delete()
        self.m.VerifyAll()

    def test_delete_eip_successful_if_eip_associate_failed(self):
        floating_ip = mox.IsA(object)
        floating_ip.ip = '172.24.4.13'
        floating_ip.id = '9037272b-6875-42e6-82e9-4342d5925da4'

        self.m.StubOutWithMock(self.fc.floating_ips, 'create')
        self.fc.floating_ips.create().AndReturn(floating_ip)

        server = self.fc.servers.list()[0]
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        self.fc.servers.get('WebServer').MultipleTimes().AndReturn(server)

        self.m.StubOutWithMock(self.fc.servers, 'add_floating_ip')
        self.fc.servers.add_floating_ip(server, floating_ip.ip, None).\
            AndRaise(nova_exceptions.BadRequest(400))

        self.m.StubOutWithMock(self.fc.servers, 'remove_floating_ip')
        msg = ("ClientException: Floating ip 172.24.4.13 is not associated "
               "with instance 1234.")
        self.fc.servers.remove_floating_ip(server, floating_ip.ip).\
            AndRaise(nova_exceptions.ClientException(422, msg))
        self.m.StubOutWithMock(self.fc.floating_ips, 'delete')
        self.fc.floating_ips.delete(mox.IsA(object))

        self.m.ReplayAll()

        t = template_format.parse(eip_template)
        stack = utils.parse_stack(t)
        resource_name = 'IPAddress'
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = eip.ElasticIp(resource_name,
                             resource_defns[resource_name],
                             stack)

        self.assertIsNone(rsrc.validate())
        self.assertRaises(exception.ResourceFailure,
                          scheduler.TaskRunner(rsrc.create))
        self.assertEqual((rsrc.CREATE, rsrc.FAILED), rsrc.state)

        # to delete the eip
        scheduler.TaskRunner(rsrc.delete)()
        self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state)
        self.m.VerifyAll()


class AllocTest(HeatTestCase):

    def setUp(self):
        super(AllocTest, self).setUp()

        self.fc = fakes.FakeClient()
        self.m.StubOutWithMock(self.fc.servers, 'get')
        self.m.StubOutWithMock(nova.NovaClientPlugin, '_create')
        self.m.StubOutWithMock(parser.Stack, 'resource_by_refid')
        self.m.StubOutWithMock(neutronclient.Client,
                               'create_floatingip')
        self.m.StubOutWithMock(neutronclient.Client,
                               'show_floatingip')
        self.m.StubOutWithMock(neutronclient.Client,
                               'update_floatingip')
        self.m.StubOutWithMock(neutronclient.Client,
                               'delete_floatingip')
        self.m.StubOutWithMock(neutronclient.Client,
                               'add_gateway_router')
        self.m.StubOutWithMock(neutronclient.Client, 'list_networks')
        self.m.StubOutWithMock(neutronclient.Client, 'list_ports')
        self.m.StubOutWithMock(neutronclient.Client, 'show_network')
        self.m.StubOutWithMock(neutronclient.Client, 'list_routers')
        self.m.StubOutWithMock(neutronclient.Client,
                               'remove_gateway_router')
        self.stub_keystoneclient()

    def _setup_test_stack(self, stack_name):
        t = template_format.parse(ipassoc_template_validate)
        template = parser.Template(t)
        stack = parser.Stack(utils.dummy_context(), stack_name,
                             template, stack_id='12233',
                             stack_user_project_id='8888')

        return template, stack

    def _validate_properties(self, stack, template, expected):
        resource_defns = template.resource_definitions(stack)
        rsrc = eip.ElasticIpAssociation('validate_eip_ass',
                                        resource_defns['IPAssoc'],
                                        stack)

        exc = self.assertRaises(exception.StackValidationFailed,
                                rsrc.validate)
        self.assertIn(expected, six.text_type(exc))

    def mock_show_network(self):
        vpc_name = utils.PhysName('test_stack', 'the_vpc')
        neutronclient.Client.show_network(
            '22c26451-cf27-4d48-9031-51f5e397b84e'
        ).AndReturn({"network": {
            "status": "BUILD",
            "subnets": [],
            "name": vpc_name,
            "admin_state_up": False,
            "shared": False,
            "tenant_id": "c1210485b2424d48804aad5d39c61b8f",
            "id": "22c26451-cf27-4d48-9031-51f5e397b84e"
        }})

    def create_eip(self, t, stack, resource_name):
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = eip.ElasticIp(resource_name,
                             resource_defns[resource_name],
                             stack)
        self.assertIsNone(rsrc.validate())
        scheduler.TaskRunner(rsrc.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
        return rsrc

    def create_association(self, t, stack, resource_name):
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = eip.ElasticIpAssociation(resource_name,
                                        resource_defns[resource_name],
                                        stack)
        self.assertIsNone(rsrc.validate())
        scheduler.TaskRunner(rsrc.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)
        return rsrc

    def mock_update_floatingip(self, port='the_nic'):
        neutronclient.Client.update_floatingip(
            'fc68ea2c-b60b-4b4f-bd82-94ec81110766',
            {'floatingip': {'port_id': port}}).AndReturn(None)

    def mock_create_gateway_attachment(self):
        neutronclient.Client.add_gateway_router(
            'bbbb', {'network_id': 'eeee'}).AndReturn(None)

    def mock_create_floatingip(self):
        neutronclient.Client.list_networks(
            **{'router:external': True}).AndReturn({'networks': [{
                'status': 'ACTIVE',
                'subnets': [],
                'name': 'nova',
                'router:external': True,
                'tenant_id': 'c1210485b2424d48804aad5d39c61b8f',
                'admin_state_up': True,
                'shared': True,
                'id': 'eeee'
            }]})

        neutronclient.Client.create_floatingip({
            'floatingip': {'floating_network_id': u'eeee'}
        }).AndReturn({'floatingip': {
            "status": "ACTIVE",
            "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766",
            "floating_ip_address": "192.168.9.3"
        }})

    def mock_show_floatingip(self, refid):
        neutronclient.Client.show_floatingip(
            refid,
        ).AndReturn({'floatingip': {
            'router_id': None,
            'tenant_id': 'e936e6cd3e0b48dcb9ff853a8f253257',
            'floating_network_id': 'eeee',
            'fixed_ip_address': None,
            'floating_ip_address': '172.24.4.227',
            'port_id': None,
            'id': 'ffff'
        }})

    def mock_delete_floatingip(self):
        id = 'fc68ea2c-b60b-4b4f-bd82-94ec81110766'
        neutronclient.Client.delete_floatingip(id).AndReturn(None)

    def mock_list_ports(self):
        neutronclient.Client.list_ports(id='the_nic').AndReturn(
            {"ports": [{
                "status": "DOWN",
                "binding:host_id": "null",
                "name": "wp-NIC-yu7fc7l4g5p6",
                "admin_state_up": True,
                "network_id": "22c26451-cf27-4d48-9031-51f5e397b84e",
                "tenant_id": "ecf538ec1729478fa1f97f1bf4fdcf7b",
                "binding:vif_type": "ovs",
                "device_owner": "",
                "binding:capabilities": {"port_filter": True},
                "mac_address": "fa:16:3e:62:2d:4f",
                "fixed_ips": [{"subnet_id": "mysubnetid-70ec",
                               "ip_address": "192.168.9.2"}],
                "id": "a000228d-b40b-4124-8394-a4082ae1b76b",
                "security_groups": ["5c6f529d-3186-4c36-84c0-af28b8daac7b"],
                "device_id": ""
            }]})

    def mock_list_instance_ports(self, refid):
        neutronclient.Client.list_ports(device_id=refid).AndReturn(
            {"ports": [{
                "status": "DOWN",
                "binding:host_id": "null",
                "name": "wp-NIC-yu7fc7l4g5p6",
                "admin_state_up": True,
                "network_id": "22c26451-cf27-4d48-9031-51f5e397b84e",
                "tenant_id": "ecf538ec1729478fa1f97f1bf4fdcf7b",
                "binding:vif_type": "ovs",
                "device_owner": "",
                "binding:capabilities": {"port_filter": True},
                "mac_address": "fa:16:3e:62:2d:4f",
                "fixed_ips": [{"subnet_id": "mysubnetid-70ec",
                               "ip_address": "192.168.9.2"}],
                "id": "a000228d-b40b-4124-8394-a4082ae1b76c",
                "security_groups": ["5c6f529d-3186-4c36-84c0-af28b8daac7b"],
                "device_id": refid
            }]})

    def mock_router_for_vpc(self):
        vpc_name = utils.PhysName('test_stack', 'the_vpc')
        neutronclient.Client.list_routers(name=vpc_name).AndReturn({
            "routers": [{
                "status": "ACTIVE",
                "external_gateway_info": {
                    "network_id": "zzzz",
                    "enable_snat": True},
                "name": vpc_name,
                "admin_state_up": True,
                "tenant_id": "3e21026f2dc94372b105808c0e721661",
                "routes": [],
                "id": "bbbb"
            }]
        })

    def mock_no_router_for_vpc(self):
        vpc_name = utils.PhysName('test_stack', 'the_vpc')
        neutronclient.Client.list_routers(name=vpc_name).AndReturn({
            "routers": []
        })

    def test_neutron_eip(self):
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        self.fc.servers.get('WebServer').AndReturn(self.fc.servers.list()[0])
        self.fc.servers.get('WebServer')

        self.m.ReplayAll()

        t = template_format.parse(eip_template)
        stack = utils.parse_stack(t)

        rsrc = self.create_eip(t, stack, 'IPAddress')

        try:
            self.assertEqual('11.0.0.1', rsrc.FnGetRefId())
            rsrc.refid = None
            self.assertEqual('11.0.0.1', rsrc.FnGetRefId())

            self.assertEqual('1', rsrc.FnGetAtt('AllocationId'))

            self.assertRaises(exception.InvalidTemplateAttribute,
                              rsrc.FnGetAtt, 'Foo')

        finally:
            scheduler.TaskRunner(rsrc.destroy)()

        self.m.VerifyAll()

    def test_association_allocationid(self):
        self.mock_create_gateway_attachment()
        self.mock_show_network()
        self.mock_router_for_vpc()

        self.mock_create_floatingip()
        self.mock_list_ports()

        self.mock_show_floatingip('fc68ea2c-b60b-4b4f-bd82-94ec81110766')
        self.mock_update_floatingip()

        self.mock_update_floatingip(port=None)
        self.mock_delete_floatingip()

        self.m.ReplayAll()

        t = template_format.parse(eip_template_ipassoc2)
        stack = utils.parse_stack(t)

        rsrc = self.create_eip(t, stack, 'the_eip')
        association = self.create_association(t, stack, 'IPAssoc')

        scheduler.TaskRunner(association.delete)()
        scheduler.TaskRunner(rsrc.delete)()

        self.m.VerifyAll()

    def test_association_allocationid_with_instance(self):
        self.mock_show_network()

        self.mock_create_floatingip()
        self.mock_list_instance_ports('1fafbe59-2332-4f5f-bfa4-517b4d6c1b65')

        self.mock_no_router_for_vpc()
        self.mock_update_floatingip(
            port='a000228d-b40b-4124-8394-a4082ae1b76c')

        self.mock_update_floatingip(port=None)
        self.mock_delete_floatingip()

        self.m.ReplayAll()

        t = template_format.parse(eip_template_ipassoc3)
        stack = utils.parse_stack(t)

        rsrc = self.create_eip(t, stack, 'the_eip')
        association = self.create_association(t, stack, 'IPAssoc')

        scheduler.TaskRunner(association.delete)()
        scheduler.TaskRunner(rsrc.delete)()

        self.m.VerifyAll()

    def test_validate_properties_EIP_and_AllocationId(self):
        template, stack = self._setup_test_stack(
            stack_name='validate_EIP_AllocationId')

        properties = template.t['Resources']['IPAssoc']['Properties']
        # test with EIP and AllocationId
        properties['AllocationId'] = 'fc68ea2c-b60b-4b4f-bd82-94ec81110766'
        expected = ("Either 'EIP' or 'AllocationId' must be provided.")
        self._validate_properties(stack, template, expected)

        # test without EIP and AllocationId
        properties.pop('AllocationId')
        properties.pop('EIP')
        self._validate_properties(stack, template, expected)

    def test_validate_EIP_and_InstanceId(self):
        template, stack = self._setup_test_stack(
            stack_name='validate_EIP_InstanceId')
        properties = template.t['Resources']['IPAssoc']['Properties']
        # test with EIP and no InstanceId
        properties.pop('InstanceId')
        expected = ("Must specify 'InstanceId' if you specify 'EIP'.")
        self._validate_properties(stack, template, expected)

    def test_validate_without_NetworkInterfaceId_and_InstanceId(self):
        template, stack = self._setup_test_stack(
            stack_name='validate_EIP_InstanceId')

        properties = template.t['Resources']['IPAssoc']['Properties']
        # test without NetworkInterfaceId and InstanceId
        properties.pop('InstanceId')
        properties.pop('EIP')
        allocation_id = '1fafbe59-2332-4f5f-bfa4-517b4d6c1b65'
        properties['AllocationId'] = allocation_id
        expected = ("Must specify at least one of 'InstanceId' "
                    "or 'NetworkInterfaceId'.")
        self._validate_properties(stack, template, expected)

    def test_delete_association_successful_if_create_failed(self):
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        server = self.fc.servers.list()[0]
        self.fc.servers.get('WebServer').MultipleTimes() \
            .AndReturn(server)
        self.m.StubOutWithMock(self.fc.servers, 'add_floating_ip')
        self.fc.servers.add_floating_ip(server, '11.0.0.1').AndRaise(
            fakes.fake_exception(400))
        self.m.ReplayAll()

        t = template_format.parse(eip_template_ipassoc)
        stack = utils.parse_stack(t)

        self.create_eip(t, stack, 'IPAddress')
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = eip.ElasticIpAssociation('IPAssoc',
                                        resource_defns['IPAssoc'],
                                        stack)
        self.assertIsNone(rsrc.validate())
        self.assertRaises(exception.ResourceFailure,
                          scheduler.TaskRunner(rsrc.create))
        self.assertEqual((rsrc.CREATE, rsrc.FAILED), rsrc.state)

        scheduler.TaskRunner(rsrc.delete)()
        self.assertEqual((rsrc.DELETE, rsrc.COMPLETE), rsrc.state)

        self.m.VerifyAll()