~barryprice/juju-deployer/resolve-OpenStack-1501-option-errors

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
""" Unittest for juju-deployer diff action (--diff) """
# pylint: disable=C0103
from __future__ import absolute_import
import os
import shutil
import tempfile
import unittest

try:
    from yaml import CSafeLoader, CSafeDumper
    SafeLoader, SafeDumper = CSafeLoader, CSafeDumper
except ImportError:
    from yaml import SafeLoader

import yaml

from mock import patch, mock_open
from six import StringIO

from deployer.config import ConfigStack
from deployer.env.mem import MemoryEnvironment
from deployer.utils import setup_logging

from .base import Base, skip_if_offline, TEST_OFFLINE, TEST_OFFLINE_REASON
from ..action.diff import Diff


@skip_if_offline
class DiffTest(Base):

    def setUp(self):
        self.output = setup_logging(
            debug=True, verbose=True, stream=StringIO())

    # Because fetch_charms is expensive, do it once for all tests
    @classmethod
    def setUpClass(cls):
        super(DiffTest, cls).setUpClass()
        # setUpClass not being skipped, here, could have to do with
        # decorator on derived class.  So skip explicitly.
        if TEST_OFFLINE:
            raise unittest.SkipTest(TEST_OFFLINE_REASON)
        deployment = ConfigStack(
            [os.path.join(
                cls.test_data_dir,
                "openstack",
                "openstack-1501.yaml")]).get('openstack')
        cls._dir = tempfile.mkdtemp()
        os.mkdir(os.path.join(cls._dir, "trusty"))
        deployment.repo_path = cls._dir
        deployment.fetch_charms()
        deployment.resolve()
        cls._deployment = deployment

    @classmethod
    def tearDownClass(cls):
        super(DiffTest, cls).tearDownClass()
        # TearDownClass not being skipped, here, could have to do with
        # decorator on derived class.  So skip explicitly.
        if TEST_OFFLINE:
            raise unittest.SkipTest(TEST_OFFLINE_REASON)
        shutil.rmtree(cls._dir)

    @classmethod
    def get_dir(cls):
        """ Return temp working dir
        """
        return cls._dir

    @classmethod
    def get_deployment(cls):
        """ Return saved deployment at class initialization
        """
        return cls._deployment

    def test_diff_nil(self):
        dpl = self.get_deployment()
        # No changes, assert nil diff
        env = MemoryEnvironment(dpl.name, dpl)
        diff = Diff(env, dpl, {}).do_diff()
        self.assertEqual(diff, {})

    def test_diff_num_units(self):
        # Removing 1 unit must show -1 'num_units'
        dpl = self.get_deployment()
        env = MemoryEnvironment(dpl.name, dpl)
        env.remove_unit(env.status()['services']['nova-compute']['units'][0])
        diff = Diff(env, dpl, {}).do_diff()
        self.assertEqual(
            diff['services']['modified']['nova-compute']['num_units'], -1)
        # re-adding a unit -> nil diff
        env.add_units('nova-compute', 1)
        diff = Diff(env, dpl, {}).do_diff()
        self.assertEqual(diff, {})

    def test_diff_config(self):
        dpl = self.get_deployment()
        env = MemoryEnvironment(dpl.name, dpl)
        # Reconfigure the environment to have an explicit change
        # (admin-password), one that differs from the charm
        # default (admin-token), and an option that no longer exists in the
        # charm (obsolete).
        env.set_config(
            'keystone',
            {'admin-password': 'password', 'admin-user': 'root',
             'obsolete': 'for ages'})
        diff = Diff(env, dpl, {}).do_diff()
        mod_keystone = diff['services']['modified']['keystone']
        self.assertEqual(
            mod_keystone['env-config'],
            {'admin-password': 'password', 'admin-user': 'root',
             'obsolete': 'for ages'})
        self.assertEqual(
            mod_keystone['cfg-config'],
            {'admin-password': 'openstack', 'admin-user': 'admin',
             'obsolete': None})

    def test_diff_constraints(self):
        dpl = self.get_deployment()
        env = MemoryEnvironment(dpl.name, dpl)
        env.set_constraints('nova-compute', 'foo=bar')
        diff = Diff(env, dpl, {}).do_diff()
        mod_svc = diff['services']['modified']['nova-compute']
        self.assertTrue(
            mod_svc['env-constraints'] != mod_svc['cfg-constraints'])
        self.assertEqual(mod_svc['env-constraints'], {'foo': 'bar'})

    def test_diff_env_remove_relation(self):
        dpl = self.get_deployment()
        env = MemoryEnvironment(dpl.name, dpl)
        env.remove_relation('cinder:amqp', 'rabbitmq-server:amqp')
        diff = Diff(env, dpl, {}).do_diff()
        self.assertEqual(str(diff['relations']['missing']),
                         '[cinder:amqp <-> rabbitmq-server:amqp]')

    def test_diff_env_service_destroy(self):
        dpl = self.get_deployment()
        env = MemoryEnvironment(dpl.name, dpl)
        env.destroy_service('nova-compute')
        diff = Diff(env, dpl, {}).do_diff()
        self.assertTrue(
            str(diff['relations']['missing'][0]).find('nova-compute') != -1)
        self.assertEqual(
            list(diff['services']['missing'].keys()),
            ['nova-compute'])

    def test_diff_cfg_remove_relation(self):
        dpl = self.get_deployment()
        # need a tmp file to sneak and save deployment YAML
        edited_config_file = os.path.join(self.get_dir(), 'saved.yaml')
        dpl.save(edited_config_file)
        # in memory edit yaml content
        edited_config = yaml.load(open(edited_config_file), Loader=SafeLoader)
        edited_config["relations"].remove(
            ['nova-compute:amqp', 'rabbitmq-server:amqp'])
        edited_config = yaml.dump({'openstack': edited_config})

        # mock open to inyect edited_config YAML to ConfigStack
        with patch('deployer.config.open', mock_open(read_data=edited_config),
                   create=True):
            edited_dpl = ConfigStack("mocked").get('openstack')

        edited_dpl.repo_path = self.get_dir()
        edited_dpl.fetch_charms()
        edited_dpl.resolve()
        env = MemoryEnvironment(dpl.name, dpl)
        diff = Diff(env, edited_dpl, {}).do_diff()
        self.assertTrue(
            diff['relations']['unknown'],
            '[nova-compute:amqp <-> rabbitmq-server:amqp]')

    def test_diff_cfg_remove_ambiguous_relation(self):
        dpl = self.get_deployment()
        # need a tmp file to sneak and save deployment YAML
        edited_config_file = os.path.join(self.get_dir(), 'saved.yaml')
        dpl.save(edited_config_file)
        # in memory edit yaml content
        edited_config = yaml.load(open(edited_config_file), Loader=SafeLoader)
        edited_config["relations"].remove(
            ['ceilometer:identity-service', 'keystone:identity-service'])
        edited_config = yaml.dump({'openstack': edited_config})

        # mock open to inyect edited_config YAML to ConfigStack
        with patch('deployer.config.open', mock_open(read_data=edited_config),
                   create=True):
            edited_dpl = ConfigStack("mocked").get('openstack')

        edited_dpl.repo_path = self.get_dir()
        edited_dpl.fetch_charms()
        edited_dpl.resolve()
        env = MemoryEnvironment(dpl.name, dpl)
        diff = Diff(env, edited_dpl, {}).do_diff()
        # verify ceilometer<->keystone present in unknown relations
        self.assertTrue('ceilometer' in str(diff['relations']['unknown']) and
                        'keystone' in str(diff['relations']['unknown']))

    def test_diff_cfg_replace_with_unnamed_relations(self):
        dpl = self.get_deployment()
        # need a tmp file to sneak and save deployment YAML
        edited_config_file = os.path.join(self.get_dir(), 'saved.yaml')
        dpl.save(edited_config_file)
        # in memory edit yaml content
        edited_config = yaml.load(open(edited_config_file), Loader=SafeLoader)
        # remove ':name' from service endpoint specification
        for relation in edited_config["relations"]:
            relation = [(relation[0] + ":").split(":")[0],
                        (relation[1] + ":").split(":")[0]]
        edited_config = yaml.dump({'openstack': edited_config})

        # mock open to inyect edited_config YAML to ConfigStack
        with patch('deployer.config.open', mock_open(read_data=edited_config),
                   create=True):
            edited_dpl = ConfigStack("mocked").get('openstack')

        edited_dpl.repo_path = self.get_dir()
        edited_dpl.fetch_charms()
        edited_dpl.resolve()
        env = MemoryEnvironment(dpl.name, dpl)
        diff = Diff(env, edited_dpl, {}).do_diff()
        self.assertEqual(diff, {})