Statistics
| Branch: | Tag: | Revision:

root / snf-deploy / snfdeploy / fabfile.py @ 3bae85da

History | View | Annotate | Download (41.3 kB)

1
# Too many lines in module pylint: disable-msg=C0302
2
# Too many arguments (7/5) pylint: disable-msg=R0913
3
"""
4
Fabric file for snf-deploy
5

6
"""
7

    
8
from __future__ import with_statement
9
from fabric.api import hide, env, settings, local, roles
10
from fabric.operations import run, put, get
11
import fabric
12
import re
13
import os
14
import shutil
15
import tempfile
16
import ast
17
from snfdeploy.lib import debug, Conf, Env, disable_color
18
from snfdeploy import massedit
19

    
20

    
21
def setup_env(args):
22
    """Setup environment"""
23
    print("Loading configuration for synnefo...")
24

    
25
    conf = Conf(args)
26
    env.env = Env(conf)
27

    
28
    env.local = args.autoconf
29
    env.key_inject = args.key_inject
30
    env.password = env.env.password
31
    env.user = env.env.user
32
    env.shell = "/bin/bash -c"
33
    env.key_filename = args.ssh_key
34

    
35
    if args.disable_colors:
36
        disable_color()
37

    
38
    if env.env.cms.hostname in \
39
            [env.env.accounts.hostname, env.env.cyclades.hostname,
40
             env.env.pithos.hostname]:
41
        env.cms_pass = True
42
    else:
43
        env.cms_pass = False
44

    
45
    if env.env.accounts.hostname in \
46
            [env.env.cyclades.hostname, env.env.pithos.hostname]:
47
        env.csrf_disable = True
48
    else:
49
        env.csrf_disable = False
50

    
51
    env.roledefs = {
52
        "nodes": env.env.ips,
53
        "ips": env.env.ips,
54
        "accounts": [env.env.accounts.ip],
55
        "cyclades": [env.env.cyclades.ip],
56
        "pithos": [env.env.pithos.ip],
57
        "cms": [env.env.cms.ip],
58
        "mq": [env.env.mq.ip],
59
        "db": [env.env.db.ip],
60
        "mq": [env.env.mq.ip],
61
        "db": [env.env.db.ip],
62
        "ns": [env.env.ns.ip],
63
        "client": [env.env.client.ip],
64
        "router": [env.env.router.ip],
65
    }
66

    
67
    env.enable_lvm = False
68
    env.enable_drbd = False
69
    if ast.literal_eval(env.env.create_extra_disk) and env.env.extra_disk:
70
        env.enable_lvm = True
71
        env.enable_drbd = True
72

    
73
    env.roledefs.update({
74
        "ganeti": env.env.cluster_ips,
75
        "master": [env.env.master.ip],
76
    })
77

    
78

    
79
def install_package(package):
80
    debug(env.host, " * Installing package %s..." % package)
81
    apt_get = "export DEBIAN_FRONTEND=noninteractive ;" + \
82
              "apt-get install -y --force-yes "
83

    
84
    host_info = env.env.ips_info[env.host]
85
    env.env.update_packages(host_info.os)
86
    if ast.literal_eval(env.env.use_local_packages):
87
        with settings(warn_only=True):
88
            deb = local("ls %s/%s*%s_*.deb"
89
                        % (env.env.packages, package, host_info.os),
90
                        capture=True)
91
            if deb:
92
                debug(env.host,
93
                      " * Package %s found in %s..."
94
                      % (package, env.env.packages))
95
                try_put(deb, "/tmp/")
96
                try_run("dpkg -i /tmp/%s || "
97
                        % os.path.basename(deb) + apt_get + "-f")
98
                try_run("rm /tmp/%s" % os.path.basename(deb))
99
                return
100

    
101
    info = getattr(env.env, package)
102
    if info in \
103
            ["squeeze-backports", "squeeze", "stable",
104
             "testing", "unstable", "wheezy"]:
105
        apt_get += " -t %s %s " % (info, package)
106
    elif info:
107
        apt_get += " %s=%s " % (package, info)
108
    else:
109
        apt_get += package
110

    
111
    try_run(apt_get)
112

    
113
    return
114

    
115

    
116
@roles("ns")
117
def update_ns_for_ganeti():
118
    debug(env.host,
119
          "Updating name server entries for backend %s..."
120
          % env.env.cluster.fqdn)
121
    update_arecord(env.env.cluster)
122
    update_ptrrecord(env.env.cluster)
123
    try_run("/etc/init.d/bind9 restart")
124

    
125

    
126
@roles("ns")
127
def update_ns_for_node(node):
128
    info = env.env.nodes_info.get(node)
129
    update_arecord(info)
130
    update_ptrrecord(info)
131
    try_run("/etc/init.d/bind9 restart")
132

    
133

    
134
@roles("ns")
135
def update_arecord(host):
136
    filename = "/etc/bind/zones/" + env.env.domain
137
    cmd = """
138
    echo '{0}' >> {1}
139
    """.format(host.arecord, filename)
140
    try_run(cmd)
141

    
142

    
143
@roles("ns")
144
def update_cnamerecord(host):
145
    filename = "/etc/bind/zones/" + env.env.domain
146
    cmd = """
147
    echo '{0}' >> {1}
148
    """.format(host.cnamerecord, filename)
149
    try_run(cmd)
150

    
151

    
152
@roles("ns")
153
def update_ptrrecord(host):
154
    filename = "/etc/bind/rev/synnefo.in-addr.arpa.zone"
155
    cmd = """
156
    echo '{0}' >> {1}
157
    """.format(host.ptrrecord, filename)
158
    try_run(cmd)
159

    
160

    
161
@roles("nodes")
162
def apt_get_update():
163
    debug(env.host, "apt-get update....")
164
    try_run("apt-get update")
165

    
166

    
167
@roles("ns")
168
def setup_ns():
169
    debug(env.host, "Setting up name server..")
170
    #WARNING: this should be remove after we are done
171
    # because gevent does pick randomly nameservers and google does
172
    # not know our setup!!!!!
173
    apt_get_update()
174
    install_package("bind9")
175
    tmpl = "/etc/bind/named.conf.local"
176
    replace = {
177
        "domain": env.env.domain,
178
    }
179
    custom = customize_settings_from_tmpl(tmpl, replace)
180
    try_put(custom, tmpl)
181

    
182
    try_run("mkdir -p /etc/bind/zones")
183
    tmpl = "/etc/bind/zones/example.com"
184
    replace = {
185
        "domain": env.env.domain,
186
        "ns_node_ip": env.env.ns.ip,
187
    }
188
    custom = customize_settings_from_tmpl(tmpl, replace)
189
    remote = "/etc/bind/zones/" + env.env.domain
190
    try_put(custom, remote)
191

    
192
    try_run("mkdir -p /etc/bind/rev")
193
    tmpl = "/etc/bind/rev/synnefo.in-addr.arpa.zone"
194
    replace = {
195
        "domain": env.env.domain,
196
    }
197
    custom = customize_settings_from_tmpl(tmpl, replace)
198
    try_put(custom, tmpl)
199

    
200
    tmpl = "/etc/bind/named.conf.options"
201
    replace = {
202
        "NODE_IPS": ";".join(env.env.ips),
203
    }
204
    custom = customize_settings_from_tmpl(tmpl, replace)
205
    try_put(custom, tmpl, mode=0644)
206

    
207
    for role, info in env.env.roles.iteritems():
208
        if role == "ns":
209
            continue
210
        update_cnamerecord(info)
211
    for node, info in env.env.nodes_info.iteritems():
212
        update_arecord(info)
213
        update_ptrrecord(info)
214

    
215
    try_run("/etc/init.d/bind9 restart")
216

    
217

    
218
@roles("nodes")
219
def check_dhcp():
220
    debug(env.host, "Checking IPs for synnefo..")
221
    for n, info in env.env.nodes_info.iteritems():
222
        try_run("ping -c 1 " + info.ip)
223

    
224

    
225
@roles("nodes")
226
def check_dns():
227
    debug(env.host, "Checking fqdns for synnefo..")
228
    for n, info in env.env.nodes_info.iteritems():
229
        try_run("ping -c 1 " + info.fqdn)
230

    
231
    for n, info in env.env.roles.iteritems():
232
        try_run("ping -c 1 " + info.fqdn)
233

    
234

    
235
@roles("nodes")
236
def check_connectivity():
237
    debug(env.host, "Checking internet connectivity..")
238
    try_run("ping -c 1 www.google.com")
239

    
240

    
241
@roles("nodes")
242
def check_ssh():
243
    debug(env.host, "Checking password-less ssh..")
244
    for n, info in env.env.nodes_info.iteritems():
245
        try_run("ssh " + info.fqdn + "  date")
246

    
247

    
248
@roles("ips")
249
def add_keys():
250
    if not env.key_inject:
251
        debug(env.host, "Skipping ssh keys injection..")
252
        return
253
    else:
254
        debug(env.host, "Adding rsa/dsa keys..")
255
    try_run("mkdir -p /root/.ssh")
256
    cmd = """
257
for f in $(ls /root/.ssh/*); do
258
  cp $f $f.bak
259
done
260
    """
261
    try_run(cmd)
262
    files = ["authorized_keys", "id_dsa", "id_dsa.pub",
263
             "id_rsa", "id_rsa.pub"]
264
    for f in files:
265
        tmpl = "/root/.ssh/" + f
266
        replace = {}
267
        custom = customize_settings_from_tmpl(tmpl, replace)
268
        try_put(custom, tmpl, mode=0600)
269

    
270
    cmd = """
271
if [ -e /root/.ssh/authorized_keys.bak ]; then
272
  cat /root/.ssh/authorized_keys.bak >> /root/.ssh/authorized_keys
273
fi
274
    """
275
    debug(env.host, "Updating exising authorized keys..")
276
    try_run(cmd)
277

    
278

    
279
@roles("ips")
280
def setup_resolv_conf():
281
    debug(env.host, "Tweak /etc/resolv.conf...")
282
    try_run("/etc/init.d/network-manager stop", abort=False)
283
    tmpl = "/etc/dhcp/dhclient-enter-hooks.d/nodnsupdate"
284
    replace = {}
285
    custom = customize_settings_from_tmpl(tmpl, replace)
286
    try_put(custom, tmpl, mode=0644)
287
    try_run("cp /etc/resolv.conf /etc/resolv.conf.bak")
288
    tmpl = "/etc/resolv.conf"
289
    replace = {
290
        "domain": env.env.domain,
291
        "ns_node_ip": env.env.ns.ip,
292
    }
293
    custom = customize_settings_from_tmpl(tmpl, replace)
294
    try:
295
        try_put(custom, tmpl)
296
        cmd = """
297
        echo "\
298
# This has been generated automatically by snf-deploy, at
299
# $(date).
300
# The immutable bit (+i attribute) has been used to avoid it being
301
# overwritten by software such as NetworkManager or resolvconf.
302
# Use lsattr/chattr to view or modify its file attributes.
303

304

305
$(cat {0})" > {0}
306
""".format(tmpl)
307
        try_run(cmd)
308
    except:
309
        pass
310
    try_run("chattr +i /etc/resolv.conf")
311

    
312

    
313
@roles("ips")
314
def setup_hosts():
315
    debug(env.host, "Tweaking /etc/hosts and ssh_config files...")
316
    try_run("echo StrictHostKeyChecking no >> /etc/ssh/ssh_config")
317
    cmd = "sed -i 's/^127.*$/127.0.0.1 localhost/g' /etc/hosts "
318
    try_run(cmd)
319
    host_info = env.env.ips_info[env.host]
320
    cmd = "hostname %s" % host_info.hostname
321
    try_run(cmd)
322
    cmd = "echo %s > /etc/hostname" % host_info.hostname
323
    try_run(cmd)
324

    
325

    
326
def try_run(cmd, abort=True):
327
    try:
328
        if env.local:
329
            return local(cmd, capture=True)
330
        else:
331
            return run(cmd)
332
    except BaseException as e:
333
        if abort:
334
            fabric.utils.abort(e)
335
        else:
336
            debug(env.host, "WARNING: command failed. Continuing anyway...")
337

    
338

    
339
def try_put(local_path=None, remote_path=None, abort=True, **kwargs):
340
    try:
341
        put(local_path=local_path, remote_path=remote_path, **kwargs)
342
    except BaseException as e:
343
        if abort:
344
            fabric.utils.abort(e)
345
        else:
346
            debug(env.host, "WARNING: command failed. Continuing anyway...")
347

    
348

    
349
def try_get(remote_path, local_path=None, abort=True, **kwargs):
350
    try:
351
        get(remote_path, local_path=local_path, **kwargs)
352
    except BaseException as e:
353
        if abort:
354
            fabric.utils.abort(e)
355
        else:
356
            debug(env.host, "WARNING: command failed. Continuing anyway...")
357

    
358

    
359
def create_bridges():
360
    debug(env.host, " * Creating bridges...")
361
    install_package("bridge-utils")
362
    cmd = """
363
    brctl addbr {0} ; ip link set {0} up
364
    """.format(env.env.common_bridge)
365
    try_run(cmd)
366

    
367

    
368
def connect_bridges():
369
    debug(env.host, " * Connecting bridges...")
370
    #cmd = """
371
    #brctl addif {0} {1}
372
    #""".format(env.env.common_bridge, env.env.public_iface)
373
    #try_run(cmd)
374

    
375

    
376
@roles("ganeti")
377
def setup_net_infra():
378
    debug(env.host, "Setup networking infrastracture..")
379
    create_bridges()
380
    connect_bridges()
381

    
382

    
383
@roles("ganeti")
384
def setup_lvm():
385
    debug(env.host, "create volume group %s for ganeti.." % env.env.vg)
386
    if env.enable_lvm:
387
        install_package("lvm2")
388
        cmd = """
389
        pvcreate {0}
390
        vgcreate {1} {0}
391
        """.format(env.env.extra_disk, env.env.vg)
392
        try_run(cmd)
393

    
394

    
395
def customize_settings_from_tmpl(tmpl, replace):
396
    debug(env.host, " * Customizing template %s..." % tmpl)
397
    local = env.env.templates + tmpl
398
    _, custom = tempfile.mkstemp()
399
    shutil.copyfile(local, custom)
400
    for k, v in replace.iteritems():
401
        regex = "re.sub('%{0}%', '{1}', line)".format(k.upper(), v)
402
        massedit.edit_files([custom], [regex], dry_run=False)
403

    
404
    return custom
405

    
406

    
407
@roles("nodes")
408
def setup_apt():
409
    debug(env.host, "Setting up apt sources...")
410
    install_package("curl")
411
    cmd = """
412
    echo 'APT::Install-Suggests "false";' >> /etc/apt/apt.conf
413
    curl -k https://dev.grnet.gr/files/apt-grnetdev.pub | apt-key add -
414
    """
415
    try_run(cmd)
416
    host_info = env.env.ips_info[env.host]
417
    if host_info.os == "squeeze":
418
        tmpl = "/etc/apt/sources.list.d/synnefo.squeeze.list"
419
    else:
420
        tmpl = "/etc/apt/sources.list.d/synnefo.wheezy.list"
421
    replace = {}
422
    custom = customize_settings_from_tmpl(tmpl, replace)
423
    try_put(custom, tmpl)
424
    apt_get_update()
425

    
426

    
427
@roles("cyclades", "cms", "pithos", "accounts")
428
def restart_services():
429
    debug(env.host, " * Restarting apache2 and gunicorn...")
430
    try_run("/etc/init.d/gunicorn restart")
431
    try_run("/etc/init.d/apache2 restart")
432

    
433

    
434
def setup_gunicorn():
435
    debug(env.host, " * Setting up gunicorn...")
436
    install_package("gunicorn")
437
    tmpl = "/etc/gunicorn.d/synnefo"
438
    replace = {}
439
    custom = customize_settings_from_tmpl(tmpl, replace)
440
    try_put(custom, tmpl, mode=0644)
441
    try_run("/etc/init.d/gunicorn restart")
442

    
443

    
444
def setup_apache():
445
    debug(env.host, " * Setting up apache2...")
446
    host_info = env.env.ips_info[env.host]
447
    install_package("apache2")
448
    tmpl = "/etc/apache2/sites-available/synnefo"
449
    replace = {
450
        "HOST": host_info.fqdn,
451
    }
452
    custom = customize_settings_from_tmpl(tmpl, replace)
453
    try_put(custom, tmpl)
454
    tmpl = "/etc/apache2/sites-available/synnefo-ssl"
455
    custom = customize_settings_from_tmpl(tmpl, replace)
456
    try_put(custom, tmpl)
457
    cmd = """
458
    a2enmod ssl
459
    a2enmod rewrite
460
    a2dissite default
461
    a2ensite synnefo
462
    a2ensite synnefo-ssl
463
    a2enmod headers
464
    a2enmod proxy_http
465
    a2dismod autoindex
466
    """
467
    try_run(cmd)
468
    try_run("/etc/init.d/apache2 restart")
469

    
470

    
471
@roles("mq")
472
def setup_mq():
473
    debug(env.host, "Setting up RabbitMQ...")
474
    install_package("rabbitmq-server")
475
    cmd = """
476
    rabbitmqctl add_user {0} {1}
477
    rabbitmqctl set_permissions {0} ".*" ".*" ".*"
478
    rabbitmqctl delete_user guest
479
    rabbitmqctl set_user_tags {0} administrator
480
    """.format(env.env.synnefo_user, env.env.synnefo_rabbitmq_passwd)
481
    try_run(cmd)
482
    try_run("/etc/init.d/rabbitmq-server restart")
483

    
484

    
485
@roles("db")
486
def allow_access_in_db(ip, user="all", method="md5"):
487
    cmd = """
488
    pg_hba=$(ls /etc/postgresql/*/main/pg_hba.conf)
489
    echo host all {0} {1}/32 {2} >> $pg_hba
490
    """.format(user, ip, method)
491
    try_run(cmd)
492
    cmd = """
493
    pg_hba=$(ls /etc/postgresql/*/main/pg_hba.conf)
494
    sed -i 's/\(host.*127.0.0.1.*\)md5/\\1trust/' $pg_hba
495
    """
496
    try_run(cmd)
497
    try_run("/etc/init.d/postgresql restart")
498

    
499

    
500
@roles("db")
501
def setup_db():
502
    debug(env.host, "Setting up DataBase server...")
503
    install_package("postgresql")
504

    
505
    tmpl = "/tmp/db-init.psql"
506
    replace = {
507
        "synnefo_user": env.env.synnefo_user,
508
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
509
        }
510
    custom = customize_settings_from_tmpl(tmpl, replace)
511
    try_put(custom, tmpl)
512
    cmd = 'su - postgres -c "psql -w -f %s" ' % tmpl
513
    try_run(cmd)
514
    cmd = """
515
    conf=$(ls /etc/postgresql/*/main/postgresql.conf)
516
    echo "listen_addresses = '*'" >> $conf
517
    """
518
    try_run(cmd)
519

    
520
    if env.env.testing_vm:
521
        cmd = """
522
        conf=$(ls /etc/postgresql/*/main/postgresql.conf)
523
        echo "fsync=off\nsynchronous_commit=off\nfull_page_writes=off" >> $conf
524
        """
525
        try_run(cmd)
526

    
527
    allow_access_in_db(env.host, "all", "trust")
528
    try_run("/etc/init.d/postgresql restart")
529

    
530

    
531
@roles("db")
532
def destroy_db():
533
    try_run("""su - postgres -c ' psql -w -c "drop database snf_apps" '""")
534
    try_run("""su - postgres -c ' psql -w -c "drop database snf_pithos" '""")
535

    
536

    
537
def setup_webproject():
538
    debug(env.host, " * Setting up snf-webproject...")
539
    with settings(hide("everything")):
540
        try_run("ping -c1 " + env.env.db.ip)
541
    setup_common()
542
    install_package("snf-webproject")
543
    install_package("python-psycopg2")
544
    install_package("python-gevent")
545
    install_package("python-django")
546
    tmpl = "/etc/synnefo/webproject.conf"
547
    replace = {
548
        "synnefo_user": env.env.synnefo_user,
549
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
550
        "db_node": env.env.db.ip,
551
        "domain": env.env.domain,
552
    }
553
    custom = customize_settings_from_tmpl(tmpl, replace)
554
    try_put(custom, tmpl, mode=0644)
555
    with settings(host_string=env.env.db.ip):
556
        host_info = env.env.ips_info[env.host]
557
        allow_access_in_db(host_info.ip, "all", "trust")
558
    try_run("/etc/init.d/gunicorn restart")
559

    
560

    
561
def setup_common():
562
    debug(env.host, " * Setting up snf-common...")
563
    host_info = env.env.ips_info[env.host]
564
    install_package("python-objpool")
565
    install_package("snf-common")
566
    install_package("python-astakosclient")
567
    install_package("snf-django-lib")
568
    install_package("snf-branding")
569
    tmpl = "/etc/synnefo/common.conf"
570
    replace = {
571
        #FIXME:
572
        "EMAIL_SUBJECT_PREFIX": env.host,
573
        "domain": env.env.domain,
574
        "HOST": host_info.fqdn,
575
        "MAIL_DIR": env.env.mail_dir,
576
    }
577
    custom = customize_settings_from_tmpl(tmpl, replace)
578
    try_put(custom, tmpl, mode=0644)
579
    try_run("mkdir -p {0}; chmod 777 {0}".format(env.env.mail_dir))
580
    try_run("/etc/init.d/gunicorn restart")
581

    
582

    
583
@roles("accounts")
584
def astakos_loaddata():
585
    debug(env.host, " * Loading initial data to astakos...")
586
    cmd = """
587
    snf-manage loaddata groups
588
    """
589
    try_run(cmd)
590

    
591

    
592
@roles("accounts")
593
def astakos_register_components():
594
    debug(env.host, " * Register services in astakos...")
595

    
596
    cyclades_base_url = "https://%s/cyclades" % env.env.cyclades.fqdn
597
    pithos_base_url = "https://%s/pithos" % env.env.pithos.fqdn
598
    astakos_base_url = "https://%s/astakos" % env.env.accounts.fqdn
599

    
600
    cmd = """
601
    snf-manage component-add "home" --ui-url https://{0}
602
    snf-manage component-add "cyclades" --base-url {1} --ui-url {1}/ui
603
    snf-manage component-add "pithos" --base-url {2} --ui-url {2}/ui
604
    snf-manage component-add "astakos" --base-url {3} --ui-url {3}/ui
605
    """.format(env.env.cms.fqdn, cyclades_base_url,
606
               pithos_base_url, astakos_base_url)
607
    try_run(cmd)
608

    
609

    
610
@roles("accounts")
611
def add_user():
612
    debug(env.host, " * adding user %s to astakos..." % env.env.user_email)
613
    email = env.env.user_email
614
    name = env.env.user_name
615
    lastname = env.env.user_lastname
616
    passwd = env.env.user_passwd
617
    cmd = """
618
    snf-manage user-add {0} {1} {2}
619
    """.format(email, name, lastname)
620
    try_run(cmd)
621
    with settings(host_string=env.env.db.ip):
622
        uid, user_auth_token, user_uuid = get_auth_token_from_db(email)
623
    cmd = """
624
    snf-manage user-modify --password {0} {1}
625
    """.format(passwd, uid)
626
    try_run(cmd)
627

    
628

    
629
@roles("accounts")
630
def activate_user(user_email=None):
631
    if not user_email:
632
        user_email = env.env.user_email
633
    debug(env.host, " * Activate user %s..." % user_email)
634
    with settings(host_string=env.env.db.ip):
635
        uid, user_auth_token, user_uuid = get_auth_token_from_db(user_email)
636

    
637
    cmd = """
638
    snf-manage user-modify --verify {0}
639
    snf-manage user-modify --accept {0}
640
    """.format(uid)
641
    try_run(cmd)
642

    
643

    
644
@roles("accounts")
645
def setup_astakos():
646
    debug(env.host, "Setting up snf-astakos-app...")
647
    setup_gunicorn()
648
    setup_apache()
649
    setup_webproject()
650
    install_package("python-django-south")
651
    install_package("snf-astakos-app")
652
    install_package("kamaki")
653

    
654
    tmpl = "/etc/synnefo/astakos.conf"
655
    replace = {
656
        "ACCOUNTS": env.env.accounts.fqdn,
657
        "domain": env.env.domain,
658
        "CYCLADES": env.env.cyclades.fqdn,
659
        "PITHOS": env.env.pithos.fqdn,
660
    }
661
    custom = customize_settings_from_tmpl(tmpl, replace)
662
    try_put(custom, tmpl, mode=0644)
663
    if env.csrf_disable:
664
        cmd = """
665
cat <<EOF >> /etc/synnefo/astakos.conf
666
try:
667
  MIDDLEWARE_CLASSES.remove('django.middleware.csrf.CsrfViewMiddleware')
668
except:
669
  pass
670
EOF
671
"""
672
        try_run(cmd)
673

    
674
    try_run("/etc/init.d/gunicorn restart")
675

    
676
    cmd = """
677
    snf-manage syncdb --noinput
678
    snf-manage migrate im --delete-ghost-migrations
679
    snf-manage migrate quotaholder_app
680
    """
681
    try_run(cmd)
682

    
683

    
684
@roles("accounts")
685
def get_service_details(service="pithos"):
686
    debug(env.host,
687
          " * Getting registered details for %s service..." % service)
688
    result = try_run("snf-manage component-list -o id,name,token")
689
    r = re.compile(r".*%s.*" % service, re.M)
690
    service_id, _, service_token = r.search(result).group().split()
691
    # print("%s: %s %s" % (service, service_id, service_token))
692
    return (service_id, service_token)
693

    
694

    
695
@roles("db")
696
def get_auth_token_from_db(user_email=None):
697
    if not user_email:
698
        user_email = env.env.user_email
699
    debug(env.host,
700
          " * Getting authentication token and uuid for user %s..."
701
          % user_email)
702
    cmd = """
703
echo "select id, auth_token, uuid, email from auth_user, im_astakosuser \
704
where auth_user.id = im_astakosuser.user_ptr_id and auth_user.email = '{0}';" \
705
> /tmp/psqlcmd
706
su - postgres -c  "psql -w -d snf_apps -f /tmp/psqlcmd"
707
""".format(user_email)
708

    
709
    result = try_run(cmd)
710
    r = re.compile(r"(\d+)[ |]*(\S+)[ |]*(\S+)[ |]*" + user_email, re.M)
711
    match = r.search(result)
712
    uid, user_auth_token, user_uuid = match.groups()
713
    # print("%s: %s %s %s" % ( user_email, uid, user_auth_token, user_uuid))
714

    
715
    return (uid, user_auth_token, user_uuid)
716

    
717

    
718
@roles("cms")
719
def cms_loaddata():
720
    debug(env.host, " * Loading cms initial data...")
721
    if env.cms_pass:
722
        debug(env.host, "Aborting. Prerequisites not met.")
723
        return
724
    tmpl = "/tmp/sites.json"
725
    replace = {}
726
    custom = customize_settings_from_tmpl(tmpl, replace)
727
    try_put(custom, tmpl)
728

    
729
    tmpl = "/tmp/page.json"
730
    replace = {}
731
    custom = customize_settings_from_tmpl(tmpl, replace)
732
    try_put(custom, tmpl)
733

    
734
    cmd = """
735
    snf-manage loaddata /tmp/sites.json
736
    snf-manage loaddata /tmp/page.json
737
    snf-manage createsuperuser --username=admin --email=admin@{0} --noinput
738
    """.format(env.env.domain)
739
    try_run(cmd)
740

    
741

    
742
@roles("cms")
743
def setup_cms():
744
    debug(env.host, "Setting up cms...")
745
    if env.cms_pass:
746
        debug(env.host, "Aborting. Prerequisites not met.")
747
        return
748
    with settings(hide("everything")):
749
        try_run("ping -c1 accounts." + env.env.domain)
750
    setup_gunicorn()
751
    setup_apache()
752
    setup_webproject()
753
    install_package("snf-cloudcms")
754

    
755
    tmpl = "/etc/synnefo/cms.conf"
756
    replace = {
757
        "ACCOUNTS": env.env.accounts.fqdn,
758
        }
759
    custom = customize_settings_from_tmpl(tmpl, replace)
760
    try_put(custom, tmpl, mode=0644)
761
    try_run("/etc/init.d/gunicorn restart")
762

    
763
    cmd = """
764
    snf-manage syncdb
765
    snf-manage migrate --delete-ghost-migrations
766
    """.format(env.env.domain)
767
    try_run(cmd)
768

    
769

    
770
def setup_nfs_dirs():
771
    debug(env.host, " * Creating NFS mount point for pithos and ganeti...")
772
    cmd = """
773
    mkdir -p {0}
774
    cd {0}
775
    mkdir -p data
776
    chown www-data:www-data data
777
    chmod g+ws data
778
    mkdir -p {1}
779
    """.format(env.env.pithos_dir, env.env.image_dir)
780
    try_run(cmd)
781

    
782

    
783
@roles("nodes")
784
def setup_nfs_clients():
785
    if env.host == env.env.pithos.ip:
786
        return
787

    
788
    host_info = env.env.ips_info[env.host]
789
    debug(env.host, " * Mounting pithos NFS mount point...")
790
    with settings(hide("everything")):
791
        try_run("ping -c1 " + env.env.pithos.hostname)
792
    with settings(host_string=env.env.pithos.ip):
793
        update_nfs_exports(host_info.ip)
794

    
795
    install_package("nfs-common")
796
    for d in [env.env.pithos_dir, env.env.image_dir]:
797
        try_run("mkdir -p " + d)
798
        cmd = """
799
echo "{0}:{1} {1}  nfs defaults,rw,noatime,rsize=131072,\
800
wsize=131072,timeo=14,intr,noacl" >> /etc/fstab
801
""".format(env.env.pithos.ip, d)
802
        try_run(cmd)
803
        try_run("mount " + d)
804

    
805

    
806
@roles("pithos")
807
def update_nfs_exports(ip):
808
    tmpl = "/tmp/exports"
809
    replace = {
810
        "pithos_dir": env.env.pithos_dir,
811
        "image_dir": env.env.image_dir,
812
        "ip": ip,
813
    }
814
    custom = customize_settings_from_tmpl(tmpl, replace)
815
    try_put(custom, tmpl)
816
    try_run("cat %s >> /etc/exports" % tmpl)
817
    try_run("/etc/init.d/nfs-kernel-server restart")
818

    
819

    
820
@roles("pithos")
821
def setup_nfs_server():
822
    debug(env.host, " * Setting up NFS server for pithos...")
823
    setup_nfs_dirs()
824
    install_package("nfs-kernel-server")
825

    
826

    
827
@roles("pithos")
828
def setup_pithos():
829
    debug(env.host, "Setting up snf-pithos-app...")
830
    with settings(hide("everything")):
831
        try_run("ping -c1 accounts." + env.env.domain)
832
        try_run("ping -c1 " + env.env.db.ip)
833
    setup_gunicorn()
834
    setup_apache()
835
    setup_webproject()
836

    
837
    with settings(host_string=env.env.accounts.ip):
838
        service_id, service_token = get_service_details("pithos")
839

    
840
    install_package("kamaki")
841
    install_package("snf-pithos-backend")
842
    install_package("snf-pithos-app")
843
    tmpl = "/etc/synnefo/pithos.conf"
844
    replace = {
845
        "ACCOUNTS": env.env.accounts.fqdn,
846
        "PITHOS": env.env.pithos.fqdn,
847
        "db_node": env.env.db.ip,
848
        "synnefo_user": env.env.synnefo_user,
849
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
850
        "pithos_dir": env.env.pithos_dir,
851
        "PITHOS_SERVICE_TOKEN": service_token,
852
        "proxy": env.env.pithos.hostname == env.env.accounts.hostname
853
        }
854
    custom = customize_settings_from_tmpl(tmpl, replace)
855
    try_put(custom, tmpl, mode=0644)
856
    try_run("/etc/init.d/gunicorn restart")
857

    
858
    install_package("snf-pithos-webclient")
859
    tmpl = "/etc/synnefo/webclient.conf"
860
    replace = {
861
        "ACCOUNTS": env.env.accounts.fqdn,
862
        "PITHOS_UI_CLOUDBAR_ACTIVE_SERVICE": service_id,
863
        }
864
    custom = customize_settings_from_tmpl(tmpl, replace)
865
    try_put(custom, tmpl, mode=0644)
866

    
867
    try_run("/etc/init.d/gunicorn restart")
868
    #TOFIX: the previous command lets pithos-backend create blocks and maps
869
    #       with root owner
870
    try_run("chown -R www-data:www-data %s/data " % env.env.pithos_dir)
871
    #try_run("pithos-migrate stamp 4c8ccdc58192")
872
    #try_run("pithos-migrate upgrade head")
873

    
874

    
875
@roles("ganeti")
876
def setup_ganeti():
877
    debug(env.host, "Setting up snf-ganeti...")
878
    node_info = env.env.ips_info[env.host]
879
    with settings(hide("everything")):
880
        #if env.enable_lvm:
881
        #    try_run("vgs " + env.env.vg)
882
        try_run("getent hosts " + env.env.cluster.fqdn)
883
        try_run("getent hosts %s | grep -v ^127" % env.host)
884
        try_run("hostname -f | grep " + node_info.fqdn)
885
        #try_run("ip link show " + env.env.common_bridge)
886
        #try_run("ip link show " + env.env.common_bridge)
887
        #try_run("apt-get update")
888
    install_package("qemu-kvm")
889
    install_package("python-bitarray")
890
    install_package("ganeti-htools")
891
    install_package("snf-ganeti")
892
    try_run("mkdir -p /srv/ganeti/file-storage/")
893
    cmd = """
894
cat <<EOF > /etc/ganeti/file-storage-paths
895
/srv/ganeti/file-storage
896
/srv/ganeti/shared-file-storage
897
EOF
898
"""
899
    try_run(cmd)
900

    
901

    
902
@roles("master")
903
def add_rapi_user():
904
    debug(env.host, " * Adding RAPI user to Ganeti backend...")
905
    cmd = """
906
    echo -n "{0}:Ganeti Remote API:{1}" | openssl md5 | sed 's/^.* //'
907
    """.format(env.env.synnefo_user, env.env.synnefo_rapi_passwd)
908
    result = try_run(cmd)
909
    if result.startswith("(stdin)= "):
910
        result = result.split("(stdin)= ")[1]
911
    cmd = """
912
    echo "{0} {1}{2} write" >> /var/lib/ganeti/rapi/users
913
    """.format(env.env.synnefo_user, '{ha1}', result)
914
    try_run(cmd)
915
    try_run("/etc/init.d/ganeti restart")
916

    
917

    
918
@roles("master")
919
def add_nodes():
920
    nodes = env.env.cluster_nodes.split(",")
921
    nodes.remove(env.env.master_node)
922
    debug(env.host, " * Adding nodes to Ganeti backend...")
923
    for n in nodes:
924
        add_node(n)
925

    
926

    
927
@roles("master")
928
def add_node(node):
929
    node_info = env.env.nodes_info[node]
930
    debug(env.host, " * Adding node %s to Ganeti backend..." % node_info.fqdn)
931
    cmd = "gnt-node add --no-ssh-key-check --master-capable=yes " + \
932
          "--vm-capable=yes " + node_info.fqdn
933
    try_run(cmd)
934

    
935

    
936
@roles("ganeti")
937
def enable_drbd():
938
    if env.enable_drbd:
939
        debug(env.host, " * Enabling DRBD...")
940
        install_package("drbd8-utils")
941
        try_run("modprobe drbd minor_count=255 usermode_helper=/bin/true")
942
        try_run("echo drbd minor_count=255 usermode_helper=/bin/true " +
943
                ">> /etc/modules")
944

    
945

    
946
@roles("master")
947
def setup_drbd_dparams():
948
    if env.enable_drbd:
949
        debug(env.host,
950
              " * Twicking drbd related disk parameters in Ganeti...")
951
        cmd = """
952
        gnt-cluster modify --disk-parameters=drbd:metavg={0}
953
        gnt-group modify --disk-parameters=drbd:metavg={0} default
954
        """.format(env.env.vg)
955
        try_run(cmd)
956

    
957

    
958
@roles("master")
959
def enable_lvm():
960
    if env.enable_lvm:
961
        debug(env.host, " * Enabling LVM...")
962
        cmd = """
963
        gnt-cluster modify --vg-name={0}
964
        """.format(env.env.vg)
965
        try_run(cmd)
966
    else:
967
        debug(env.host, " * Disabling LVM...")
968
        try_run("gnt-cluster modify --no-lvm-storage")
969

    
970

    
971
@roles("master")
972
def destroy_cluster():
973
    debug(env.host, " * Destroying Ganeti cluster...")
974
    #TODO: remove instances first
975
    allnodes = env.env.cluster_hostnames[:]
976
    allnodes.remove(env.host)
977
    for n in allnodes:
978
        host_info = env.env.ips_info[env.host]
979
        debug(env.host, " * Removing node %s..." % n)
980
        cmd = "gnt-node remove  " + host_info.fqdn
981
        try_run(cmd)
982
    try_run("gnt-cluster destroy --yes-do-it")
983

    
984

    
985
@roles("master")
986
def init_cluster():
987
    debug(env.host, " * Initializing Ganeti backend...")
988
    # extra = ""
989
    # if env.enable_lvm:
990
    #     extra += " --vg-name={0} ".format(env.env.vg)
991
    # else:
992
    #     extra += " --no-lvm-storage "
993
    # if not env.enable_drbd:
994
    #     extra += " --no-drbd-storage "
995
    extra = " --no-lvm-storage --no-drbd-storage "
996
    cmd = """
997
    gnt-cluster init --enabled-hypervisors=kvm \
998
        {0} \
999
        --nic-parameters link={1},mode=bridged \
1000
        --master-netdev {2} \
1001
        --default-iallocator hail \
1002
        --hypervisor-parameters kvm:kernel_path=,vnc_bind_address=0.0.0.0 \
1003
        --no-ssh-init --no-etc-hosts \
1004
        {3}
1005
    """.format(extra, env.env.common_bridge,
1006
               env.env.cluster_netdev, env.env.cluster.fqdn)
1007
    try_run(cmd)
1008

    
1009

    
1010
@roles("ganeti")
1011
def debootstrap():
1012
    install_package("ganeti-instance-debootstrap")
1013

    
1014

    
1015
@roles("ganeti")
1016
def setup_image_host():
1017
    debug(env.host, "Setting up snf-image...")
1018
    install_package("snf-pithos-backend")
1019
    install_package("snf-image")
1020
    try_run("mkdir -p %s" % env.env.image_dir)
1021
    tmpl = "/etc/default/snf-image"
1022
    replace = {
1023
        "synnefo_user": env.env.synnefo_user,
1024
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
1025
        "pithos_dir": env.env.pithos_dir,
1026
        "db_node": env.env.db.ip,
1027
        "image_dir": env.env.image_dir,
1028
    }
1029
    custom = customize_settings_from_tmpl(tmpl, replace)
1030
    try_put(custom, tmpl)
1031

    
1032

    
1033
@roles("ganeti")
1034
def setup_image_helper():
1035
    debug(env.host, " * Updating helper image...")
1036
    cmd = """
1037
    snf-image-update-helper -y
1038
    """
1039
    try_run(cmd)
1040

    
1041

    
1042
@roles("ganeti")
1043
def setup_gtools():
1044
    debug(env.host, " * Setting up snf-cyclades-gtools...")
1045
    with settings(hide("everything")):
1046
        try_run("ping -c1 " + env.env.mq.ip)
1047
    setup_common()
1048
    install_package("snf-cyclades-gtools")
1049
    tmpl = "/etc/synnefo/gtools.conf"
1050
    replace = {
1051
        "synnefo_user": env.env.synnefo_user,
1052
        "synnefo_rabbitmq_passwd": env.env.synnefo_rabbitmq_passwd,
1053
        "mq_node": env.env.mq.ip,
1054
    }
1055
    custom = customize_settings_from_tmpl(tmpl, replace)
1056
    try_put(custom, tmpl)
1057

    
1058
    cmd = """
1059
    sed -i 's/false/true/' /etc/default/snf-ganeti-eventd
1060
    /etc/init.d/snf-ganeti-eventd start
1061
    """
1062
    try_run(cmd)
1063

    
1064

    
1065
@roles("ganeti")
1066
def setup_iptables():
1067
    debug(env.host, " * Setting up iptables to mangle DHCP requests...")
1068
    cmd = """
1069
    iptables -t mangle -A PREROUTING -i br+ -p udp -m udp --dport 67 \
1070
            -j NFQUEUE --queue-num 42
1071
    iptables -t mangle -A PREROUTING -i tap+ -p udp -m udp --dport 67 \
1072
            -j NFQUEUE --queue-num 42
1073
    iptables -t mangle -A PREROUTING -i prv+ -p udp -m udp --dport 67 \
1074
            -j NFQUEUE --queue-num 42
1075

1076
    ip6tables -t mangle -A PREROUTING -i br+ -p ipv6-icmp -m icmp6 \
1077
            --icmpv6-type 133 -j NFQUEUE --queue-num 43
1078
    ip6tables -t mangle -A PREROUTING -i br+ -p ipv6-icmp -m icmp6 \
1079
            --icmpv6-type 135 -j NFQUEUE --queue-num 44
1080
    """
1081
    try_run(cmd)
1082

    
1083

    
1084
@roles("ganeti")
1085
def setup_network():
1086
    debug(env.host,
1087
          "Setting up networking for Ganeti instances (nfdhcpd, etc.)...")
1088
    install_package("nfqueue-bindings-python")
1089
    install_package("nfdhcpd")
1090
    tmpl = "/etc/nfdhcpd/nfdhcpd.conf"
1091
    replace = {
1092
        "ns_node_ip": env.env.ns.ip
1093
    }
1094
    custom = customize_settings_from_tmpl(tmpl, replace)
1095
    try_put(custom, tmpl)
1096
    try_run("/etc/init.d/nfdhcpd restart")
1097

    
1098
    install_package("snf-network")
1099
    cmd = """
1100
sed -i 's/MAC_MASK.*/MAC_MASK = ff:ff:f0:00:00:00/' /etc/default/snf-network
1101
    """
1102
    try_run(cmd)
1103

    
1104

    
1105
@roles("router")
1106
def setup_router():
1107
    debug(env.host, " * Setting up internal router for NAT...")
1108
    cmd = """
1109
    echo 1 > /proc/sys/net/ipv4/ip_forward
1110
    iptables -t nat -A POSTROUTING -s {0} -o {3} -j MASQUERADE
1111
    ip addr add {1} dev {2}
1112
    ip route add {0} dev {2} src {1}
1113
    """.format(env.env.synnefo_public_network_subnet,
1114
               env.env.synnefo_public_network_gateway,
1115
               env.env.common_bridge, env.env.public_iface)
1116
    try_run(cmd)
1117

    
1118

    
1119
@roles("cyclades")
1120
def cyclades_loaddata():
1121
    debug(env.host, " * Loading initial data for cyclades...")
1122
    try_run("snf-manage flavor-create %s %s %s %s" % (env.env.flavor_cpu,
1123
                                                      env.env.flavor_ram,
1124
                                                      env.env.flavor_disk,
1125
                                                      env.env.flavor_storage))
1126
    #run("snf-manage loaddata flavors")
1127

    
1128

    
1129
@roles("cyclades")
1130
def setup_cyclades():
1131
    debug(env.host, "Setting up snf-cyclades-app...")
1132
    with settings(hide("everything")):
1133
        try_run("ping -c1 accounts." + env.env.domain)
1134
        try_run("ping -c1 " + env.env.db.ip)
1135
        try_run("ping -c1 " + env.env.mq.ip)
1136
    setup_gunicorn()
1137
    setup_apache()
1138
    setup_webproject()
1139
    install_package("memcached")
1140
    install_package("python-memcache")
1141
    install_package("snf-pithos-backend")
1142
    install_package("kamaki")
1143
    install_package("snf-cyclades-app")
1144
    install_package("python-django-south")
1145
    tmpl = "/etc/synnefo/cyclades.conf"
1146

    
1147
    with settings(host_string=env.env.accounts.ip):
1148
        service_id, service_token = get_service_details("cyclades")
1149

    
1150
    replace = {
1151
        "ACCOUNTS": env.env.accounts.fqdn,
1152
        "CYCLADES": env.env.cyclades.fqdn,
1153
        "mq_node": env.env.mq.ip,
1154
        "db_node": env.env.db.ip,
1155
        "synnefo_user": env.env.synnefo_user,
1156
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
1157
        "synnefo_rabbitmq_passwd": env.env.synnefo_rabbitmq_passwd,
1158
        "pithos_dir": env.env.pithos_dir,
1159
        "common_bridge": env.env.common_bridge,
1160
        "HOST": env.env.cyclades.ip,
1161
        "domain": env.env.domain,
1162
        "CYCLADES_SERVICE_TOKEN": service_token,
1163
        "proxy": env.env.cyclades.hostname == env.env.accounts.hostname
1164
        }
1165
    custom = customize_settings_from_tmpl(tmpl, replace)
1166
    try_put(custom, tmpl, mode=0644)
1167
    try_run("/etc/init.d/gunicorn restart")
1168

    
1169
    cmd = """
1170
    sed -i 's/false/true/' /etc/default/snf-dispatcher
1171
    /etc/init.d/snf-dispatcher start
1172
    """
1173
    try_run(cmd)
1174

    
1175
    try_run("snf-manage syncdb")
1176
    try_run("snf-manage migrate --delete-ghost-migrations")
1177

    
1178

    
1179
@roles("cyclades")
1180
def get_backend_id(cluster_name="ganeti1.synnefo.deploy.local"):
1181
    backend_id = try_run("snf-manage backend-list 2>/dev/null " +
1182
                         "| grep %s | awk '{print $1}'" % cluster_name)
1183
    return backend_id
1184

    
1185

    
1186
@roles("cyclades")
1187
def add_backend():
1188
    debug(env.host,
1189
          "adding %s ganeti backend to cyclades..." % env.env.cluster.fqdn)
1190
    with settings(hide("everything")):
1191
        try_run("ping -c1 " + env.env.cluster.fqdn)
1192
    cmd = """
1193
    snf-manage backend-add --clustername={0} --user={1} --pass={2}
1194
    """.format(env.env.cluster.fqdn, env.env.synnefo_user,
1195
               env.env.synnefo_rapi_passwd)
1196
    try_run(cmd)
1197
    backend_id = get_backend_id(env.env.cluster.fqdn)
1198
    try_run("snf-manage backend-modify --drained=False " + backend_id)
1199

    
1200

    
1201
@roles("cyclades")
1202
def pin_user_to_backend(user_email):
1203
    backend_id = get_backend_id(env.env.cluster.fqdn)
1204
    # pin user to backend
1205
    cmd = """
1206
cat <<EOF >> /etc/synnefo/cyclades.conf
1207

1208
BACKEND_PER_USER = {
1209
  '{0}': {1},
1210
}
1211

1212
EOF
1213
/etc/init.d/gunicorn restart
1214
""".format(user_email, backend_id)
1215
    try_run(cmd)
1216

    
1217

    
1218
@roles("cyclades")
1219
def add_pools():
1220
    debug(env.host,
1221
          " * Creating pools of resources (brigdes, mac prefixes) " +
1222
          "in cyclades...")
1223
    try_run("snf-manage pool-create --type=mac-prefix " +
1224
            "--base=aa:00:0 --size=65536")
1225
    try_run("snf-manage pool-create --type=bridge --base=prv --size=20")
1226

    
1227

    
1228
@roles("accounts", "cyclades", "pithos")
1229
def export_services():
1230
    debug(env.host, " * Exporting services...")
1231
    host = env.host
1232
    services = []
1233
    if host == env.env.cyclades.ip:
1234
        services.append("cyclades")
1235
    if host == env.env.pithos.ip:
1236
        services.append("pithos")
1237
    if host == env.env.accounts.ip:
1238
        services.append("astakos")
1239
    for service in services:
1240
        filename = "%s_services.json" % service
1241
        cmd = "snf-manage service-export-%s > %s" % (service, filename)
1242
        run(cmd)
1243
        try_get(filename, filename+".local")
1244

    
1245

    
1246
@roles("accounts")
1247
def import_services():
1248
    debug(env.host, " * Registering services to astakos...")
1249
    for service in ["cyclades", "pithos", "astakos"]:
1250
        filename = "%s_services.json" % service
1251
        try_put(filename + ".local", filename)
1252
        cmd = "snf-manage service-import --json=%s" % filename
1253
        run(cmd)
1254

    
1255
    debug(env.host, " * Setting default quota...")
1256
    cmd = """
1257
    snf-manage resource-modify --limit 40G pithos.diskspace
1258
    snf-manage resource-modify --limit 2 astakos.pending_app
1259
    snf-manage resource-modify --limit 4 cyclades.vm
1260
    snf-manage resource-modify --limit 40G cyclades.disk
1261
    snf-manage resource-modify --limit 16G cyclades.ram
1262
    snf-manage resource-modify --limit 8G cyclades.active_ram
1263
    snf-manage resource-modify --limit 32 cyclades.cpu
1264
    snf-manage resource-modify --limit 16 cyclades.active_cpu
1265
    snf-manage resource-modify --limit 4 cyclades.network.private
1266
    snf-manage resource-modify --limit 4 cyclades.floating_ip
1267
    """
1268
    try_run(cmd)
1269

    
1270

    
1271
@roles("cyclades")
1272
def add_network():
1273
    debug(env.host, " * Adding public network in cyclades...")
1274
    backend_id = get_backend_id(env.env.cluster.fqdn)
1275
    cmd = """
1276
    snf-manage network-create --subnet={0} --gateway={1} --public \
1277
        --dhcp=True --flavor={2} --mode=bridged --link={3} --name=Internet \
1278
        --backend-id={4}
1279
    """.format(env.env.synnefo_public_network_subnet,
1280
               env.env.synnefo_public_network_gateway,
1281
               env.env.synnefo_public_network_type,
1282
               env.env.common_bridge, backend_id)
1283
    try_run(cmd)
1284

    
1285

    
1286
@roles("cyclades")
1287
def setup_vncauthproxy():
1288
    debug(env.host, " * Setting up vncauthproxy...")
1289
    install_package("snf-vncauthproxy")
1290
    cmd = """
1291
    echo CHUID="www-data:nogroup" >> /etc/default/vncauthproxy
1292
    rm /var/log/vncauthproxy/vncauthproxy.log
1293
    """
1294
    try_run(cmd)
1295
    try_run("/etc/init.d/vncauthproxy restart")
1296

    
1297

    
1298
@roles("client")
1299
def setup_kamaki():
1300
    debug(env.host, "Setting up kamaki client...")
1301
    with settings(hide("everything")):
1302
        try_run("ping -c1 accounts." + env.env.domain)
1303
        try_run("ping -c1 cyclades." + env.env.domain)
1304
        try_run("ping -c1 pithos." + env.env.domain)
1305

    
1306
    with settings(host_string=env.env.db.ip):
1307
        uid, user_auth_token, user_uuid = \
1308
            get_auth_token_from_db(env.env.user_email)
1309

    
1310
    install_package("python-progress")
1311
    install_package("kamaki")
1312
    cmd = """
1313
    kamaki config set cloud.default.url "https://{0}/astakos/identity/v2.0/"
1314
    kamaki config set cloud.default.token {1}
1315
    """.format(env.env.accounts.fqdn, user_auth_token)
1316
    try_run(cmd)
1317
    try_run("kamaki file create images")
1318

    
1319

    
1320
@roles("client")
1321
def upload_image(image="debian_base.diskdump"):
1322
    debug(env.host, " * Uploading initial image to pithos...")
1323
    image = "debian_base.diskdump"
1324
    try_run("wget {0} -O /tmp/{1}".format(env.env.debian_base_url, image))
1325
    try_run("kamaki file upload --container images /tmp/{0} {0}".format(image))
1326

    
1327

    
1328
@roles("client")
1329
def register_image(image="debian_base.diskdump"):
1330
    debug(env.host, " * Register image to plankton...")
1331
    # with settings(host_string=env.env.db.ip):
1332
    #     uid, user_auth_token, user_uuid = \
1333
    #        get_auth_token_from_db(env.env.user_email)
1334

    
1335
    image_location = "images:{0}".format(image)
1336
    cmd = """
1337
    sleep 5
1338
    kamaki image register "Debian Base" {0} --public --disk-format=diskdump \
1339
            --property OSFAMILY=linux --property ROOT_PARTITION=1 \
1340
            --property description="Debian Squeeze Base System" \
1341
            --property size=450M --property kernel=2.6.32 \
1342
            --property GUI="No GUI" --property sortorder=1 \
1343
            --property USERS=root --property OS=debian
1344
    """.format(image_location)
1345
    try_run(cmd)
1346

    
1347

    
1348
@roles("client")
1349
def setup_burnin():
1350
    debug(env.host, "Setting up burnin testing tool...")
1351
    install_package("kamaki")
1352
    install_package("snf-tools")
1353

    
1354

    
1355
@roles("pithos")
1356
def add_image_locally():
1357
    debug(env.host,
1358
          " * Getting image locally in order snf-image to use it directly..")
1359
    image = "debian_base.diskdump"
1360
    try_run("wget {0} -O {1}/{2}".format(
1361
            env.env.debian_base_url, env.env.image_dir, image))
1362

    
1363

    
1364
@roles("master")
1365
def gnt_instance_add(name="test"):
1366
    debug(env.host, " * Adding test instance to Ganeti...")
1367
    osp = """img_passwd=gamwtosecurity,\
1368
img_format=diskdump,img_id=debian_base,\
1369
img_properties='{"OSFAMILY":"linux"\,"ROOT_PARTITION":"1"}'"""
1370
    cmd = """
1371
    gnt-instance add  -o snf-image+default --os-parameters {0} \
1372
            -t plain --disk 0:size=1G --no-name-check --no-ip-check \
1373
            --net 0:ip=pool,network=test --no-install \
1374
            --hypervisor-parameters kvm:machine_version=pc-1.0 {1}
1375
    """.format(osp, name)
1376
    try_run(cmd)
1377

    
1378

    
1379
@roles("master")
1380
def gnt_network_add(name="test", subnet="10.0.0.0/26", gw="10.0.0.1",
1381
                    mode="bridged", link="br0"):
1382
    debug(env.host, " * Adding test network to Ganeti...")
1383
    cmd = """
1384
    gnt-network add --network={1} --gateway={2} {0}
1385
    gnt-network connect {0} {3} {4}
1386
    """.format(name, subnet, gw, mode, link)
1387
    try_run(cmd)
1388

    
1389

    
1390
@roles("ips")
1391
def test():
1392
    debug(env.host, "Testing...")
1393
    try_run("hostname && date")