Statistics
| Branch: | Tag: | Revision:

root / snf-deploy / fabfile.py @ 9772cb94

History | View | Annotate | Download (40.8 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 re
12
import os
13
import shutil
14
import tempfile
15
import ast
16
from snfdeploy.lib import debug, Conf, Env, disable_color
17
from snfdeploy import massedit
18

    
19

    
20
def setup_env(confdir="conf", packages="packages", templates="files",
21
              cluster_name="ganeti1", autoconf=False, disable_colors=False,
22
              key_inject=False):
23
    """Setup environment"""
24
    print("Loading configuration for synnefo...")
25
    print(" * Using config files under %s..." % confdir)
26
    print(" * Using %s and %s for packages and templates accordingly..."
27
          % (packages, templates))
28

    
29
    autoconf = ast.literal_eval(autoconf)
30
    disable_colors = ast.literal_eval(disable_colors)
31
    env.key_inject = ast.literal_eval(key_inject)
32
    conf = Conf.configure(confdir=confdir, cluster_name=cluster_name,
33
                          autoconf=autoconf)
34
    env.env = Env(conf)
35

    
36
    env.local = autoconf
37
    env.password = env.env.password
38
    env.user = env.env.user
39
    env.shell = "/bin/bash -c"
40

    
41
    if disable_colors:
42
        disable_color()
43

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

    
51
    if env.env.accounts.hostname in \
52
            [env.env.cyclades.hostname, env.env.pithos.hostname]:
53
        env.csrf_disable = True
54
    else:
55
        env.csrf_disable = False
56

    
57
    env.roledefs = {
58
        "nodes": env.env.ips,
59
        "ips": env.env.ips,
60
        "accounts": [env.env.accounts.ip],
61
        "cyclades": [env.env.cyclades.ip],
62
        "pithos": [env.env.pithos.ip],
63
        "cms": [env.env.cms.ip],
64
        "mq": [env.env.mq.ip],
65
        "db": [env.env.db.ip],
66
        "mq": [env.env.mq.ip],
67
        "db": [env.env.db.ip],
68
        "ns": [env.env.ns.ip],
69
        "client": [env.env.client.ip],
70
        "router": [env.env.router.ip],
71
    }
72

    
73
    env.enable_lvm = False
74
    env.enable_drbd = False
75
    if ast.literal_eval(env.env.create_extra_disk) and env.env.extra_disk:
76
        env.enable_lvm = True
77
        env.enable_drbd = True
78

    
79
    env.roledefs.update({
80
        "ganeti": env.env.cluster_ips,
81
        "master": [env.env.master.ip],
82
    })
83

    
84

    
85
def install_package(package):
86
    debug(env.host, " * Installing package %s..." % package)
87
    apt_get = "export DEBIAN_FRONTEND=noninteractive ;" + \
88
              "apt-get install -y --force-yes "
89

    
90
    host_info = env.env.ips_info[env.host]
91
    env.env.update_packages(host_info.os)
92
    if ast.literal_eval(env.env.use_local_packages):
93
        with settings(warn_only=True):
94
            deb = local("ls %s/%s*%s_all.deb"
95
                        % (env.env.packages, package, host_info.os),
96
                        capture=True)
97
            if deb:
98
                debug(env.host,
99
                      " * Package %s found in %s..."
100
                      % (package, env.env.packages))
101
                put(deb, "/tmp/")
102
                try_run("dpkg -i /tmp/%s || "
103
                        % os.path.basename(deb) + apt_get + "-f")
104
                try_run("rm /tmp/%s" % os.path.basename(deb))
105
                return
106

    
107
    info = getattr(env.env, package)
108
    if info in \
109
            ["squeeze-backports", "squeeze", "stable",
110
             "testing", "unstable", "wheezy"]:
111
        apt_get += " -t %s %s " % (info, package)
112
    elif info:
113
        apt_get += " %s=%s " % (package, info)
114
    else:
115
        apt_get += package
116

    
117
    try_run(apt_get)
118

    
119
    return
120

    
121

    
122
@roles("ns")
123
def update_ns_for_ganeti():
124
    debug(env.host,
125
          "Updating name server entries for backend %s..."
126
          % env.env.cluster.fqdn)
127
    update_arecord(env.env.cluster)
128
    update_ptrrecord(env.env.cluster)
129
    try_run("/etc/init.d/bind9 restart")
130

    
131

    
132
@roles("ns")
133
def update_ns_for_node(node):
134
    info = env.env.nodes_info.get(node)
135
    update_arecord(info)
136
    update_ptrrecord(info)
137
    try_run("/etc/init.d/bind9 restart")
138

    
139

    
140
@roles("ns")
141
def update_arecord(host):
142
    filename = "/etc/bind/zones/" + env.env.domain
143
    cmd = """
144
    echo '{0}' >> {1}
145
    """.format(host.arecord, filename)
146
    try_run(cmd)
147

    
148

    
149
@roles("ns")
150
def update_cnamerecord(host):
151
    filename = "/etc/bind/zones/" + env.env.domain
152
    cmd = """
153
    echo '{0}' >> {1}
154
    """.format(host.cnamerecord, filename)
155
    try_run(cmd)
156

    
157

    
158
@roles("ns")
159
def update_ptrrecord(host):
160
    filename = "/etc/bind/rev/synnefo.in-addr.arpa.zone"
161
    cmd = """
162
    echo '{0}' >> {1}
163
    """.format(host.ptrrecord, filename)
164
    try_run(cmd)
165

    
166

    
167
@roles("nodes")
168
def apt_get_update():
169
    debug(env.host, "apt-get update....")
170
    try_run("apt-get update")
171

    
172

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

    
188
    try_run("mkdir -p /etc/bind/zones")
189
    tmpl = "/etc/bind/zones/example.com"
190
    replace = {
191
        "domain": env.env.domain,
192
        "ns_node_ip": env.env.ns.ip,
193
    }
194
    custom = customize_settings_from_tmpl(tmpl, replace)
195
    remote = "/etc/bind/zones/" + env.env.domain
196
    put(custom, remote)
197

    
198
    try_run("mkdir -p /etc/bind/rev")
199
    tmpl = "/etc/bind/rev/synnefo.in-addr.arpa.zone"
200
    replace = {
201
        "domain": env.env.domain,
202
    }
203
    custom = customize_settings_from_tmpl(tmpl, replace)
204
    put(custom, tmpl)
205

    
206
    tmpl = "/etc/bind/named.conf.options"
207
    replace = {
208
        "NODE_IPS": ";".join(env.env.ips),
209
    }
210
    custom = customize_settings_from_tmpl(tmpl, replace)
211
    put(custom, tmpl, mode=0644)
212

    
213
    for role, info in env.env.roles.iteritems():
214
        if role == "ns":
215
            continue
216
        update_cnamerecord(info)
217
    for node, info in env.env.nodes_info.iteritems():
218
        update_arecord(info)
219
        update_ptrrecord(info)
220

    
221
    try_run("/etc/init.d/bind9 restart")
222

    
223

    
224
@roles("nodes")
225
def check_dhcp():
226
    debug(env.host, "Checking IPs for synnefo..")
227
    for n, info in env.env.nodes_info.iteritems():
228
        try_run("ping -c 1 " + info.ip, True)
229

    
230

    
231
@roles("nodes")
232
def check_dns():
233
    debug(env.host, "Checking fqdns for synnefo..")
234
    for n, info in env.env.nodes_info.iteritems():
235
        try_run("ping -c 1 " + info.fqdn, True)
236

    
237
    for n, info in env.env.roles.iteritems():
238
        try_run("ping -c 1 " + info.fqdn, True)
239

    
240

    
241
@roles("nodes")
242
def check_connectivity():
243
    debug(env.host, "Checking internet connectivity..")
244
    try_run("ping -c 1 www.google.com", True)
245

    
246

    
247
@roles("nodes")
248
def check_ssh():
249
    debug(env.host, "Checking password-less ssh..")
250
    for n, info in env.env.nodes_info.iteritems():
251
        try_run("ssh " + info.fqdn + "  date", True)
252

    
253

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

    
276
    cmd = """
277
if [ -e /root/.ssh/authorized_keys.bak ]; then
278
  cat /root/.ssh/authorized_keys.bak >> /root/.ssh/authorized_keys
279
fi
280
    """
281
    debug(env.host, "Updating exising authorized keys..")
282
    try_run(cmd)
283

    
284

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

310

311
$(cat {0})" > {0}
312
""".format(tmpl)
313
        try_run(cmd)
314
    except:
315
        pass
316
    try_run("chattr +i /etc/resolv.conf")
317

    
318

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

    
331

    
332
def try_run(cmd, abort=False):
333
    try:
334
        if env.local:
335
            return local(cmd, capture=True)
336
        else:
337
            return run(cmd)
338
    except:
339
        debug(env.host, "WARNING: command failed. Continuing anyway...")
340
        if abort:
341
            raise
342

    
343

    
344
def create_bridges():
345
    debug(env.host, " * Creating bridges...")
346
    install_package("bridge-utils")
347
    cmd = """
348
    brctl addbr {0} ; ip link set {0} up
349
    """.format(env.env.common_bridge)
350
    try_run(cmd)
351

    
352

    
353
def connect_bridges():
354
    debug(env.host, " * Connecting bridges...")
355
    #cmd = """
356
    #brctl addif {0} {1}
357
    #""".format(env.env.common_bridge, env.env.public_iface)
358
    #try_run(cmd)
359

    
360

    
361
@roles("ganeti")
362
def setup_net_infra():
363
    debug(env.host, "Setup networking infrastracture..")
364
    create_bridges()
365
    connect_bridges()
366

    
367

    
368
@roles("ganeti")
369
def setup_lvm():
370
    debug(env.host, "create volume group %s for ganeti.." % env.env.vg)
371
    if env.enable_lvm:
372
        install_package("lvm2")
373
        cmd = """
374
        pvcreate {0}
375
        vgcreate {1} {0}
376
        """.format(env.env.extra_disk, env.env.vg)
377
        try_run(cmd)
378

    
379

    
380
def customize_settings_from_tmpl(tmpl, replace):
381
    debug(env.host, " * Customizing template %s..." % tmpl)
382
    local = env.env.templates + tmpl
383
    _, custom = tempfile.mkstemp()
384
    shutil.copyfile(local, custom)
385
    for k, v in replace.iteritems():
386
        regex = "re.sub('%{0}%', '{1}', line)".format(k.upper(), v)
387
        massedit.edit_files([custom], [regex], dry_run=False)
388

    
389
    return custom
390

    
391

    
392
@roles("nodes")
393
def setup_apt():
394
    debug(env.host, "Setting up apt sources...")
395
    install_package("curl")
396
    cmd = """
397
    echo 'APT::Install-Suggests "false";' >> /etc/apt/apt.conf
398
    curl -k https://dev.grnet.gr/files/apt-grnetdev.pub | apt-key add -
399
    """
400
    try_run(cmd)
401
    host_info = env.env.ips_info[env.host]
402
    if host_info.os == "squeeze":
403
        tmpl = "/etc/apt/sources.list.d/synnefo.squeeze.list"
404
    else:
405
        tmpl = "/etc/apt/sources.list.d/synnefo.wheezy.list"
406
    replace = {}
407
    custom = customize_settings_from_tmpl(tmpl, replace)
408
    put(custom, tmpl)
409
    apt_get_update()
410

    
411

    
412
@roles("cyclades", "cms", "pithos", "accounts")
413
def restart_services():
414
    debug(env.host, " * Restarting apache2 and gunicorn...")
415
    try_run("/etc/init.d/gunicorn restart")
416
    try_run("/etc/init.d/apache2 restart")
417

    
418

    
419
def setup_gunicorn():
420
    debug(env.host, " * Setting up gunicorn...")
421
    install_package("gunicorn")
422
    tmpl = "/etc/gunicorn.d/synnefo"
423
    replace = {}
424
    custom = customize_settings_from_tmpl(tmpl, replace)
425
    put(custom, tmpl, mode=0644)
426
    try_run("/etc/init.d/gunicorn restart")
427

    
428

    
429
def setup_apache():
430
    debug(env.host, " * Setting up apache2...")
431
    host_info = env.env.ips_info[env.host]
432
    install_package("apache2")
433
    tmpl = "/etc/apache2/sites-available/synnefo"
434
    replace = {
435
        "HOST": host_info.fqdn,
436
    }
437
    custom = customize_settings_from_tmpl(tmpl, replace)
438
    put(custom, tmpl)
439
    tmpl = "/etc/apache2/sites-available/synnefo-ssl"
440
    custom = customize_settings_from_tmpl(tmpl, replace)
441
    put(custom, tmpl)
442
    cmd = """
443
    a2enmod ssl
444
    a2enmod rewrite
445
    a2dissite default
446
    a2ensite synnefo
447
    a2ensite synnefo-ssl
448
    a2enmod headers
449
    a2enmod proxy_http
450
    a2dismod autoindex
451
    """
452
    try_run(cmd)
453
    try_run("/etc/init.d/apache2 restart")
454

    
455

    
456
@roles("mq")
457
def setup_mq():
458
    debug(env.host, "Setting up RabbitMQ...")
459
    install_package("rabbitmq-server")
460
    cmd = """
461
    rabbitmqctl add_user {0} {1}
462
    rabbitmqctl set_permissions {0} ".*" ".*" ".*"
463
    rabbitmqctl delete_user guest
464
    rabbitmqctl set_user_tags {0} administrator
465
    """.format(env.env.synnefo_user, env.env.synnefo_rabbitmq_passwd)
466
    try_run(cmd)
467
    try_run("/etc/init.d/rabbitmq-server restart")
468

    
469

    
470
@roles("db")
471
def allow_access_in_db(ip, user="all", method="md5"):
472
    cmd = """
473
    pg_hba=$(ls /etc/postgresql/*/main/pg_hba.conf)
474
    echo host all {0} {1}/32 {2} >> $pg_hba
475
    """.format(user, ip, method)
476
    try_run(cmd)
477
    cmd = """
478
    pg_hba=$(ls /etc/postgresql/*/main/pg_hba.conf)
479
    sed -i 's/\(host.*127.0.0.1.*\)md5/\\1trust/' $pg_hba
480
    """
481
    try_run(cmd)
482
    try_run("/etc/init.d/postgresql restart")
483

    
484

    
485
@roles("db")
486
def setup_db():
487
    debug(env.host, "Setting up DataBase server...")
488
    install_package("postgresql")
489

    
490
    tmpl = "/tmp/db-init.psql"
491
    replace = {
492
        "synnefo_user": env.env.synnefo_user,
493
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
494
        }
495
    custom = customize_settings_from_tmpl(tmpl, replace)
496
    put(custom, tmpl)
497
    cmd = 'su - postgres -c "psql -w -f %s" ' % tmpl
498
    try_run(cmd)
499
    cmd = """
500
    conf=$(ls /etc/postgresql/*/main/postgresql.conf)
501
    echo "listen_addresses = '*'" >> $conf
502
    """
503
    try_run(cmd)
504

    
505
    if env.env.testing_vm:
506
        cmd = """
507
        conf=$(ls /etc/postgresql/*/main/postgresql.conf)
508
        echo "fsync=off\nsynchronous_commit=off\nfull_page_writes=off" >> $conf
509
        """
510
        try_run(cmd)
511

    
512
    allow_access_in_db(env.host, "all", "trust")
513
    try_run("/etc/init.d/postgresql restart")
514

    
515

    
516
@roles("db")
517
def destroy_db():
518
    try_run("""su - postgres -c ' psql -w -c "drop database snf_apps" '""")
519
    try_run("""su - postgres -c ' psql -w -c "drop database snf_pithos" '""")
520

    
521

    
522
def setup_webproject():
523
    debug(env.host, " * Setting up snf-webproject...")
524
    with settings(hide("everything")):
525
        try_run("ping -c1 " + env.env.db.ip)
526
    setup_common()
527
    install_package("snf-webproject")
528
    install_package("python-psycopg2")
529
    install_package("python-gevent")
530
    tmpl = "/etc/synnefo/webproject.conf"
531
    replace = {
532
        "synnefo_user": env.env.synnefo_user,
533
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
534
        "db_node": env.env.db.ip,
535
        "domain": env.env.domain,
536
    }
537
    custom = customize_settings_from_tmpl(tmpl, replace)
538
    put(custom, tmpl, mode=0644)
539
    with settings(host_string=env.env.db.ip):
540
        host_info = env.env.ips_info[env.host]
541
        allow_access_in_db(host_info.ip, "all", "trust")
542
    try_run("/etc/init.d/gunicorn restart")
543

    
544

    
545
def setup_common():
546
    debug(env.host, " * Setting up snf-common...")
547
    host_info = env.env.ips_info[env.host]
548
    install_package("python-objpool")
549
    install_package("snf-common")
550
    install_package("python-astakosclient")
551
    install_package("snf-django-lib")
552
    install_package("snf-branding")
553
    tmpl = "/etc/synnefo/common.conf"
554
    replace = {
555
        #FIXME:
556
        "EMAIL_SUBJECT_PREFIX": env.host,
557
        "domain": env.env.domain,
558
        "HOST": host_info.fqdn,
559
        "MAIL_DIR": env.env.mail_dir,
560
    }
561
    custom = customize_settings_from_tmpl(tmpl, replace)
562
    put(custom, tmpl, mode=0644)
563
    try_run("mkdir -p {0}; chown root:www-data {0}; chmod 775 {0}".format(
564
            env.env.mail_dir))
565
    try_run("/etc/init.d/gunicorn restart")
566

    
567

    
568
@roles("accounts")
569
def astakos_loaddata():
570
    debug(env.host, " * Loading initial data to astakos...")
571
    cmd = """
572
    snf-manage loaddata groups
573
    """
574
    try_run(cmd)
575

    
576

    
577
@roles("accounts")
578
def astakos_register_components():
579
    debug(env.host, " * Register services in astakos...")
580

    
581
    cyclades_base_url = "https://%s/cyclades/" % env.env.cyclades.fqdn
582
    pithos_base_url = "https://%s/pithos/" % env.env.pithos.fqdn
583
    astakos_base_url = "https://%s/astakos/" % env.env.accounts.fqdn
584

    
585
    cmd = """
586
    snf-manage component-add "home" https://{0} home-icon.png
587
    snf-manage component-add "cyclades" {1}ui/
588
    snf-manage component-add "pithos" {2}ui/
589
    snf-manage component-add "astakos" {3}ui/
590
    """.format(env.env.cms.fqdn, cyclades_base_url,
591
               pithos_base_url, astakos_base_url)
592
    try_run(cmd)
593

    
594

    
595
@roles("accounts")
596
def add_user():
597
    debug(env.host, " * adding user %s to astakos..." % env.env.user_email)
598
    email = env.env.user_email
599
    name = env.env.user_name
600
    lastname = env.env.user_lastname
601
    passwd = env.env.user_passwd
602
    cmd = """
603
    snf-manage user-add {0} {1} {2}
604
    """.format(email, name, lastname)
605
    try_run(cmd)
606
    with settings(host_string=env.env.db.ip):
607
        uid, user_auth_token, user_uuid = get_auth_token_from_db(email)
608
    cmd = """
609
    snf-manage user-modify --password {0} {1}
610
    """.format(passwd, uid)
611
    try_run(cmd)
612

    
613

    
614
@roles("accounts")
615
def activate_user(user_email=None):
616
    if not user_email:
617
        user_email = env.env.user_email
618
    debug(env.host, " * Activate user %s..." % user_email)
619
    with settings(host_string=env.env.db.ip):
620
        uid, user_auth_token, user_uuid = get_auth_token_from_db(user_email)
621

    
622
    cmd = """
623
    snf-manage user-modify --verify {0}
624
    snf-manage user-modify --accept {0}
625
    """.format(uid)
626
    try_run(cmd)
627

    
628

    
629
@roles("accounts")
630
def setup_astakos():
631
    debug(env.host, "Setting up snf-astakos-app...")
632
    setup_gunicorn()
633
    setup_apache()
634
    setup_webproject()
635
    install_package("python-django-south")
636
    install_package("snf-astakos-app")
637
    install_package("kamaki")
638

    
639
    tmpl = "/etc/synnefo/astakos.conf"
640
    replace = {
641
        "ACCOUNTS": env.env.accounts.fqdn,
642
        "domain": env.env.domain,
643
        "CYCLADES": env.env.cyclades.fqdn,
644
        "PITHOS": env.env.pithos.fqdn,
645
    }
646
    custom = customize_settings_from_tmpl(tmpl, replace)
647
    put(custom, tmpl, mode=0644)
648
    if env.csrf_disable:
649
        cmd = """
650
cat <<EOF >> /etc/synnefo/astakos.conf
651
try:
652
  MIDDLEWARE_CLASSES.remove('django.middleware.csrf.CsrfViewMiddleware')
653
except:
654
  pass
655
EOF
656
"""
657
        try_run(cmd)
658

    
659
    try_run("/etc/init.d/gunicorn restart")
660

    
661
    cmd = """
662
    snf-manage syncdb --noinput
663
    snf-manage migrate im --delete-ghost-migrations
664
    snf-manage migrate quotaholder_app
665
    """
666
    try_run(cmd)
667

    
668

    
669
@roles("accounts")
670
def get_service_details(service="pithos"):
671
    debug(env.host,
672
          " * Getting registered details for %s service..." % service)
673
    result = try_run("snf-manage component-list")
674
    r = re.compile(r".*%s.*" % service, re.M)
675
    service_id, _, _, service_token = r.search(result).group().split()
676
    # print("%s: %s %s" % (service, service_id, service_token))
677
    return (service_id, service_token)
678

    
679

    
680
@roles("db")
681
def get_auth_token_from_db(user_email=None):
682
    if not user_email:
683
        user_email = env.env.user_email
684
    debug(env.host,
685
          " * Getting authentication token and uuid for user %s..."
686
          % user_email)
687
    cmd = """
688
echo "select id, auth_token, uuid, email from auth_user, im_astakosuser \
689
where auth_user.id = im_astakosuser.user_ptr_id and auth_user.email = '{0}';" \
690
> /tmp/psqlcmd
691
su - postgres -c  "psql -w -d snf_apps -f /tmp/psqlcmd"
692
""".format(user_email)
693

    
694
    result = try_run(cmd)
695
    r = re.compile(r"(\d+)[ |]*(\S+)[ |]*(\S+)[ |]*" + user_email, re.M)
696
    match = r.search(result)
697
    uid, user_auth_token, user_uuid = match.groups()
698
    # print("%s: %s %s %s" % ( user_email, uid, user_auth_token, user_uuid))
699

    
700
    return (uid, user_auth_token, user_uuid)
701

    
702

    
703
@roles("cms")
704
def cms_loaddata():
705
    debug(env.host, " * Loading cms initial data...")
706
    if env.cms_pass:
707
        debug(env.host, "Aborting. Prerequisites not met.")
708
        return
709
    tmpl = "/tmp/sites.json"
710
    replace = {}
711
    custom = customize_settings_from_tmpl(tmpl, replace)
712
    put(custom, tmpl)
713

    
714
    tmpl = "/tmp/page.json"
715
    replace = {}
716
    custom = customize_settings_from_tmpl(tmpl, replace)
717
    put(custom, tmpl)
718

    
719
    cmd = """
720
    snf-manage loaddata /tmp/sites.json
721
    snf-manage loaddata /tmp/page.json
722
    snf-manage createsuperuser --username=admin --email=admin@{0} --noinput
723
    """.format(env.env.domain)
724
    try_run(cmd)
725

    
726

    
727
@roles("cms")
728
def setup_cms():
729
    debug(env.host, "Setting up cms...")
730
    if env.cms_pass:
731
        debug(env.host, "Aborting. Prerequisites not met.")
732
        return
733
    with settings(hide("everything")):
734
        try_run("ping -c1 accounts." + env.env.domain)
735
    setup_gunicorn()
736
    setup_apache()
737
    setup_webproject()
738
    install_package("snf-cloudcms")
739

    
740
    tmpl = "/etc/synnefo/cms.conf"
741
    replace = {
742
        "ACCOUNTS": env.env.accounts.fqdn,
743
        }
744
    custom = customize_settings_from_tmpl(tmpl, replace)
745
    put(custom, tmpl, mode=0644)
746
    try_run("/etc/init.d/gunicorn restart")
747

    
748
    cmd = """
749
    snf-manage syncdb
750
    snf-manage migrate --delete-ghost-migrations
751
    """.format(env.env.domain)
752
    try_run(cmd)
753

    
754

    
755
def setup_nfs_dirs():
756
    debug(env.host, " * Creating NFS mount point for pithos and ganeti...")
757
    cmd = """
758
    mkdir -p {0}
759
    cd {0}
760
    mkdir -p data
761
    chown www-data:www-data data
762
    chmod g+ws data
763
    mkdir -p /srv/okeanos
764
    """.format(env.env.pithos_dir)
765
    try_run(cmd)
766

    
767

    
768
@roles("nodes")
769
def setup_nfs_clients():
770
    if env.host == env.env.pithos.ip:
771
        return
772

    
773
    host_info = env.env.ips_info[env.host]
774
    debug(env.host, " * Mounting pithos NFS mount point...")
775
    with settings(hide("everything")):
776
        try_run("ping -c1 " + env.env.pithos.hostname)
777
    with settings(host_string=env.env.pithos.ip):
778
        update_nfs_exports(host_info.ip)
779

    
780
    install_package("nfs-common")
781
    for d in [env.env.pithos_dir, env.env.image_dir]:
782
        try_run("mkdir -p " + d)
783
        cmd = """
784
echo "{0}:{1} {1}  nfs defaults,rw,noatime,rsize=131072,\
785
wsize=131072,timeo=14,intr,noacl" >> /etc/fstab
786
""".format(env.env.pithos.ip, d)
787
        try_run(cmd)
788
        try_run("mount " + d)
789

    
790

    
791
@roles("pithos")
792
def update_nfs_exports(ip):
793
    tmpl = "/tmp/exports"
794
    replace = {
795
        "pithos_dir": env.env.pithos_dir,
796
        "image_dir": env.env.image_dir,
797
        "ip": ip,
798
    }
799
    custom = customize_settings_from_tmpl(tmpl, replace)
800
    put(custom, tmpl)
801
    try_run("cat %s >> /etc/exports" % tmpl)
802
    try_run("/etc/init.d/nfs-kernel-server restart")
803

    
804

    
805
@roles("pithos")
806
def setup_nfs_server():
807
    debug(env.host, " * Setting up NFS server for pithos...")
808
    setup_nfs_dirs()
809
    install_package("nfs-kernel-server")
810

    
811

    
812
@roles("pithos")
813
def setup_pithos():
814
    debug(env.host, "Setting up snf-pithos-app...")
815
    with settings(hide("everything")):
816
        try_run("ping -c1 accounts." + env.env.domain)
817
        try_run("ping -c1 " + env.env.db.ip)
818
    setup_gunicorn()
819
    setup_apache()
820
    setup_webproject()
821

    
822
    with settings(host_string=env.env.accounts.ip):
823
        service_id, service_token = get_service_details("pithos")
824

    
825
    install_package("kamaki")
826
    install_package("snf-pithos-backend")
827
    install_package("snf-pithos-app")
828
    tmpl = "/etc/synnefo/pithos.conf"
829
    replace = {
830
        "ACCOUNTS": env.env.accounts.fqdn,
831
        "PITHOS": env.env.pithos.fqdn,
832
        "db_node": env.env.db.ip,
833
        "synnefo_user": env.env.synnefo_user,
834
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
835
        "pithos_dir": env.env.pithos_dir,
836
        "PITHOS_SERVICE_TOKEN": service_token,
837
        "proxy": env.env.pithos.hostname == env.env.accounts.hostname
838
        }
839
    custom = customize_settings_from_tmpl(tmpl, replace)
840
    put(custom, tmpl, mode=0644)
841
    try_run("/etc/init.d/gunicorn restart")
842

    
843
    install_package("snf-pithos-webclient")
844
    tmpl = "/etc/synnefo/webclient.conf"
845
    replace = {
846
        "ACCOUNTS": env.env.accounts.fqdn,
847
        "PITHOS_UI_CLOUDBAR_ACTIVE_SERVICE": service_id,
848
        }
849
    custom = customize_settings_from_tmpl(tmpl, replace)
850
    put(custom, tmpl, mode=0644)
851

    
852
    try_run("/etc/init.d/gunicorn restart")
853
    #TOFIX: the previous command lets pithos-backend create blocks and maps
854
    #       with root owner
855
    try_run("chown -R www-data:www-data %s/data " % env.env.pithos_dir)
856
    #try_run("pithos-migrate stamp 4c8ccdc58192")
857
    #try_run("pithos-migrate upgrade head")
858

    
859

    
860
@roles("ganeti")
861
def setup_ganeti():
862
    debug(env.host, "Setting up snf-ganeti...")
863
    node_info = env.env.ips_info[env.host]
864
    with settings(hide("everything")):
865
        #if env.enable_lvm:
866
        #    try_run("vgs " + env.env.vg)
867
        try_run("getent hosts " + env.env.cluster.fqdn)
868
        try_run("getent hosts %s | grep -v ^127" % env.host)
869
        try_run("hostname -f | grep " + node_info.fqdn)
870
        #try_run("ip link show " + env.env.common_bridge)
871
        #try_run("ip link show " + env.env.common_bridge)
872
        #try_run("apt-get update")
873
    install_package("qemu-kvm")
874
    install_package("python-bitarray")
875
    install_package("ganeti-htools")
876
    install_package("snf-ganeti")
877
    try_run("mkdir -p /srv/ganeti/file-storage/")
878
    cmd = """
879
cat <<EOF > /etc/ganeti/file-storage-paths
880
/srv/ganeti/file-storage
881
/srv/ganeti/shared-file-storage
882
EOF
883
"""
884
    try_run(cmd)
885

    
886

    
887
@roles("master")
888
def add_rapi_user():
889
    debug(env.host, " * Adding RAPI user to Ganeti backend...")
890
    cmd = """
891
    echo -n "{0}:Ganeti Remote API:{1}" | openssl md5
892
    """.format(env.env.synnefo_user, env.env.synnefo_rapi_passwd)
893
    result = try_run(cmd)
894
    if result.startswith("(stdin)= "):
895
        result = result.split("(stdin)= ")[1]
896
    cmd = """
897
    echo "{0} {1}{2} write" >> /var/lib/ganeti/rapi/users
898
    """.format(env.env.synnefo_user, '{ha1}', result)
899
    try_run(cmd)
900
    try_run("/etc/init.d/ganeti restart")
901

    
902

    
903
@roles("master")
904
def add_nodes():
905
    nodes = env.env.cluster_nodes.split(",")
906
    nodes.remove(env.env.master_node)
907
    debug(env.host, " * Adding nodes to Ganeti backend...")
908
    for n in nodes:
909
        add_node(n)
910

    
911

    
912
@roles("master")
913
def add_node(node):
914
    node_info = env.env.nodes_info[node]
915
    debug(env.host, " * Adding node %s to Ganeti backend..." % node_info.fqdn)
916
    cmd = "gnt-node add --no-ssh-key-check --master-capable=yes " + \
917
          "--vm-capable=yes " + node_info.fqdn
918
    try_run(cmd)
919

    
920

    
921
@roles("ganeti")
922
def enable_drbd():
923
    if env.enable_drbd:
924
        debug(env.host, " * Enabling DRBD...")
925
        try_run("modprobe drbd minor_count=255 usermode_helper=/bin/true")
926
        try_run("echo drbd minor_count=255 usermode_helper=/bin/true " +
927
                ">> /etc/modules")
928

    
929

    
930
@roles("master")
931
def setup_drbd_dparams():
932
    if env.enable_drbd:
933
        debug(env.host,
934
              " * Twicking drbd related disk parameters in Ganeti...")
935
        cmd = """
936
        gnt-cluster modify --disk-parameters=drbd:metavg={0}
937
        gnt-group modify --disk-parameters=drbd:metavg={0} default
938
        """.format(env.env.vg)
939
        try_run(cmd)
940

    
941

    
942
@roles("master")
943
def enable_lvm():
944
    if env.enable_lvm:
945
        debug(env.host, " * Enabling LVM...")
946
        cmd = """
947
        gnt-cluster modify --vg-name={0}
948
        """.format(env.env.vg)
949
        try_run(cmd)
950
    else:
951
        debug(env.host, " * Disabling LVM...")
952
        try_run("gnt-cluster modify --no-lvm-storage")
953

    
954

    
955
@roles("master")
956
def destroy_cluster():
957
    debug(env.host, " * Destroying Ganeti cluster...")
958
    #TODO: remove instances first
959
    allnodes = env.env.cluster_hostnames[:]
960
    allnodes.remove(env.host)
961
    for n in allnodes:
962
        host_info = env.env.ips_info[env.host]
963
        debug(env.host, " * Removing node %s..." % n)
964
        cmd = "gnt-node remove  " + host_info.fqdn
965
        try_run(cmd)
966
    try_run("gnt-cluster destroy --yes-do-it")
967

    
968

    
969
@roles("master")
970
def init_cluster():
971
    debug(env.host, " * Initializing Ganeti backend...")
972
    # extra = ""
973
    # if env.enable_lvm:
974
    #     extra += " --vg-name={0} ".format(env.env.vg)
975
    # else:
976
    #     extra += " --no-lvm-storage "
977
    # if not env.enable_drbd:
978
    #     extra += " --no-drbd-storage "
979
    extra = " --no-lvm-storage --no-drbd-storage "
980
    cmd = """
981
    gnt-cluster init --enabled-hypervisors=kvm \
982
        {0} \
983
        --nic-parameters link={1},mode=bridged \
984
        --master-netdev {2} \
985
        --default-iallocator hail \
986
        --hypervisor-parameters kvm:kernel_path=,vnc_bind_address=0.0.0.0 \
987
        --no-ssh-init --no-etc-hosts \
988
        {3}
989
    """.format(extra, env.env.common_bridge,
990
               env.env.cluster_netdev, env.env.cluster.fqdn)
991
    try_run(cmd)
992

    
993

    
994
@roles("ganeti")
995
def debootstrap():
996
    install_package("ganeti-instance-debootstrap")
997

    
998

    
999
@roles("ganeti")
1000
def setup_image_host():
1001
    debug(env.host, "Setting up snf-image...")
1002
    install_package("snf-pithos-backend")
1003
    install_package("snf-image")
1004
    try_run("mkdir -p %s" % env.env.image_dir)
1005
    tmpl = "/etc/default/snf-image"
1006
    replace = {
1007
        "synnefo_user": env.env.synnefo_user,
1008
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
1009
        "pithos_dir": env.env.pithos_dir,
1010
        "db_node": env.env.db.ip,
1011
    }
1012
    custom = customize_settings_from_tmpl(tmpl, replace)
1013
    put(custom, tmpl)
1014

    
1015

    
1016
@roles("ganeti")
1017
def setup_image_helper():
1018
    debug(env.host, " * Updating helper image...")
1019
    cmd = """
1020
    snf-image-update-helper -y
1021
    """
1022
    try_run(cmd)
1023

    
1024

    
1025
@roles("ganeti")
1026
def setup_gtools():
1027
    debug(env.host, " * Setting up snf-cyclades-gtools...")
1028
    with settings(hide("everything")):
1029
        try_run("ping -c1 " + env.env.mq.ip)
1030
    setup_common()
1031
    install_package("snf-cyclades-gtools")
1032
    tmpl = "/etc/synnefo/gtools.conf"
1033
    replace = {
1034
        "synnefo_user": env.env.synnefo_user,
1035
        "synnefo_rabbitmq_passwd": env.env.synnefo_rabbitmq_passwd,
1036
        "mq_node": env.env.mq.ip,
1037
    }
1038
    custom = customize_settings_from_tmpl(tmpl, replace)
1039
    put(custom, tmpl)
1040

    
1041
    cmd = """
1042
    sed -i 's/false/true/' /etc/default/snf-ganeti-eventd
1043
    /etc/init.d/snf-ganeti-eventd start
1044
    """
1045
    try_run(cmd)
1046

    
1047

    
1048
@roles("ganeti")
1049
def setup_iptables():
1050
    debug(env.host, " * Setting up iptables to mangle DHCP requests...")
1051
    cmd = """
1052
    iptables -t mangle -A PREROUTING -i br+ -p udp -m udp --dport 67 \
1053
            -j NFQUEUE --queue-num 42
1054
    iptables -t mangle -A PREROUTING -i tap+ -p udp -m udp --dport 67 \
1055
            -j NFQUEUE --queue-num 42
1056
    iptables -t mangle -A PREROUTING -i prv+ -p udp -m udp --dport 67 \
1057
            -j NFQUEUE --queue-num 42
1058

1059
    ip6tables -t mangle -A PREROUTING -i br+ -p ipv6-icmp -m icmp6 \
1060
            --icmpv6-type 133 -j NFQUEUE --queue-num 43
1061
    ip6tables -t mangle -A PREROUTING -i br+ -p ipv6-icmp -m icmp6 \
1062
            --icmpv6-type 135 -j NFQUEUE --queue-num 44
1063
    """
1064
    try_run(cmd)
1065

    
1066

    
1067
@roles("ganeti")
1068
def setup_network():
1069
    debug(env.host,
1070
          "Setting up networking for Ganeti instances (nfdhcpd, etc.)...")
1071
    install_package("nfqueue-bindings-python")
1072
    install_package("nfdhcpd")
1073
    tmpl = "/etc/nfdhcpd/nfdhcpd.conf"
1074
    replace = {
1075
        "ns_node_ip": env.env.ns.ip
1076
    }
1077
    custom = customize_settings_from_tmpl(tmpl, replace)
1078
    put(custom, tmpl)
1079
    try_run("/etc/init.d/nfdhcpd restart")
1080

    
1081
    install_package("snf-network")
1082
    cmd = """
1083
sed -i 's/MAC_MASK.*/MAC_MASK = ff:ff:f0:00:00:00/' /etc/default/snf-network
1084
    """
1085
    try_run(cmd)
1086

    
1087

    
1088
@roles("router")
1089
def setup_router():
1090
    debug(env.host, " * Setting up internal router for NAT...")
1091
    cmd = """
1092
    echo 1 > /proc/sys/net/ipv4/ip_forward
1093
    iptables -t nat -A POSTROUTING -s {0} -o {3} -j MASQUERADE
1094
    ip addr add {1} dev {2}
1095
    ip route add {0} dev {2} src {1}
1096
    """.format(env.env.synnefo_public_network_subnet,
1097
               env.env.synnefo_public_network_gateway,
1098
               env.env.common_bridge, env.env.public_iface)
1099
    try_run(cmd)
1100

    
1101

    
1102
@roles("cyclades")
1103
def cyclades_loaddata():
1104
    debug(env.host, " * Loading initial data for cyclades...")
1105
    try_run("snf-manage flavor-create %s %s %s %s" % (env.env.flavor_cpu,
1106
                                                      env.env.flavor_ram,
1107
                                                      env.env.flavor_disk,
1108
                                                      env.env.flavor_storage))
1109
    #run("snf-manage loaddata flavors")
1110

    
1111

    
1112
@roles("cyclades")
1113
def setup_cyclades():
1114
    debug(env.host, "Setting up snf-cyclades-app...")
1115
    with settings(hide("everything")):
1116
        try_run("ping -c1 accounts." + env.env.domain)
1117
        try_run("ping -c1 " + env.env.db.ip)
1118
        try_run("ping -c1 " + env.env.mq.ip)
1119
    setup_gunicorn()
1120
    setup_apache()
1121
    setup_webproject()
1122
    install_package("memcached")
1123
    install_package("python-memcache")
1124
    install_package("snf-pithos-backend")
1125
    install_package("kamaki")
1126
    install_package("snf-cyclades-app")
1127
    install_package("python-django-south")
1128
    tmpl = "/etc/synnefo/cyclades.conf"
1129

    
1130
    with settings(host_string=env.env.accounts.ip):
1131
        service_id, service_token = get_service_details("cyclades")
1132

    
1133
    replace = {
1134
        "ACCOUNTS": env.env.accounts.fqdn,
1135
        "CYCLADES": env.env.cyclades.fqdn,
1136
        "mq_node": env.env.mq.ip,
1137
        "db_node": env.env.db.ip,
1138
        "synnefo_user": env.env.synnefo_user,
1139
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
1140
        "synnefo_rabbitmq_passwd": env.env.synnefo_rabbitmq_passwd,
1141
        "pithos_dir": env.env.pithos_dir,
1142
        "common_bridge": env.env.common_bridge,
1143
        "HOST": env.env.cyclades.ip,
1144
        "domain": env.env.domain,
1145
        "CYCLADES_SERVICE_TOKEN": service_token,
1146
        "proxy": env.env.cyclades.hostname == env.env.accounts.hostname
1147
        }
1148
    custom = customize_settings_from_tmpl(tmpl, replace)
1149
    put(custom, tmpl, mode=0644)
1150
    try_run("/etc/init.d/gunicorn restart")
1151

    
1152
    cmd = """
1153
    sed -i 's/false/true/' /etc/default/snf-dispatcher
1154
    /etc/init.d/snf-dispatcher start
1155
    """
1156
    try_run(cmd)
1157

    
1158
    try_run("snf-manage syncdb")
1159
    try_run("snf-manage migrate --delete-ghost-migrations")
1160

    
1161

    
1162
@roles("cyclades")
1163
def get_backend_id(cluster_name="ganeti1.synnefo.deploy.local"):
1164
    backend_id = try_run("snf-manage backend-list 2>/dev/null " +
1165
                         "| grep %s | awk '{print $1}'" % cluster_name)
1166
    return backend_id
1167

    
1168

    
1169
@roles("cyclades")
1170
def add_backend():
1171
    debug(env.host,
1172
          "adding %s ganeti backend to cyclades..." % env.env.cluster.fqdn)
1173
    with settings(hide("everything")):
1174
        try_run("ping -c1 " + env.env.cluster.fqdn)
1175
    cmd = """
1176
    snf-manage backend-add --clustername={0} --user={1} --pass={2}
1177
    """.format(env.env.cluster.fqdn, env.env.synnefo_user,
1178
               env.env.synnefo_rapi_passwd)
1179
    try_run(cmd)
1180
    backend_id = get_backend_id(env.env.cluster.fqdn)
1181
    try_run("snf-manage backend-modify --drained=False " + backend_id)
1182

    
1183

    
1184
@roles("cyclades")
1185
def pin_user_to_backend(user_email):
1186
    backend_id = get_backend_id(env.env.cluster.fqdn)
1187
    # pin user to backend
1188
    cmd = """
1189
cat <<EOF >> /etc/synnefo/cyclades.conf
1190

1191
BACKEND_PER_USER = {
1192
  '{0}': {1},
1193
}
1194

1195
EOF
1196
/etc/init.d/gunicorn restart
1197
""".format(user_email, backend_id)
1198
    try_run(cmd)
1199

    
1200

    
1201
@roles("cyclades")
1202
def add_pools():
1203
    debug(env.host,
1204
          " * Creating pools of resources (brigdes, mac prefixes) " +
1205
          "in cyclades...")
1206
    try_run("snf-manage pool-create --type=mac-prefix " +
1207
            "--base=aa:00:0 --size=65536")
1208
    try_run("snf-manage pool-create --type=bridge --base=prv --size=20")
1209

    
1210

    
1211
@roles("accounts", "cyclades", "pithos")
1212
def export_services():
1213
    debug(env.host, " * Exporting services...")
1214
    host = env.host
1215
    services = []
1216
    if host == env.env.cyclades.ip:
1217
        services.append("cyclades")
1218
    if host == env.env.pithos.ip:
1219
        services.append("pithos")
1220
    if host == env.env.accounts.ip:
1221
        services.append("astakos")
1222
    for service in services:
1223
        filename = "%s_services.json" % service
1224
        cmd = "snf-manage service-export-%s > %s" % (service, filename)
1225
        run(cmd)
1226
        get(filename, filename+".local")
1227

    
1228

    
1229
@roles("accounts")
1230
def import_services():
1231
    debug(env.host, " * Registering services to astakos...")
1232
    for service in ["cyclades", "pithos", "astakos"]:
1233
        filename = "%s_services.json" % service
1234
        put(filename + ".local", filename)
1235
        cmd = "snf-manage service-import --json=%s" % filename
1236
        run(cmd)
1237

    
1238
    debug(env.host, " * Setting default quota...")
1239
    cmd = """
1240
    snf-manage resource-modify --limit 40G pithos.diskspace
1241
    snf-manage resource-modify --limit 2 astakos.pending_app
1242
    snf-manage resource-modify --limit 4 cyclades.vm
1243
    snf-manage resource-modify --limit 40G cyclades.disk
1244
    snf-manage resource-modify --limit 16G cyclades.ram
1245
    snf-manage resource-modify --limit 8G cyclades.active_ram
1246
    snf-manage resource-modify --limit 32 cyclades.cpu
1247
    snf-manage resource-modify --limit 16 cyclades.active_cpu
1248
    snf-manage resource-modify --limit 4 cyclades.network.private
1249
    """
1250
    try_run(cmd)
1251

    
1252

    
1253
@roles("cyclades")
1254
def add_network():
1255
    debug(env.host, " * Adding public network in cyclades...")
1256
    backend_id = get_backend_id(env.env.cluster.fqdn)
1257
    cmd = """
1258
    snf-manage network-create --subnet={0} --gateway={1} \
1259
            --public --dhcp --flavor={2} --mode=bridged --link={3} \
1260
            --name=Internet --backend-id={4}
1261
    """.format(env.env.synnefo_public_network_subnet,
1262
               env.env.synnefo_public_network_gateway,
1263
               env.env.synnefo_public_network_type,
1264
               env.env.common_bridge, backend_id)
1265
    try_run(cmd)
1266

    
1267

    
1268
@roles("cyclades")
1269
def setup_vncauthproxy():
1270
    debug(env.host, " * Setting up vncauthproxy...")
1271
    install_package("snf-vncauthproxy")
1272
    cmd = """
1273
    echo CHUID="www-data:nogroup" >> /etc/default/vncauthproxy
1274
    rm /var/log/vncauthproxy/vncauthproxy.log
1275
    """
1276
    try_run(cmd)
1277
    try_run("/etc/init.d/vncauthproxy restart")
1278

    
1279

    
1280
@roles("client")
1281
def setup_kamaki():
1282
    debug(env.host, "Setting up kamaki client...")
1283
    with settings(hide("everything")):
1284
        try_run("ping -c1 accounts." + env.env.domain)
1285
        try_run("ping -c1 cyclades." + env.env.domain)
1286
        try_run("ping -c1 pithos." + env.env.domain)
1287

    
1288
    with settings(host_string=env.env.db.ip):
1289
        uid, user_auth_token, user_uuid = \
1290
            get_auth_token_from_db(env.env.user_email)
1291

    
1292
    install_package("python-progress")
1293
    install_package("kamaki")
1294
    cmd = """
1295
    kamaki config set cloud.default.url "https://{0}/astakos/identity/v2.0/"
1296
    kamaki config set cloud.default.token {1}
1297
    """.format(env.env.accounts.fqdn, user_auth_token)
1298
    try_run(cmd)
1299
    try_run("kamaki file create images")
1300

    
1301

    
1302
@roles("client")
1303
def upload_image(image="debian_base.diskdump"):
1304
    debug(env.host, " * Uploading initial image to pithos...")
1305
    image = "debian_base.diskdump"
1306
    try_run("wget {0} -O /tmp/{1}".format(env.env.debian_base_url, image))
1307
    try_run("kamaki file upload --container images /tmp/{0} {0}".format(image))
1308

    
1309

    
1310
@roles("client")
1311
def register_image(image="debian_base.diskdump"):
1312
    debug(env.host, " * Register image to plankton...")
1313
    # with settings(host_string=env.env.db.ip):
1314
    #     uid, user_auth_token, user_uuid = \
1315
    #        get_auth_token_from_db(env.env.user_email)
1316

    
1317
    image_location = "images:{0}".format(image)
1318
    cmd = """
1319
    sleep 5
1320
    kamaki image register "Debian Base" {0} --public --disk-format=diskdump \
1321
            --property OSFAMILY=linux --property ROOT_PARTITION=1 \
1322
            --property description="Debian Squeeze Base System" \
1323
            --property size=450M --property kernel=2.6.32 \
1324
            --property GUI="No GUI" --property sortorder=1 \
1325
            --property USERS=root --property OS=debian
1326
    """.format(image_location)
1327
    try_run(cmd)
1328

    
1329

    
1330
@roles("client")
1331
def setup_burnin():
1332
    debug(env.host, "Setting up burnin testing tool...")
1333
    install_package("kamaki")
1334
    install_package("snf-tools")
1335

    
1336

    
1337
@roles("pithos")
1338
def add_image_locally():
1339
    debug(env.host,
1340
          " * Getting image locally in order snf-image to use it directly..")
1341
    image = "debian_base.diskdump"
1342
    try_run("wget {0} -O {1}/{2}".format(
1343
            env.env.debian_base_url, env.env.image_dir, image))
1344

    
1345

    
1346
@roles("master")
1347
def gnt_instance_add(name="test"):
1348
    debug(env.host, " * Adding test instance to Ganeti...")
1349
    osp = """img_passwd=gamwtosecurity,\
1350
img_format=diskdump,img_id=debian_base,\
1351
img_properties='{"OSFAMILY":"linux"\,"ROOT_PARTITION":"1"}'"""
1352
    cmd = """
1353
    gnt-instance add  -o snf-image+default --os-parameters {0} \
1354
            -t plain --disk 0:size=1G --no-name-check --no-ip-check \
1355
            --net 0:ip=pool,network=test --no-install \
1356
            --hypervisor-parameters kvm:machine_version=pc-1.0 {1}
1357
    """.format(osp, name)
1358
    try_run(cmd)
1359

    
1360

    
1361
@roles("master")
1362
def gnt_network_add(name="test", subnet="10.0.0.0/26", gw="10.0.0.1",
1363
                    mode="bridged", link="br0"):
1364
    debug(env.host, " * Adding test network to Ganeti...")
1365
    cmd = """
1366
    gnt-network add --network={1} --gateway={2} {0}
1367
    gnt-network connect {0} {3} {4}
1368
    """.format(name, subnet, gw, mode, link)
1369
    try_run(cmd)
1370

    
1371

    
1372
@roles("ips")
1373
def test():
1374
    debug(env.host, "Testing...")
1375
    try_run("hostname && date")