Statistics
| Branch: | Tag: | Revision:

root / snf-deploy / snfdeploy / fabfile.py @ 6ce03057

History | View | Annotate | Download (41.2 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
    try_run("chown root.www-data /var/log/gunicorn")
438
    tmpl = "/etc/gunicorn.d/synnefo"
439
    replace = {}
440
    custom = customize_settings_from_tmpl(tmpl, replace)
441
    try_put(custom, tmpl, mode=0644)
442
    try_run("/etc/init.d/gunicorn restart")
443

    
444

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

    
471

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

    
485

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

    
500

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

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

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

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

    
531

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

    
537

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

    
561

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

    
583

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

    
592

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

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

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

    
610

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

    
629

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

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

    
644

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

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

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

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

    
684

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

    
695

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

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

    
716
    return (uid, user_auth_token, user_uuid)
717

    
718

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

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

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

    
742

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

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

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

    
770

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

    
783

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

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

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

    
806

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

    
820

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

    
827

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

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

    
841
    install_package("kamaki")
842
    install_package("snf-pithos-backend")
843
    install_package("snf-pithos-app")
844
    tmpl = "/etc/synnefo/pithos.conf"
845
    replace = {
846
        "ACCOUNTS": env.env.accounts.fqdn,
847
        "PITHOS": env.env.pithos.fqdn,
848
        "db_node": env.env.db.ip,
849
        "synnefo_user": env.env.synnefo_user,
850
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
851
        "pithos_dir": env.env.pithos_dir,
852
        "PITHOS_SERVICE_TOKEN": service_token,
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
        }
1164
    custom = customize_settings_from_tmpl(tmpl, replace)
1165
    try_put(custom, tmpl, mode=0644)
1166
    try_run("/etc/init.d/gunicorn restart")
1167

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

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

    
1177

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

    
1184

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

    
1199

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

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

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

    
1216

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

    
1226

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

    
1244

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

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

    
1269

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

    
1284

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

    
1296

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

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

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

    
1318

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

    
1326

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

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

    
1346

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

    
1353

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

    
1362

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

    
1377

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

    
1388

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