Statistics
| Branch: | Tag: | Revision:

root / ci / utils.py @ c1b1d444

History | View | Annotate | Download (18.5 kB)

1
#!/usr/bin/env python
2

    
3
"""
4
Synnefo ci utils module
5
"""
6

    
7
import os
8
import sys
9
import time
10
import logging
11
import fabric.api as fabric
12
from ConfigParser import ConfigParser, DuplicateSectionError
13

    
14
from kamaki.cli import config as kamaki_config
15
from kamaki.clients.astakos import AstakosClient
16
from kamaki.clients.cyclades import CycladesClient
17
from kamaki.clients.image import ImageClient
18

    
19

    
20
def _run(cmd, verbose):
21
    """Run fabric with verbose level"""
22
    if verbose:
23
        args = ('running',)
24
    else:
25
        args = ('running', 'stdout',)
26
    with fabric.hide(*args):
27
        return fabric.run(cmd)
28

    
29

    
30
def _red(msg):
31
    """Red color"""
32
    #return "\x1b[31m" + str(msg) + "\x1b[0m"
33
    return str(msg)
34

    
35

    
36
def _yellow(msg):
37
    """Yellow color"""
38
    #return "\x1b[33m" + str(msg) + "\x1b[0m"
39
    return str(msg)
40

    
41

    
42
def _green(msg):
43
    """Green color"""
44
    #return "\x1b[32m" + str(msg) + "\x1b[0m"
45
    return str(msg)
46

    
47

    
48
def _check_fabric(fun):
49
    """Check if fabric env has been set"""
50
    def wrapper(self, *args):
51
        """wrapper function"""
52
        if not self.fabric_installed:
53
            self.setup_fabric()
54
        return fun(self, *args)
55
    return wrapper
56

    
57

    
58
def _check_kamaki(fun):
59
    """Check if kamaki has been initialized"""
60
    def wrapper(self, *args):
61
        """wrapper function"""
62
        if not self.kamaki_installed:
63
            self.setup_kamaki()
64
        return fun(self, *args)
65
    return wrapper
66

    
67

    
68
class _MyFormatter(logging.Formatter):
69
    """Logging Formatter"""
70
    def format(self, record):
71
        format_orig = self._fmt
72
        if record.levelno == logging.DEBUG:
73
            self._fmt = "  %(msg)s"
74
        elif record.levelno == logging.INFO:
75
            self._fmt = "%(msg)s"
76
        elif record.levelno == logging.WARNING:
77
            self._fmt = _yellow("[W] %(msg)s")
78
        elif record.levelno == logging.ERROR:
79
            self._fmt = _red("[E] %(msg)s")
80
        result = logging.Formatter.format(self, record)
81
        self._fmt = format_orig
82
        return result
83

    
84

    
85
class SynnefoCI(object):
86
    """SynnefoCI python class"""
87

    
88
    def __init__(self, cleanup_config=False, cloud=None):
89
        """ Initialize SynnefoCI python class
90

91
        Setup logger, local_dir, config and kamaki
92
        """
93
        # Setup logger
94
        self.logger = logging.getLogger('synnefo-ci')
95
        self.logger.setLevel(logging.DEBUG)
96
        handler = logging.StreamHandler()
97
        handler.setFormatter(_MyFormatter())
98
        self.logger.addHandler(handler)
99

    
100
        # Get our local dir
101
        self.ci_dir = os.path.dirname(os.path.abspath(__file__))
102
        self.repo_dir = os.path.dirname(self.ci_dir)
103

    
104
        # Read config file
105
        default_conffile = os.path.join(self.ci_dir, "new_config")
106
        self.conffile = os.environ.get("SYNNEFO_CI_CONFIG_FILE",
107
                                       default_conffile)
108

    
109
        self.config = ConfigParser()
110
        self.config.optionxform = str
111
        self.config.read(self.conffile)
112
        temp_config = self.config.get('Global', 'temporary_config')
113
        if cleanup_config:
114
            try:
115
                os.remove(temp_config)
116
            except:
117
                pass
118
        else:
119
            self.config.read(self.config.get('Global', 'temporary_config'))
120

    
121
        # Set kamaki cloud
122
        if cloud is not None:
123
            self.kamaki_cloud = cloud
124
        elif self.config.has_option("Deployment", "kamaki_cloud"):
125
            kamaki_cloud = self.config.get("Deployment", "kamaki_cloud")
126
            if kamaki_cloud == "":
127
                self.kamaki_cloud = None
128
        else:
129
            self.kamaki_cloud = None
130

    
131
        # Initialize variables
132
        self.fabric_installed = False
133
        self.kamaki_installed = False
134
        self.cyclades_client = None
135
        self.image_client = None
136

    
137
    def setup_kamaki(self):
138
        """Initialize kamaki
139

140
        Setup cyclades_client and image_client
141
        """
142

    
143
        config = kamaki_config.Config()
144
        if self.kamaki_cloud is None:
145
            self.kamaki_cloud = config.get_global("default_cloud")
146

    
147
        self.logger.info("Setup kamaki client, using cloud '%s'.." %
148
                         self.kamaki_cloud)
149
        auth_url = config.get_cloud(self.kamaki_cloud, "url")
150
        self.logger.debug("Authentication URL is %s" % _green(auth_url))
151
        token = config.get_cloud(self.kamaki_cloud, "token")
152
        #self.logger.debug("Token is %s" % _green(token))
153

    
154
        astakos_client = AstakosClient(auth_url, token)
155

    
156
        cyclades_url = \
157
            astakos_client.get_service_endpoints('compute')['publicURL']
158
        self.logger.debug("Cyclades API url is %s" % _green(cyclades_url))
159
        self.cyclades_client = CycladesClient(cyclades_url, token)
160
        self.cyclades_client.CONNECTION_RETRY_LIMIT = 2
161

    
162
        image_url = \
163
            astakos_client.get_service_endpoints('image')['publicURL']
164
        self.logger.debug("Images API url is %s" % _green(image_url))
165
        self.image_client = ImageClient(cyclades_url, token)
166
        self.image_client.CONNECTION_RETRY_LIMIT = 2
167

    
168
    def _wait_transition(self, server_id, current_status, new_status):
169
        """Wait for server to go from current_status to new_status"""
170
        self.logger.debug("Waiting for server to become %s" % new_status)
171
        timeout = self.config.getint('Global', 'build_timeout')
172
        sleep_time = 5
173
        while True:
174
            server = self.cyclades_client.get_server_details(server_id)
175
            if server['status'] == new_status:
176
                return server
177
            elif timeout < 0:
178
                self.logger.error(
179
                    "Waiting for server to become %s timed out" % new_status)
180
                self.destroy_server(False)
181
                sys.exit(-1)
182
            elif server['status'] == current_status:
183
                # Sleep for #n secs and continue
184
                timeout = timeout - sleep_time
185
                time.sleep(sleep_time)
186
            else:
187
                self.logger.error(
188
                    "Server failed with status %s" % server['status'])
189
                self.destroy_server(False)
190
                sys.exit(-1)
191

    
192
    @_check_kamaki
193
    def destroy_server(self, wait=True):
194
        """Destroy slave server"""
195
        server_id = self.config.getint('Temporary Options', 'server_id')
196
        self.logger.info("Destoying server with id %s " % server_id)
197
        self.cyclades_client.delete_server(server_id)
198
        if wait:
199
            self._wait_transition(server_id, "ACTIVE", "DELETED")
200

    
201
    @_check_kamaki
202
    def create_server(self):
203
        """Create slave server"""
204
        self.logger.info("Create a new server..")
205
        image = self._find_image()
206
        self.logger.debug("Will use image \"%s\"" % _green(image['name']))
207
        self.logger.debug("Image has id %s" % _green(image['id']))
208
        server = self.cyclades_client.create_server(
209
            self.config.get('Deployment', 'server_name'),
210
            self.config.getint('Deployment', 'flavor_id'),
211
            image['id'])
212
        server_id = server['id']
213
        self.write_config('server_id', server_id)
214
        self.logger.debug("Server got id %s" % _green(server_id))
215
        server_user = server['metadata']['users']
216
        self.write_config('server_user', server_user)
217
        self.logger.debug("Server's admin user is %s" % _green(server_user))
218
        server_passwd = server['adminPass']
219
        self.write_config('server_passwd', server_passwd)
220

    
221
        server = self._wait_transition(server_id, "BUILD", "ACTIVE")
222
        self._get_server_ip_and_port(server)
223
        self._copy_ssh_keys()
224

    
225
        self.setup_fabric()
226
        self.logger.info("Setup firewall")
227
        accept_ssh_from = self.config.get('Global', 'filter_access_network')
228
        self.logger.debug("Block ssh except from %s" % accept_ssh_from)
229
        cmd = """
230
        local_ip=$(/sbin/ifconfig eth0 | grep 'inet addr:' | \
231
            cut -d':' -f2 | cut -d' ' -f1)
232
        iptables -A INPUT -s localhost -j ACCEPT
233
        iptables -A INPUT -s $local_ip -j ACCEPT
234
        iptables -A INPUT -s {0} -p tcp --dport 22 -j ACCEPT
235
        iptables -A INPUT -p tcp --dport 22 -j DROP
236
        """.format(accept_ssh_from)
237
        _run(cmd, False)
238

    
239
    def _find_image(self):
240
        """Find a suitable image to use
241

242
        It has to belong to the `system_uuid' user and
243
        contain the word `image_name'
244
        """
245
        system_uuid = self.config.get('Deployment', 'system_uuid')
246
        image_name = self.config.get('Deployment', 'image_name').lower()
247
        images = self.image_client.list_public(detail=True)['images']
248
        # Select images by `system_uuid' user
249
        images = [x for x in images if x['user_id'] == system_uuid]
250
        # Select images with `image_name' in their names
251
        images = \
252
            [x for x in images if x['name'].lower().find(image_name) != -1]
253
        # Let's select the first one
254
        return images[0]
255

    
256
    def _get_server_ip_and_port(self, server):
257
        """Compute server's IPv4 and ssh port number"""
258
        self.logger.info("Get server connection details..")
259
        # XXX: check if this IP is from public network
260
        server_ip = server['attachments'][0]['ipv4']
261
        if self.config.get('Deployment', 'deploy_on_io') == "True":
262
            tmp1 = int(server_ip.split(".")[2])
263
            tmp2 = int(server_ip.split(".")[3])
264
            server_ip = "gate.okeanos.io"
265
            server_port = 10000 + tmp1 * 256 + tmp2
266
        else:
267
            server_port = 22
268
        self.write_config('server_ip', server_ip)
269
        self.logger.debug("Server's IPv4 is %s" % _green(server_ip))
270
        self.write_config('server_port', server_port)
271
        self.logger.debug("Server's ssh port is %s" % _green(server_port))
272

    
273
    @_check_fabric
274
    def _copy_ssh_keys(self):
275
        authorized_keys = self.config.get("Deployment",
276
                                          "ssh_keys")
277
        if os.path.exists(authorized_keys):
278
            keyfile = '/tmp/%s.pub' % fabric.env.user
279
            _run('mkdir -p ~/.ssh && chmod 700 ~/.ssh', False)
280
            fabric.put(authorized_keys, keyfile)
281
            _run('cat %s >> ~/.ssh/authorized_keys' % keyfile, False)
282
            _run('rm %s' % keyfile, False)
283
            self.logger.debug("Uploaded ssh authorized keys")
284
        else:
285
            self.logger.debug("No ssh keys found")
286

    
287
    def write_config(self, option, value, section="Temporary Options"):
288
        """Write changes back to config file"""
289
        try:
290
            self.config.add_section(section)
291
        except DuplicateSectionError:
292
            pass
293
        self.config.set(section, option, str(value))
294
        temp_conf_file = self.config.get('Global', 'temporary_config')
295
        with open(temp_conf_file, 'wb') as tcf:
296
            self.config.write(tcf)
297

    
298
    def setup_fabric(self):
299
        """Setup fabric environment"""
300
        self.logger.info("Setup fabric parameters..")
301
        fabric.env.user = self.config.get('Temporary Options', 'server_user')
302
        fabric.env.host_string = \
303
            self.config.get('Temporary Options', 'server_ip')
304
        fabric.env.port = self.config.getint('Temporary Options',
305
                                             'server_port')
306
        fabric.env.password = self.config.get('Temporary Options',
307
                                              'server_passwd')
308
        fabric.env.connection_attempts = 10
309
        fabric.env.shell = "/bin/bash -c"
310
        fabric.env.disable_known_hosts = True
311
        fabric.env.output_prefix = None
312

    
313
    def _check_hash_sum(self, localfile, remotefile):
314
        """Check hash sums of two files"""
315
        self.logger.debug("Check hash sum for local file %s" % localfile)
316
        hash1 = os.popen("sha256sum %s" % localfile).read().split(' ')[0]
317
        self.logger.debug("Local file has sha256 hash %s" % hash1)
318
        self.logger.debug("Check hash sum for remote file %s" % remotefile)
319
        hash2 = _run("sha256sum %s" % remotefile, False)
320
        hash2 = hash2.split(' ')[0]
321
        self.logger.debug("Remote file has sha256 hash %s" % hash2)
322
        if hash1 != hash2:
323
            self.logger.error("Hashes differ.. aborting")
324
            sys.exit(-1)
325

    
326
    @_check_fabric
327
    def clone_repo(self):
328
        """Clone Synnefo repo from slave server"""
329
        self.logger.info("Configure repositories on remote server..")
330
        self.logger.debug("Setup apt, install curl and git")
331
        cmd = """
332
        echo 'APT::Install-Suggests "false";' >> /etc/apt/apt.conf
333
        apt-get update
334
        apt-get install curl git --yes
335
        echo -e "\n\ndeb {0}" >> /etc/apt/sources.list
336
        curl https://dev.grnet.gr/files/apt-grnetdev.pub | apt-key add -
337
        apt-get update
338
        git config --global user.name {1}
339
        git config --global user.mail {2}
340
        """.format(self.config.get('Global', 'apt_repo'),
341
                   self.config.get('Global', 'git_config_name'),
342
                   self.config.get('Global', 'git_config_mail'))
343
        _run(cmd, False)
344

    
345
        synnefo_repo = self.config.get('Global', 'synnefo_repo')
346
        synnefo_branch = self.config.get('Global', 'synnefo_branch')
347
        # Currently clonning synnefo can fail unexpectedly
348
        cloned = False
349
        for i in range(3):
350
            self.logger.debug("Clone synnefo from %s" % synnefo_repo)
351
            cmd = ("git clone --branch %s %s"
352
                   % (synnefo_branch, synnefo_repo))
353
            try:
354
                _run(cmd, False)
355
                cloned = True
356
                break
357
            except:
358
                self.logger.warning("Clonning synnefo failed.. retrying %s"
359
                                    % i)
360
        if not cloned:
361
            self.logger.error("Can not clone Synnefo repo.")
362
            sys.exit(-1)
363

    
364
        deploy_repo = self.config.get('Global', 'deploy_repo')
365
        self.logger.debug("Clone snf-deploy from %s" % deploy_repo)
366
        _run("git clone --depth 1 %s" % deploy_repo, False)
367

    
368
    @_check_fabric
369
    def build_synnefo(self):
370
        """Build Synnefo packages"""
371
        self.logger.info("Build Synnefo packages..")
372
        self.logger.debug("Install development packages")
373
        cmd = """
374
        apt-get update
375
        apt-get install zlib1g-dev dpkg-dev debhelper git-buildpackage \
376
                python-dev python-all python-pip --yes
377
        pip install devflow
378
        """
379
        _run(cmd, False)
380

    
381
        if self.config.get('Global', 'patch_pydist') == "True":
382
            self.logger.debug("Patch pydist.py module")
383
            cmd = r"""
384
            sed -r -i 's/(\(\?P<name>\[A-Za-z\]\[A-Za-z0-9_\.)/\1\\\-/' \
385
                /usr/share/python/debpython/pydist.py
386
            """
387
            _run(cmd, False)
388

389
        self.logger.debug("Build snf-deploy package")
390
        cmd = """
391
        git checkout -t origin/debian
392
        git-buildpackage --git-upstream-branch=master \
393
                --git-debian-branch=debian \
394
                --git-export-dir=../snf-deploy_build-area \
395
                -uc -us
396
        """
397
        with fabric.cd("snf-deploy"):
398
            _run(cmd, True)
399

400
        self.logger.debug("Install snf-deploy package")
401
        cmd = """
402
        dpkg -i snf-deploy*.deb
403
        apt-get -f install --yes
404
        """
405
        with fabric.cd("snf-deploy_build-area"):
406
            with fabric.settings(warn_only=True):
407
                _run(cmd, True)
408

409
        self.logger.debug("Build synnefo packages")
410
        cmd = """
411
        devflow-autopkg snapshot -b ~/synnefo_build-area --no-sign
412
        """
413
        with fabric.cd("synnefo"):
414
            _run(cmd, True)
415

416
        self.logger.debug("Copy synnefo debs to snf-deploy packages dir")
417
        cmd = """
418
        cp ~/synnefo_build-area/*.deb /var/lib/snf-deploy/packages/
419
        """
420
        _run(cmd, False)
421

422
    @_check_fabric
423
    def deploy_synnefo(self):
424
        """Deploy Synnefo using snf-deploy"""
425
        self.logger.info("Deploy Synnefo..")
426
        schema = self.config.get('Global', 'schema')
427
        schema_files = os.path.join(self.ci_dir, "schemas/%s/*" % schema)
428
        self.logger.debug("Will use %s schema" % schema)
429

430
        self.logger.debug("Upload schema files to server")
431
        with fabric.quiet():
432
            fabric.put(schema_files, "/etc/snf-deploy/")
433

434
        self.logger.debug("Change password in nodes.conf file")
435
        cmd = """
436
        sed -i 's/^password =.*/password = {0}/' /etc/snf-deploy/nodes.conf
437
        """.format(fabric.env.password)
438
        _run(cmd, False)
439

440
        self.logger.debug("Run snf-deploy")
441
        cmd = """
442
        snf-deploy all --autoconf
443
        """
444
        _run(cmd, True)
445

446
    @_check_fabric
447
    def unit_test(self):
448
        """Run Synnefo unit test suite"""
449
        self.logger.info("Run Synnefo unit test suite")
450
        component = self.config.get('Unit Tests', 'component')
451

452
        self.logger.debug("Install needed packages")
453
        cmd = """
454
        pip install mock
455
        pip install factory_boy
456
        """
457
        _run(cmd, False)
458

459
        self.logger.debug("Upload tests.sh file")
460
        unit_tests_file = os.path.join(self.ci_dir, "tests.sh")
461
        with fabric.quiet():
462
            fabric.put(unit_tests_file, ".")
463

464
        self.logger.debug("Run unit tests")
465
        cmd = """
466
        bash tests.sh {0}
467
        """.format(component)
468
        _run(cmd, True)
469

470
    @_check_fabric
471
    def run_burnin(self):
472
        """Run burnin functional test suite"""
473
        self.logger.info("Run Burnin functional test suite")
474
        cmd = """
475
        auth_url=$(grep -e '^url =' .kamakirc | cut -d' ' -f3)
476
        token=$(grep -e '^token =' .kamakirc | cut -d' ' -f3)
477
        images_user=$(kamaki image list -l | grep owner | \
478
                      cut -d':' -f2 | tr -d ' ')
479
        snf-burnin --auth-url=$auth_url --token=$token \
480
            --force-flavor=2 --image-id=all \
481
            --system-images-user=$images_user \
482
            {0}
483
        log_folder=$(ls -1d /var/log/burnin/* | tail -n1)
484
        for i in $(ls $log_folder/*/details*); do
485
            echo -e "\\n\\n"
486
            echo -e "***** $i\\n"
487
            cat $i
488
        done
489
        """.format(self.config.get('Burnin', 'cmd_options'))
490
        _run(cmd, True)
491

492
    @_check_fabric
493
    def fetch_packages(self):
494
        """Download Synnefo packages"""
495
        self.logger.info("Download Synnefo packages")
496
        self.logger.debug("Create tarball with packages")
497
        cmd = """
498
        tar czf synnefo_build-area.tgz synnefo_build-area
499
        """
500
        _run(cmd, False)
501

502
        pkgs_dir = self.config.get('Global', 'pkgs_dir')
503
        self.logger.debug("Fetch packages to local dir %s" % pkgs_dir)
504
        os.makedirs(pkgs_dir)
505
        with fabric.quiet():
506
            fabric.get("synnefo_build-area.tgz", pkgs_dir)
507

508
        pkgs_file = os.path.join(pkgs_dir, "synnefo_build-area.tgz")
509
        self._check_hash_sum(pkgs_file, "synnefo_build-area.tgz")
510

511
        self.logger.debug("Untar packages file %s" % pkgs_file)
512
        os.system("cd %s; tar xzf synnefo_build-area.tgz" % pkgs_dir)
513