~juju-qa/juju-ci-tools/trunk

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
#!/usr/bin/env python
"""Assess proper functionality of juju add-credential."""

from __future__ import print_function

import argparse
import logging
import sys
import os
import yaml
import pexpect
import shutil

from deploy_stack import (
    BootstrapManager,
    )
from utility import (
    configure_logging,
    add_basic_testing_arguments,
    JujuAssertionError,
    temp_dir,
    )

__metaclass__ = type


log = logging.getLogger("assess_add_credentials")

cloud_city = os.environ.get('JUJU_HOME')


def assess_add_credentials(args):
    """Tests if juju's add-credentials command works as expected.

    Adds credentials from our real source to our juju client and tests if
    that client can bootstrap.

    :param client: Client object used in bootstrap check
    :param args: Test arguments
    """

    if 'vmaas' in args.env:
        env = 'maas'
    elif 'gce' in args.env:
        env = 'google'
    else:
        env = args.env.split('parallel-')[1]

    # Grab the credentials from cloud-city
    cred = get_credentials(env)

    # Fix the keypath to reflect local username
    key_path = cred['credentials'].get('private-key-path')
    if key_path:
        cred['credentials']['private-key-path'] = os.path.join(
            cloud_city, '{}-key'.format(env))

    verify_add_credentials(args, env, cred)
    verify_credentials_match(env, cred)
    verify_bootstrap(args)

    log.info('SUCCESS')


def verify_add_credentials(args, env, cred):
    """Adds the supplied credential to juju with 'juju add-credential'.

    :param args: Testing arguments
    :param env: String environment name
    :param cred: Dict of credential information
    """
    testing_variations = {
        'aws': add_aws,
        'google': add_gce,
        'rackspace': add_rackspace,
        'maas': add_maas,
        'joyent': add_joyent,
        'azure': add_azure
        }

    log.info("Adding {} credential from /cloud-city/credentials.yaml "
             "into testing instance".format(args.env))
    with pexpect.spawn('juju add-credential {}'.format(env)) as child:
        try:
            testing_variations[env](child, env, cred)
        except pexpect.TIMEOUT:
            log.error('Buffer: {}'.format(child.buffer))
            log.error('Before: {}'.format(child.before))
            raise Exception(
                'Registering user failed: pexpect session timed out')


def get_credentials(env):
    """Gets the stored test credentials.

    :return: Dict of credential information
    """
    with open(os.path.join(cloud_city, 'credentials.yaml')) as f:
        creds_dict = yaml.load(f)
    cred = creds_dict['credentials'][env]
    return cred


def verify_bootstrap(args):
    """Verify the client can bootstrap with the newly added credentials

    :param args: Testing arguments
    """
    env_file = os.path.join(
        os.environ['HOME'], 'cloud-city', 'environments.yaml')
    shutil.copy(env_file, os.environ['JUJU_DATA'])
    bs_manager = BootstrapManager.from_args(args)
    with bs_manager.booted_context(args.upload_tools):
        log.info('Bootstrap successfull, tearing down client')


def verify_credentials_match(env, cred):
    """Verify the credentials entered match the stored credentials.

    :param env: String environment name
    :param cred: Dict of credential information
    """
    with open(os.path.join(os.environ['JUJU_DATA'], 'credentials.yaml')) as f:
        test_creds = yaml.load(f)
        test_creds = test_creds['credentials'][env][env]
    if not test_creds == cred['credentials']:
        error = 'Credential miss-match after manual add'
        raise JujuAssertionError(error)


def end_session(session):
    """Convenience function to check a pexpect session has properly closed.
    """
    session.expect(pexpect.EOF)
    session.close()
    if session.exitstatus != 0:
        log.error('Buffer: {}'.format(session.buffer))
        log.error('Before: {}'.format(session.before))
        raise Exception('pexpect process exited with {}'.format(
                session.exitstatus))


def add_aws(child, env, cred):
    """Adds credentials for AWS to test client using real credentials.

    :param child: pexpect.spawn object of the juju add-credential command
    :param env: String environment name
    :param cred: Dict of credential information
    """
    access_key = cred['credentials']['access-key']
    secret_key = cred['credentials']['secret-key']

    child.expect('Enter credential name:')
    child.sendline(env)
    child.expect('Enter access-key:')
    child.sendline(access_key)
    child.expect('Enter secret-key:')
    child.sendline(secret_key)
    end_session(child)
    log.info('Added AWS credential')


def add_gce(child, env, cred):
    """Adds credentials for GCE to test client using real credentials.

    :param child: pexpect.spawn object of the juju add-credential command
    :param env: String environment name
    :param cred: Dict of credential information
    """
    auth_type = cred['credentials']['auth-type']
    project_id = cred['credentials']['project-id']
    private_key = cred['credentials']['private-key']
    client_email = cred['credentials']['client-email']
    client_id = cred['credentials']['client-id']

    child.expect('Enter credential name:')
    child.sendline(env)
    child.expect('Select auth-type:')
    child.sendline(auth_type)
    child.expect('Enter client-id:')
    child.sendline(client_id)
    child.expect('Enter client-email:')
    child.sendline(client_email)
    child.expect('Enter private-key:')
    child.send(private_key)
    child.sendline('')
    child.expect('Enter project-id:')
    child.sendline(project_id)
    end_session(child)
    log.info('Added GCE credential')


def add_rackspace(child, env, cred):
    """Adds credentials for Rackspace to test client using real credentials.

    :param child: pexpect.spawn object of the juju add-credential command
    :param env: String environment name
    :param cred: Dict of credential information
    """
    username = cred['credentials']['username']
    password = cred['credentials']['password']
    tenant_name = cred['credentials']['tenant-name']

    child.expect('Enter credential name:')
    child.sendline(env)
    child.expect('Enter username:')
    child.sendline(username)
    child.expect('Enter password:')
    child.sendline(password)
    child.expect('Enter tenant-name:')
    child.sendline(tenant_name)
    end_session(child)
    log.info('Added Rackspace credential')


def add_maas(child, env, cred):
    """Adds credentials for MaaS to test client using real credentials.

    :param child: pexpect.spawn object of the juju add-credential command
    :param env: String environment name
    :param cred: Dict of credential information
    """
    maas_oauth = cred['credentials']['maas-oauth']

    child.expect('Enter credential name:')
    child.sendline(env)
    child.expect('Enter maas-oauth:')
    child.sendline(maas_oauth)
    end_session(child)
    log.info('Added MaaS credential')


def add_joyent(child, env, cred):
    """Adds credentials for Joyent to test client using real credentials.

    :param child: pexpect.spawn object of the juju add-credential command
    :param env: String environment name
    :param cred: Dict of credential information
    """
    algorithm = cred['credentials']['algorithm']
    sdc_user = cred['credentials']['sdc-user']
    sdc_key_id = cred['credentials']['sdc-key-id']
    private_key_path = os.path.join(
        os.environ['HOME'], 'cloud-city', 'joyent-key')

    child.expect('Enter credential name:')
    child.sendline(env)
    child.expect('Enter sdc-user:')
    child.sendline(sdc_user)
    child.expect('Enter sdc-key-id:')
    child.sendline(sdc_key_id)
    child.expect('Enter private-key-path:')
    child.sendline(private_key_path)
    child.expect(',rsa-sha512]:')
    child.sendline(algorithm)
    end_session(child)
    log.info('Added Joyent credential')


def add_azure(child, env, cred):
    """Adds credentials for Azure to test client using real credentials.

    :param child: pexpect.spawn object of the juju add-credential command
    :param env: String environment name
    :param cred: Dict of credential information
    """
    auth_type = cred['credentials']['auth-type']
    application_id = cred['credentials']['application-id']
    subscription_id = cred['credentials']['subscription-id']
    application_password = cred['credentials']['application-password']

    child.expect('Enter credential name:')
    child.sendline(env)
    child.expect('Select auth-type:')
    child.sendline(auth_type)
    child.expect('Enter application-id:')
    child.sendline(application_id)
    child.expect('Enter subscription-id:')
    child.sendline(subscription_id)
    child.expect('Enter application-password:')
    child.sendline(application_password)
    end_session(child)
    log.info('Added Azure credential')


def parse_args(argv):
    """Parse all arguments."""
    parser = argparse.ArgumentParser(
        description='Test if juju properly adds credentials with the '
        'add-credential command.')
    add_basic_testing_arguments(parser)
    return parser.parse_args(argv)


def main(argv=None):
    args = parse_args(argv)
    configure_logging(args.verbose)
    with temp_dir() as temp:
        os.environ['JUJU_HOME'] = temp
        os.environ['JUJU_DATA'] = temp
        assess_add_credentials(args)
    return 0


if __name__ == '__main__':
    sys.exit(main())