fabfile.py 37.7 KB
Newer Older
Dimitris Aragiorgis's avatar
Dimitris Aragiorgis committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm
from random import choice
from fabric.operations import run, put
import re
import shutil, os
from functools import wraps
import imp
import ConfigParser
import sys
import tempfile
import ast
from snfdeploy.lib import *
from snfdeploy import massedit


def setup_env(confdir="conf", packages="packages",
19
              templates="files", cluster_name="ganeti1", autoconf=False, disable_colors=False):
Dimitris Aragiorgis's avatar
Dimitris Aragiorgis committed
20
21
22
23
24
    print("Loading configuration for synnefo...")
    print(" * Using config files under %s..." % confdir)
    print(" * Using %s and %s for packages and templates accordingly..." % (packages, templates))

    autoconf = ast.literal_eval(autoconf)
25
    disable_colors = ast.literal_eval(disable_colors)
Dimitris Aragiorgis's avatar
Dimitris Aragiorgis committed
26
27
28
29
30
31
32
33
    conf = Conf.configure(confdir=confdir, cluster_name=cluster_name, autoconf=autoconf)
    env.env = Env(conf)

    env.local = autoconf
    env.password = env.env.password
    env.user = env.env.user
    env.shell = "/bin/bash -c"

34
35
36
    if disable_colors:
        disable_color()

Dimitris Aragiorgis's avatar
Dimitris Aragiorgis committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
    if env.env.cms.hostname in [env.env.accounts.hostname, env.env.cyclades.hostname, env.env.pithos.hostname]:
      env.cms_pass = True
    else:
      env.cms_pass = False

    if env.env.accounts.hostname in [env.env.cyclades.hostname, env.env.pithos.hostname]:
      env.csrf_disable = True
    else:
      env.csrf_disable = False


    env.roledefs = {
        "nodes": env.env.ips,
        "ips": env.env.ips,
        "accounts": [env.env.accounts.ip],
        "cyclades": [env.env.cyclades.ip],
        "pithos": [env.env.pithos.ip],
        "cms": [env.env.cms.ip],
        "mq": [env.env.mq.ip],
        "db": [env.env.db.ip],
        "ns": [env.env.ns.ip],
        "client": [env.env.client.ip],
        "router": [env.env.router.ip],
    }

    env.enable_lvm = False
    env.enable_drbd = False
    if ast.literal_eval(env.env.create_extra_disk) and env.env.extra_disk:
        env.enable_lvm = True
        env.enable_drbd = True

    env.roledefs.update({
        "ganeti": env.env.cluster_ips,
        "master": [env.env.master.ip],
    })


def install_package(package):
    debug(env.host, " * Installing package %s..." % package)
    APT_GET = "export DEBIAN_FRONTEND=noninteractive ;apt-get install -y --force-yes "

    if ast.literal_eval(env.env.use_local_packages):
        with settings(warn_only=True):
            deb = local("ls %s/%s*deb" % (env.env.packages, package))
            if deb:
                debug(env.host, " * Package %s found in %s..." % (package, env.env.packages))
                put(deb, "/tmp/")
                try_run("dpkg -i /tmp/%s*deb || " % package + APT_GET + "-f")
                try_run("rm /tmp/%s*deb" % package)
                return

    info = getattr(env.env, package)
    if info in ["stable", "squeeze-backports", "testing", "unstable"]:
        APT_GET += " -t %s %s " % (info, package)
    elif info:
        APT_GET += " %s=%s " % (package, info)
    else:
        APT_GET += package

    try_run(APT_GET)

    return


@roles("ns")
def update_ns_for_ganeti():
    debug(env.host, "Updating name server entries for backend %s..." % env.env.cluster.fqdn)
    update_arecord(env.env.cluster)
    update_ptrrecord(env.env.cluster)
    try_run("/etc/init.d/bind9 restart")


@roles("ns")
def update_ns_for_node(node):
    info = env.env.nodes_info.get(node)
    update_arecord(info)
    update_ptrrecord(info)
    try_run("/etc/init.d/bind9 restart")


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


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


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

@roles("nodes")
def apt_get_update():
    debug(env.host, "apt-get update....")
    try_run("apt-get update")

@roles("ns")
def setup_ns():
    debug(env.host, "Setting up name server..")
    #WARNING: this should be remove after we are done
    # because gevent does pick randomly nameservers and google does
    # not know our setup!!!!!
    apt_get_update()
    install_package("bind9")
    tmpl = "/etc/bind/named.conf.local"
    replace = {
      "domain": env.env.domain,
      }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)

    try_run("mkdir -p /etc/bind/zones")
    tmpl = "/etc/bind/zones/example.com"
    replace = {
      "domain": env.env.domain,
      "ns_node_ip": env.env.ns.ip,
      }
    custom = customize_settings_from_tmpl(tmpl, replace)
    remote = "/etc/bind/zones/" + env.env.domain
    put(custom, remote)

    try_run("mkdir -p /etc/bind/rev")
    tmpl = "/etc/bind/rev/synnefo.in-addr.arpa.zone"
    replace = {
      "domain": env.env.domain,
      }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)

    tmpl = "/etc/bind/named.conf.options"
    replace = {
      "NODE_IPS": ";".join(env.env.ips),
      }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)

    for role, info in env.env.roles.iteritems():
        if role == "ns":
            continue
        update_cnamerecord(info)
    for node, info in env.env.nodes_info.iteritems():
        update_arecord(info)
        update_ptrrecord(info)

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


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

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

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

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


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


@roles("ips")
def add_keys():
    debug(env.host, "Adding rsa/dsa keys..")
    try_run("mkdir -p /root/.ssh")
    cmd = """
for f in $(ls /root/.ssh/*); do
  cp $f $f.bak
done
    """
    try_run(cmd)
    files = ["authorized_keys", "id_dsa", "id_dsa.pub",
             "id_rsa", "id_rsa.pub"]
    for f in files:
      tmpl = "/root/.ssh/" + f
      replace = {}
      custom = customize_settings_from_tmpl(tmpl, replace)
      put(custom, tmpl)

    cmd = """
if [ -e /root/.ssh/authorized_keys.bak ]; then
  cat /root/.ssh/authorized_keys.bak >> /root/.ssh/authorized_keys
fi
    """
    debug(env.host, "Updating exising authorized keys..")
    try_run(cmd)

@roles("ips")
def setup_resolv_conf():
    debug(env.host, "Tweak /etc/resolv.conf...")
    try_run("/etc/init.d/network-manager stop")
    tmpl = "/etc/dhcp/dhclient-enter-hooks.d/nodnsupdate"
    replace = {}
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)
    try_run("cp /etc/resolv.conf /etc/resolv.conf.bak")
    tmpl = "/etc/resolv.conf"
    replace = {
      "domain": env.env.domain,
      "ns_node_ip": env.env.ns.ip,
      }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    try_run("chattr +i /etc/resolv.conf")


@roles("ips")
def setup_hosts():
    debug(env.host, "Tweaking /etc/hosts and ssh_config files...")
    try_run("echo StrictHostKeyChecking no >> /etc/ssh/ssh_config")
    cmd = " sed -i 's/^127.*/127.0.0.1 localhost/g' /etc/hosts "
    try_run(cmd)


def try_run(cmd):
    try:
      if env.local:
        return local(cmd, capture=True)
      else:
        return run(cmd)
    except:
      debug(env.host, "WARNING: command failed. Continuing anyway...")

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


def connect_bridges():
    debug(env.host, " * Connecting bridges...")
    cmd = """
    brctl addif {0} {1}
    """.format(env.env.common_bridge, env.env.public_iface)
    #try_run(cmd)


@roles("ganeti")
def setup_net_infra():
    debug(env.host, "Setup networking infrastracture..")
    create_bridges()
    connect_bridges()


@roles("ganeti")
def setup_lvm():
    debug(env.host, "create volume group %s for ganeti.." % env.env.vg)
    if env.enable_lvm:
        install_package("lvm2")
        cmd = """
        pvcreate {0}
        vgcreate {1} {0}
        """.format(env.env.extra_disk, env.env.vg)
        try_run(cmd)


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

    return custom


@roles("nodes")
def setup_apt():
    debug(env.host, "Setting up apt sources...")
    install_package("curl")
    cmd = """
    echo 'APT::Install-Suggests "false";' >> /etc/apt/apt.conf
    curl -k https://dev.grnet.gr/files/apt-grnetdev.pub | apt-key add -
    """
    try_run(cmd)
    tmpl = "/etc/apt/sources.list.d/okeanos.list"
    replace = {}
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    apt_get_update()


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


def setup_gunicorn():
    debug(env.host, " * Setting up gunicorn...")
    install_package("gunicorn")
    tmpl = "/etc/gunicorn.d/synnefo"
    replace = {}
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)
    try_run("/etc/init.d/gunicorn restart")


def setup_apache():
    debug(env.host, " * Setting up apache2...")
    host_info = env.env.ips_info[env.host]
    install_package("apache2")
    tmpl = "/etc/apache2/sites-available/synnefo"
    replace = {
        "HOST": host_info.fqdn,
    }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    tmpl = "/etc/apache2/sites-available/synnefo-ssl"
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    cmd = """
    a2enmod ssl
    a2enmod rewrite
    a2dissite default
    a2ensite synnefo
    a2ensite synnefo-ssl
    a2enmod headers
    a2enmod proxy_http
    a2dismod autoindex
    """
    try_run(cmd)
    try_run("/etc/init.d/apache2 restart")


@roles("mq")
def setup_mq():
    debug(env.host, "Setting up RabbitMQ...")
    install_package("rabbitmq-server")
    cmd = """
    rabbitmqctl add_user {0} {1}
    rabbitmqctl set_permissions {0} ".*" ".*" ".*"
    rabbitmqctl delete_user guest
    rabbitmqctl set_user_tags {0} administrator
    """.format(env.env.synnefo_user, env.env.synnefo_rabbitmq_passwd)
    try_run(cmd)
    try_run("/etc/init.d/rabbitmq-server restart")


@roles("db")
def allow_access_in_db(ip):
    cmd = """
    echo host all all {0}/32 md5 >> /etc/postgresql/8.4/main/pg_hba.conf
    """.format(ip)
    try_run(cmd)
    try_run("/etc/init.d/postgresql restart")

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

    tmpl = "/tmp/db-init.psql"
    replace = {
        "synnefo_user": env.env.synnefo_user,
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
        }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    cmd = 'su - postgres -c "psql -w -f %s" ' % tmpl
    try_run(cmd)
    cmd = """
    echo "listen_addresses = '*'" >> /etc/postgresql/8.4/main/postgresql.conf
    """
    try_run(cmd)

    try_run("/etc/init.d/postgresql restart")


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


def setup_webproject():
    debug(env.host, " * Setting up snf-webproject...")
    with settings(hide("everything")):
        try_run("ping -c1 " + env.env.db.ip)
    setup_common()
    install_package("snf-webproject")
    install_package("python-psycopg2")
    install_package("python-gevent")
    tmpl = "/etc/synnefo/webproject.conf"
    replace = {
        "synnefo_user": env.env.synnefo_user,
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
        "db_node": env.env.db.ip,
        "domain": env.env.domain,
    }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)
    with settings(host_string=env.env.db.hostname):
        host_info = env.env.ips_info[env.host]
        allow_access_in_db(host_info.ip)
    try_run("/etc/init.d/gunicorn restart")


def setup_common():
    debug(env.host, " * Setting up snf-common...")
    host_info = env.env.ips_info[env.host]
    install_package("python-objpool")
    install_package("snf-common")
    install_package("python-astakosclient")
    install_package("snf-django-lib")
    install_package("snf-branding")
    tmpl = "/etc/synnefo/common.conf"
    replace = {
        #FIXME:
        "EMAIL_SUBJECT_PREFIX": env.host,
        "domain": env.env.domain,
        "HOST": host_info.fqdn,
    }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)
    try_run("/etc/init.d/gunicorn restart")

@roles("accounts")
def astakos_loaddata():
    debug(env.host, " * Loading initial data to astakos...")
    cmd = """
    snf-manage loaddata groups
    """
    try_run(cmd)


@roles("accounts")
def astakos_register_services():
    debug(env.host, " * Register services in astakos...")
    cmd = """
    snf-manage component-add "home" https://{0} home-icon.png
    snf-manage component-add "cyclades" https://{1}/cyclades/ui/
    snf-manage component-add "pithos" https://{2}/pithos/ui/
    snf-manage component-add "astakos" https://{3}/astakos/ui/
    """.format(env.env.cms.fqdn, env.env.cyclades.fqdn, env.env.pithos.fqdn, env.env.accounts.fqdn)
    try_run(cmd)
    import_service("astakos")
    import_service("pithos")
    import_service("cyclades")
    tmpl = "/tmp/resources.json"
    replace = {}
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    try_run("snf-manage resource-import --json %s" % tmpl)
    cmd = """
    snf-manage resource-modify --limit 40G pithos.diskspace
    snf-manage resource-modify --limit 2 astakos.pending_app
    snf-manage resource-modify --limit 4 cyclades.vm
    snf-manage resource-modify --limit 40G cyclades.disk
    snf-manage resource-modify --limit 8G cyclades.ram
    snf-manage resource-modify --limit 16 cyclades.cpu
    snf-manage resource-modify --limit 4 cyclades.network.private
    """
    try_run(cmd)


@roles("accounts")
def add_user():
    debug(env.host, " * adding user %s to astakos..." % env.env.user_email)
    email=env.env.user_email
    name=env.env.user_name
    lastname=env.env.user_lastname
    passwd=env.env.user_passwd
    cmd = """
    snf-manage user-add {0} {1} {2}
    """.format(email, name, lastname)
    try_run(cmd)
    with settings(host_string=env.env.db.hostname):
        uid, user_auth_token, user_uuid = get_auth_token_from_db(email)
    cmd = """
    snf-manage user-modify --password {0} {1}
    """.format(passwd, uid)
    try_run(cmd)


@roles("accounts")
def activate_user(user_email=None):
    if not user_email:
      user_email = env.env.user_email
    debug(env.host, " * Activate user %s..." % user_email)
    with settings(host_string=env.env.db.hostname):
        uid, user_auth_token, user_uuid = get_auth_token_from_db(user_email)

    cmd = """
    snf-manage user-modify --verify {0}
    snf-manage user-modify --accept {0}
    """.format(uid)
    try_run(cmd)

@roles("accounts")
def setup_astakos():
    debug(env.host, "Setting up snf-astakos-app...")
    setup_gunicorn()
    setup_apache()
    setup_webproject()
    install_package("python-django-south")
    install_package("snf-astakos-app")
    install_package("kamaki")

    tmpl = "/etc/synnefo/astakos.conf"
    replace = {
      "ACCOUNTS": env.env.accounts.fqdn,
      "domain": env.env.domain,
      "CYCLADES": env.env.cyclades.fqdn,
      "PITHOS": env.env.pithos.fqdn,
    }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)
    if env.csrf_disable:
      cmd = """
cat <<EOF >> /etc/synnefo/astakos.conf
try:
  MIDDLEWARE_CLASSES.remove('django.middleware.csrf.CsrfViewMiddleware')
except:
  pass
EOF
"""
      try_run(cmd)

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

    cmd = """
    snf-manage syncdb --noinput
    snf-manage migrate im --delete-ghost-migrations
    snf-manage migrate quotaholder_app
    """
    try_run(cmd)

def import_service(service):
    tmpl = "/tmp/%s.json" % service
    replace = {
      "DOMAIN": env.env.domain,
      }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    try_run("snf-manage service-import --json %s" % tmpl)

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


@roles("db")
def get_auth_token_from_db(user_email=None):
    if not user_email:
        user_email=env.env.user_email
    debug(env.host, " * Getting authentication token and uuid for user %s..." % user_email)
    cmd = """
    echo "select id, auth_token, uuid, email from auth_user, im_astakosuser where auth_user.id = im_astakosuser.user_ptr_id and auth_user.email = '{0}';" > /tmp/psqlcmd
    su - postgres -c  "psql -w -d snf_apps -f /tmp/psqlcmd"
    """.format(user_email)

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

    return (uid, user_auth_token, user_uuid)


@roles("cms")
def cms_loaddata():
    debug(env.host, " * Loading cms initial data...")
    if env.cms_pass:
      debug(env.host, "Aborting. Prerequisites not met.")
      return
    tmpl = "/tmp/sites.json"
    replace = {}
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)

    tmpl = "/tmp/page.json"
    replace = {}
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)

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


@roles("cms")
def setup_cms():
    debug(env.host, "Setting up cms...")
    if env.cms_pass:
      debug(env.host, "Aborting. Prerequisites not met.")
      return
    with settings(hide("everything")):
        try_run("ping -c1 accounts." + env.env.domain)
    setup_gunicorn()
    setup_apache()
    setup_webproject()
    install_package("snf-cloudcms")

    tmpl = "/etc/synnefo/cms.conf"
    replace = {
        "ACCOUNTS": env.env.accounts.fqdn,
        }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)
    try_run("/etc/init.d/gunicorn restart")


    cmd = """
    snf-manage syncdb
    snf-manage migrate --delete-ghost-migrations
    """.format(env.env.domain)
    try_run(cmd)


def setup_nfs_dirs():
    debug(env.host, " * Creating NFS mount point for pithos and ganeti...")
    cmd = """
    mkdir -p {0}
    cd {0}
    mkdir -p data
    chown www-data:www-data data
    chmod g+ws data
    mkdir -p /srv/okeanos
    """.format(env.env.pithos_dir)
    try_run(cmd)


@roles("nodes")
def setup_nfs_clients():
    if env.host == env.env.pithos.hostname:
      return

    debug(env.host, " * Mounting pithos NFS mount point...")
    with settings(hide("everything")):
        try_run("ping -c1 " + env.env.pithos.hostname)
    install_package("nfs-common")
    for d in [env.env.pithos_dir, "/srv/okeanos"]:
      try_run("mkdir -p " + d)
      cmd = """
      echo "{0}:/{1} {2}  nfs4 defaults,rw,noatime,nodiratime,intr,rsize=1048576,wsize=1048576,noacl" >> /etc/fstab
      """.format(env.env.pithos.hostname, os.path.basename(d), d)
      try_run(cmd)
      try_run("mount " + d)


@roles("pithos")
def setup_nfs_server():
    debug(env.host, " * Setting up NFS server for pithos...")
    setup_nfs_dirs()
    install_package("nfs-kernel-server")
    tmpl = "/etc/exports"
    replace = {
      "pithos_dir": env.env.pithos_dir,
      "srv": os.path.dirname(env.env.pithos_dir),
      "subnet": env.env.subnet
      }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    try_run("/etc/init.d/nfs-kernel-server restart")


@roles("pithos")
def setup_pithos():
    debug(env.host, "Setting up snf-pithos-app...")
    with settings(hide("everything")):
        try_run("ping -c1 accounts." + env.env.domain)
        try_run("ping -c1 " + env.env.db.ip)
    setup_gunicorn()
    setup_apache()
    setup_webproject()

    with settings(host_string=env.env.accounts.hostname):
        service_id, service_token = get_service_details("pithos")

    install_package("kamaki")
    install_package("snf-pithos-backend")
    install_package("snf-pithos-app")
    tmpl = "/etc/synnefo/pithos.conf"
    replace = {
        "ACCOUNTS": env.env.accounts.fqdn,
        "PITHOS": env.env.pithos.fqdn,
        "db_node": env.env.db.ip,
        "synnefo_user": env.env.synnefo_user,
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
        "pithos_dir": env.env.pithos_dir,
        "PITHOS_SERVICE_TOKEN": service_token,
        "proxy": env.env.pithos.hostname == env.env.accounts.hostname
        }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)
    try_run("/etc/init.d/gunicorn restart")

    install_package("snf-pithos-webclient")
    tmpl = "/etc/synnefo/webclient.conf"
    replace = {
        "ACCOUNTS": env.env.accounts.fqdn,
        "PITHOS_UI_CLOUDBAR_ACTIVE_SERVICE": service_id,
        }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)

    #TOFIX: this is needed in order webclient not to serve /ui url
    #       but only /pithos/ui
    if env.env.pithos.hostname == env.env.cyclades.hostname:
      tmpl = "/usr/share/pyshared/pithos_webclient/synnefo_settings.py"
      replace = {}
      custom = customize_settings_from_tmpl(tmpl, replace)
      put(custom, tmpl, mode=0644)

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


def add_wheezy():
    tmpl = "/etc/apt/sources.list.d/wheezy.list"
    replace = {}
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    apt_get_update()


def remove_wheezy():
    try_run("rm -f /etc/apt/sources.list.d/wheezy.list")
    apt_get_update()


@roles("ganeti")
def setup_ganeti():
    debug(env.host, "Setting up snf-ganeti...")
    node_info = env.env.ips_info[env.host]
    with settings(hide("everything")):
        #if env.enable_lvm:
        #    try_run("vgs " + env.env.vg)
        try_run("getent hosts " + env.env.cluster.fqdn)
        try_run("getent hosts %s | grep -v ^127" % env.host)
        try_run("hostname -f | grep " + node_info.fqdn)
        #try_run("ip link show " + env.env.common_bridge)
        #try_run("ip link show " + env.env.common_bridge)
        #try_run("apt-get update")
    install_package("qemu-kvm")
    install_package("python-bitarray")
    add_wheezy()
    install_package("ganeti-htools")
    remove_wheezy()
    install_package("snf-ganeti")
    try_run("mkdir -p /srv/ganeti/file-storage/")
    cmd = """
cat <<EOF > /etc/ganeti/file-storage-paths
/srv/ganeti/file-storage
/srv/ganeti/shared-file-storage
EOF
"""
    try_run(cmd)


@roles("master")
def add_rapi_user():
    debug(env.host, " * Adding RAPI user to Ganeti backend...")
    cmd = """
    echo -n "{0}:Ganeti Remote API:{1}" | openssl md5
    """.format(env.env.synnefo_user, env.env.synnefo_rapi_passwd)
    result = try_run(cmd)
    cmd = """
    echo "{0} {1}{2} write" >> /var/lib/ganeti/rapi/users
    """.format(env.env.synnefo_user, '{ha1}',result)
    try_run(cmd)
    try_run("/etc/init.d/ganeti restart")

@roles("master")
def add_nodes():
    nodes = env.env.cluster_nodes.split(",")
    nodes.remove(env.env.master_node)
    debug(env.host, " * Adding nodes to Ganeti backend...")
    for n in nodes:
        add_node(n)

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

@roles("ganeti")
def enable_drbd():
    if env.enable_drbd:
        debug(env.host, " * Enabling DRBD...")
        try_run("modprobe drbd minor_count=255 usermode_helper=/bin/true")
        try_run("echo drbd minor_count=255 usermode_helper=/bin/true >> /etc/modules")

@roles("master")
def setup_drbd_dparams():
    if env.enable_drbd:
        debug(env.host, " * Twicking drbd related disk parameters in Ganeti...")
        cmd = """
        gnt-cluster modify --disk-parameters=drbd:metavg={0}
        gnt-group modify --disk-parameters=drbd:metavg={0} default
        """.format(env.env.vg)
        try_run(cmd)

@roles("master")
def enable_lvm():
    if env.enable_lvm:
        debug(env.host, " * Enabling LVM...")
        cmd = """
        gnt-cluster modify --vg-name={0}
        """.format(env.env.vg)
        try_run(cmd)
    else:
        debug(env.host, " * Disabling LVM...")
        try_run("gnt-cluster modify --no-lvm-storage")

@roles("master")
def destroy_cluster():
    debug(env.host, " * Destroying Ganeti cluster...")
    #TODO: remove instances first
    allnodes = env.env.cluster_hostnames[:]
    allnodes.remove(env.host)
    for n in allnodes:
      host_info = env.env.ips_info[host]
      debug(env.host, " * Removing node %s..." % n)
      cmd = "gnt-node remove  " + host_info.fqdn
      try_run(cmd)
    try_run("gnt-cluster destroy --yes-do-it")


@roles("master")
def init_cluster():
    debug(env.host, " * Initializing Ganeti backend...")
    # extra = ""
    # if env.enable_lvm:
    #     extra += " --vg-name={0} ".format(env.env.vg)
    # else:
    #     extra += " --no-lvm-storage "
    # if not env.enable_drbd:
    #     extra += " --no-drbd-storage "
    extra = " --no-lvm-storage --no-drbd-storage "
    cmd = """
    gnt-cluster init --enabled-hypervisors=kvm \
                     {0} \
                     --nic-parameters link={1},mode=bridged \
                     --master-netdev {2} \
                     --default-iallocator hail \
                     --hypervisor-parameters kvm:kernel_path=,vnc_bind_address=0.0.0.0 \
                     --no-ssh-init --no-etc-hosts \
                    {3}

    """.format(extra, env.env.common_bridge,
               env.env.cluster_netdev, env.env.cluster.fqdn)
    try_run(cmd)


@roles("ganeti")
def debootstrap():
    install_package("ganeti-instance-debootstrap")


@roles("ganeti")
def setup_image_host():
    debug(env.host, "Setting up snf-image...")
    install_package("snf-pithos-backend")
    install_package("snf-image")
    try_run("mkdir -p /srv/okeanos")
    tmpl = "/etc/default/snf-image"
    replace = {
        "synnefo_user": env.env.synnefo_user,
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
        "pithos_dir": env.env.pithos_dir,
        "db_node": env.env.db.ip,
    }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)


@roles("ganeti")
def setup_image_helper():
    debug(env.host, " * Updating helper image...")
    cmd = """
    snf-image-update-helper -y
    """
    try_run(cmd)


@roles("ganeti")
def setup_gtools():
    debug(env.host, " * Setting up snf-cyclades-gtools...")
    with settings(hide("everything")):
        try_run("ping -c1 " + env.env.mq.ip)
    setup_common()
    install_package("snf-cyclades-gtools")
    tmpl = "/etc/synnefo/gtools.conf"
    replace = {
        "synnefo_user": env.env.synnefo_user,
        "synnefo_rabbitmq_passwd": env.env.synnefo_rabbitmq_passwd,
        "mq_node": env.env.mq.ip,
    }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)

    cmd = """
    sed -i 's/false/true/' /etc/default/snf-ganeti-eventd
    /etc/init.d/snf-ganeti-eventd start
    """
    try_run(cmd)


@roles("ganeti")
def setup_iptables():
    debug(env.host, " * Setting up iptables to mangle DHCP requests...")
    cmd = """
    iptables -t mangle -A PREROUTING -i br+ -p udp -m udp --dport 67 -j NFQUEUE --queue-num 42
    iptables -t mangle -A PREROUTING -i tap+ -p udp -m udp --dport 67 -j NFQUEUE --queue-num 42
    iptables -t mangle -A PREROUTING -i prv+ -p udp -m udp --dport 67 -j NFQUEUE --queue-num 42

    ip6tables -t mangle -A PREROUTING -i br+ -p ipv6-icmp -m icmp6 --icmpv6-type 133 -j NFQUEUE --queue-num 43
    ip6tables -t mangle -A PREROUTING -i br+ -p ipv6-icmp -m icmp6 --icmpv6-type 135 -j NFQUEUE --queue-num 44
    """
    try_run(cmd)

@roles("ganeti")
def setup_network():
    debug(env.host, "Setting up networking for Ganeti instances (nfdhcpd, etc.)...")
    install_package("nfqueue-bindings-python")
    install_package("nfdhcpd")
    tmpl = "/etc/nfdhcpd/nfdhcpd.conf"
    replace = {
      "ns_node_ip": env.env.ns.ip
      }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    try_run("/etc/init.d/nfdhcpd restart")

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


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

@roles("cyclades")
def cyclades_loaddata():
    debug(env.host, " * Loading initial data for cyclades...")
    tmpl = "/tmp/flavor.json"
    replace = {}
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl)
    try_run("snf-manage loaddata " + tmpl)
    #run("snf-manage loaddata flavors")


@roles("cyclades")
def setup_cyclades():
    debug(env.host, "Setting up snf-cyclades-app...")
    with settings(hide("everything")):
        try_run("ping -c1 accounts." + env.env.domain)
        try_run("ping -c1 " + env.env.db.ip)
        try_run("ping -c1 " + env.env.mq.ip)
    setup_gunicorn()
    setup_apache()
    setup_webproject()
    install_package("memcached")
    install_package("python-memcache")
    install_package("snf-pithos-backend")
    install_package("kamaki")
    install_package("snf-cyclades-app")
    install_package("python-django-south")
    tmpl = "/etc/synnefo/cyclades.conf"

    with settings(host_string=env.env.accounts.hostname):
        service_id, service_token = get_service_details("cyclades")

    replace = {
        "ACCOUNTS": env.env.accounts.fqdn,
        "CYCLADES": env.env.cyclades.fqdn,
        "mq_node": env.env.mq.ip,
        "db_node": env.env.db.ip,
        "synnefo_user": env.env.synnefo_user,
        "synnefo_db_passwd": env.env.synnefo_db_passwd,
        "synnefo_rabbitmq_passwd": env.env.synnefo_rabbitmq_passwd,
        "pithos_dir": env.env.pithos_dir,
        "common_bridge": env.env.common_bridge,
        "HOST": env.env.cyclades.ip,
        "domain": env.env.domain,
        "CYCLADES_SERVICE_TOKEN": service_token,
        "proxy": env.env.cyclades.hostname == env.env.accounts.hostname
        }
    custom = customize_settings_from_tmpl(tmpl, replace)
    put(custom, tmpl, mode=0644)
    try_run("/etc/init.d/gunicorn restart")

    cmd = """
    sed -i 's/false/true/' /etc/default/snf-dispatcher
    /etc/init.d/snf-dispatcher start
    """
    try_run(cmd)

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


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


@roles("cyclades")
def add_backend():
    debug(env.host, "adding %s ganeti backend to cyclades..." % env.env.cluster.fqdn)
    with settings(hide("everything")):
        try_run("ping -c1 " + env.env.cluster.fqdn)
    cmd = """
    snf-manage backend-add --clustername={0} --user={1} --pass={2}
    """.format(env.env.cluster.fqdn, env.env.synnefo_user,
               env.env.synnefo_rapi_passwd)
    try_run(cmd)
    backend_id = get_backend_id(env.env.cluster.fqdn)
    try_run("snf-manage backend-modify --drained=False " + backend_id)

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

BACKEND_PER_USER = {
  '%s': %s,
}

EOF
/etc/init.d/gunicorn restart
    """  % (user_email, backend_id)
    try_run(cmd)

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


@roles("cyclades")
def add_network():
    debug(env.host, " * Adding public network in cyclades...")
    backend_id = get_backend_id(env.env.cluster.fqdn)
    cmd = """
    snf-manage network-create --subnet={0} --gateway={1} --public --dhcp --flavor={2} --mode=bridged --link={3} --name=Internet --backend-id={4}
    """.format(env.env.synnefo_public_network_subnet,
               env.env.synnefo_public_network_gateway,
               env.env.synnefo_public_network_type,
               env.env.common_bridge, backend_id)
    try_run(cmd)


@roles("cyclades")
def setup_vncauthproxy():
    debug(env.host, " * Setting up vncauthproxy...")
    install_package("snf-vncauthproxy")
    cmd = """
    echo CHUID="www-data:nogroup" >> /etc/default/vncauthproxy
    rm /var/log/vncauthproxy/vncauthproxy.log
    """
    try_run(cmd)
    try_run("/etc/init.d/vncauthproxy restart")

@roles("client")
def setup_kamaki():
    debug(env.host, "Setting up kamaki client...")
    with settings(hide("everything")):
        try_run("ping -c1 accounts." + env.env.domain)
        try_run("ping -c1 cyclades." + env.env.domain)
        try_run("ping -c1 pithos." + env.env.domain)

    with settings(host_string=env.env.db.hostname):
        uid, user_auth_token, user_uuid = get_auth_token_from_db(env.env.user_email)

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

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

@roles("client")
def register_image(image="debian_base.diskdump"):
    debug(env.host, " * Register image to plankton...")
    with settings(host_string=env.env.db.hostname):
        uid, user_auth_token, user_uuid = get_auth_token_from_db(env.env.user_email)

    pithos_url = "pithos://{0}/images/{1}".format(user_uuid, image)
    cmd = """
    sleep 5
    kamaki image register "Debian Base" {0} --public --disk-format=diskdump --property OSFAMILY=linux --property ROOT_PARTITION=1 --property description="Debian Squeeze Base System" --property size=450M --property kernel=2.6.32 --property GUI="No GUI" --property sortorder=1 --property USERS=root --property OS=debian
    """.format(pithos_url)
    try_run(cmd)

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

@roles("pithos")
def add_image_locally():
    debug(env.host, " * Getting image locally in order snf-image to use it directly..")
    image = "debian_base.diskdump"
    try_run("wget {0} -O /srv/okeanos/{1}".format(env.env.debian_base_url, image))


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

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

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