Statistics
| Branch: | Tag: | Revision:

root / snf-deploy / snfdeploy / fabfile.py @ 5a390037

History | View | Annotate | Download (41.4 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
        "proxy": env.env.pithos.hostname == env.env.accounts.hostname
854
        }
855
    custom = customize_settings_from_tmpl(tmpl, replace)
856
    try_put(custom, tmpl, mode=0644)
857
    try_run("/etc/init.d/gunicorn restart")
858

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

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

    
875

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

    
902

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

    
918

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

    
927

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

    
936

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

    
946

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

    
958

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

    
971

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

    
985

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

    
1010

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

    
1015

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

    
1033

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

    
1042

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

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

    
1065

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

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

    
1084

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

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

    
1105

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

    
1119

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

    
1129

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

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

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

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

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

    
1179

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

    
1186

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

    
1201

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

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

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

    
1218

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

    
1228

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

    
1246

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

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

    
1271

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

    
1286

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

    
1298

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

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

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

    
1320

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

    
1328

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

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

    
1348

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

    
1355

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

    
1364

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

    
1379

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

    
1390

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