-
Notifications
You must be signed in to change notification settings - Fork 1
/
vhost-manager.py
executable file
·1601 lines (1319 loc) · 55.6 KB
/
vhost-manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
#!/usr/bin/env python3
# encoding: utf-8
import lxc
import sys
import logging
import argparse
import socket
import os
import inspect
import shutil
import pprint
import locale
import json
import tempfile
import time
import stat
import atexit
import platform
import pwd
import collections
import urllib
import re
# interface/bridge for local internet bridging
INET_IFACE_NAME = "inet0"
INET_BRIDGE_NAME = "lxcbr0"
# debug interface for debugging
DEBUG_IFACE_NAME = "debug0"
DEBUG_BRIDGE_NAME = "brdebug0"
DEBUG_IFACE_V4_ADDR = "1.1.1.250"
DEBUG_IFACE_V4_MASK = 16
__programm__ = "vhost-manager"
__version__ = "1"
pp = pprint.PrettyPrinter(indent=4)
TMPDIR = tempfile.mkdtemp()
DEBUG = False
class ConfigurationException(Exception): pass
class ArgumentException(Exception): pass
class EnvironmentException(Exception): pass
class InternalException(Exception): pass
class TopologyDb(object):
def __init__(self, connections, directed=False):
self._graph = collections.defaultdict(set)
self._directed = directed
self.add_connections(connections)
def format(self, thing):
fmt = "\"{}\" [ {} ]\n".format(str(thing), thing.graphviz_repr())
return fmt
def gen_digraph(self):
d = "digraph foo { node [ fontname = \"DejaVu Sans\" ];"
d += " edge [ fontname = \"DejaVu Sans\" ];\n\n"
done = []
for k, v in self._graph.items():
for v2 in v:
if str(k) in done: continue
d += self.format(k)
done.append(str(k))
if str(v2) in done: continue
d += self.format(v2)
done.append(v2.graphviz_repr())
d += "\n"
for k, v in self._graph.items():
for v2 in v:
ks = str(k)
vs = str(v2)
d += " \"{}\" -> \"{}\" [ arrowhead = \"none\", arrowtail = \"normal\"];\n".format(ks, vs)
d += "}\n"
return d
def get_bridges(self):
ret = []
for k, v in self._graph.items():
for v2 in v:
if v2 is not None and isinstance(v2, Bridge):
ret.append(v2)
if k is not None and isinstance(k, Bridge):
ret.append(k)
done = []; reti = []
for bridge in ret:
if bridge.name in done:
continue
done.append(bridge.name)
reti.append(bridge)
return reti
def get_hosts(self):
ret = []
for k, v in self._graph.items():
for v2 in v:
if v2 is not None and isinstance(v2, Host):
ret.append(v2)
if k is not None and isinstance(k, Host):
ret.append(k)
done = []; reti = []
for host in ret:
if host.name in done:
continue
done.append(host.name)
reti.append(host)
return reti
def add_connections(self, connections):
if not connections: return
for node1, node2 in connections:
self.add(node1, node2)
def add(self, node1, node2):
self._graph[node1].add(node2)
if not self._directed:
self._graph[node2].add(node1)
def remove(self, node):
for n, cxns in self._graph.iteritems():
try:
cxns.remove(node)
except KeyError:
pass
try:
del self._graph[node]
except KeyError:
pass
def is_connected(self, node1, node2):
return node1 in self._graph and node2 in self._graph[node1]
def find_path(self, node1, node2, path=[]):
path = path + [node1]
if node1 == node2:
return path
if node1 not in self._graph:
return None
for node in self._graph[node1]:
if node not in path:
new_path = self.find_path(node, node2, path)
if new_path:
return new_path
return None
def __str__(self):
return '{}({})'.format(self.__class__.__name__, dict(self._graph))
def destroy_bridges(self):
for bridge in self.get_bridges():
bridge.destroy()
def destroy_hosts(self):
for host in self.get_hosts():
host.destroy()
def stop_hosts(self):
for host in self.get_hosts():
host.stop()
class Host:
def __init__(self, name, p, u, c, h):
self.u = u
self.c = c
self.p = p
self.name = name
self.config = h
self.container = None
self.init_user_credentials()
def __str__(self):
return "{}".format(self.name)
def init_user_credentials(self):
userdata = self.c.db["user"]
self.username = userdata["username"]
self.userpass = userdata["userpass"]
def remove_tmp_files(self):
close(self.tf_lxc)
close(self.tf_net)
def tmp_file_new(self, string):
name = os.path.join(TMPDIR, string)
fd = open(name, "w")
return fd, name
def tmp_file_destroy(self, name):
if DEBUG: return
os.remove(name)
def create_container(self):
fd, name = self.tmp_file_new("lxc-conf")
config = self.config['config']['conf-lxc']
ret = fd.write(config)
os.fsync(fd); fd.close()
# sudo LC_ALL=C lxc-create --bdev dir -f $(dirname "${BASH_SOURCE[0]}")/lxc-config
# -n $name -t $distribution --logpriority=DEBUG --logfile $logpath -- -r xenial")
# FIXME: logging should be activatable
cmd = "sudo LC_ALL=C lxc-create --bdev dir -n {} ".format(self.name)
cmd += "-f {} -t ubuntu -- -r xenial".format(name)
self.u.exec(cmd)
self.tmp_file_destroy(name)
def start_container(self):
self.u.exec("sudo lxc-start -n {} -d".format(self.name))
self.container = lxc.Container(self.name)
def stop_container(self):
self.u.exec("sudo lxc-stop -n {}".format(self.name))
def restart_container(self):
self.stop_container()
self.start_container()
def exec(self, cmd, user=None):
if user:
cmd = "lxc-attach -n {} --clear-env -- bash -c \"su - {} -c \'{}\'\"".format(self.name, user, cmd)
else:
cmd = "lxc-attach -n {} --clear-env -- bash -c \"{}\"".format(self.name, cmd)
self.u.exec(cmd)
def container_file_copy(self, name, src_path, dst_path, user=None):
cmd = "cat {} | lxc-attach -n {} ".format(src_path, name)
cmd += " --clear-env -- bash -c 'cat >{}'".format(dst_path)
self.u.exec(cmd)
# we don't want a race here: we don't know when the new process
# is scheduled, so we sleep here for a short period, just to make sure[TM]
# that the new process is executed.
time.sleep(.5)
if user:
self.exec("chown -R {}:{} {}".format(user, user, dst_path))
def copy_interface_conf(self):
tmp_fd, tmp_name = self.tmp_file_new("lxc-conf")
config = self.config['config']['conf-debian-interface']
tmp_fd.write(config)
os.fsync(tmp_fd); tmp_fd.close()
self.container_file_copy(self.name, tmp_name, "/etc/network/interfaces")
self.tmp_file_destroy(tmp_name)
def create_user_account(self):
self.exec("useradd --create-home --shell /bin/bash --user-group {}".format(self.username))
self.exec("echo '{}:{}' | chpasswd".format(self.username, self.userpass))
self.exec("echo '{} ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers".format(self.username))
def create_ssh_environment(self):
ssh_dir = os.path.join("/home", self.username, ".ssh")
self.exec("mkdir -p {}".format(ssh_dir), user=self.username)
src_ssh_pub_path = os.path.join("tmp", "ssh-id-rsa.pub")
if not os.path.isfile(src_ssh_pub_path):
raise InternalException("ssh-id-rsa.pub not found {}".format(src_ssh_pub_path))
dst_ssh_path = os.path.join(ssh_dir, "authorized_keys",)
self.container_file_copy(self.name, src_ssh_pub_path, dst_ssh_path, user=self.username)
def user_home_dir(self):
# this function handles also SUDO invoked calls
if "SUDO_UID" not in os.environ:
path = pwd.getpwuid(os.getresuid()[0])[5]
else:
path = pwd.getpwuid(int(os.getenv("SUDO_UID")))[5]
return path
def copy_dotfiles_plain(self, assets_dir):
vimrc_path = os.path.join(assets_dir, "vimrc")
dst_home_path = os.path.join("/home", self.username)
assert os.path.isfile(vimrc_path)
dst_path = os.path.join(dst_home_path, ".vimrc")
self.container_file_copy(self.name, vimrc_path, dst_path, user=self.username)
# bashrc, if user has local one we prefer this one (e.g. proxy settings)
# note: we assume here the user is using sudo, the real user home path
effective_home_path = self.user_home_dir()
bashrc_path = os.path.join(effective_home_path, ".bashrc")
dst_path = os.path.join(dst_home_path, ".bashrc")
if not os.path.isfile(bashrc_path):
# take own provided bashrc
bashrc_path = os.path.join(assets_dir, "bashrc")
self.container_file_copy(self.name, bashrc_path, dst_path, user=self.username)
# we copy bashrc to root too, just that potential proxy settings are
# also available for root too
self.container_file_copy(self.name, bashrc_path, "/root/.bashrc")
def copy_dotfiles(self):
root_dir = os.path.dirname(os.path.realpath(__file__))
assets_dir = os.path.join(root_dir, "assets")
self.copy_dotfiles_plain(assets_dir)
def copy_distribution_specific(self):
# apt.conf contains proxy settings
script_dir = os.path.dirname(os.path.realpath(__file__))
src_path = os.path.join(script_dir, "tmp", "apt.conf")
dst_path = "/etc/apt/apt.conf"
if os.path.isfile(src_path):
self.container_file_copy(self.name, src_path, dst_path)
# wget for proxy things
src_path = os.path.join(script_dir, "tmp", "wgetrc")
dst_path = "/etc/wgetrc"
if os.path.isfile(src_path):
self.container_file_copy(self.name, src_path, dst_path)
def install_base_packages(self):
self.exec("apt-get -y update")
self.exec("apt-get -y install git vim bash python3")
# we do not want that our recently written wget conf is
# overwritten.
self.exec('apt-get -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install wget')
def bootstrap_packages(self):
self.exec("git clone https://github.com/hgn/tr-bootstrapper.git", user=self.username)
self.exec("python3 tr-bootstrapper/bootstrap.py -vvv", user=self.username)
def set_utc_timezone(self):
# http://yellerapp.com/posts/2015-01-12-the-worst-server-setup-you-can-make.html
self.exec("echo 'Etc/UTC' > /etc/timezone")
self.exec("dpkg-reconfigure --frontend noninteractive tzdata")
def create(self):
self.p.msg("Create container: {}\n".format(self), stoptime=1.0)
self.create_container()
self.start_container()
self.copy_interface_conf()
self.restart_container()
self.create_user_account()
self.set_utc_timezone()
self.copy_dotfiles()
self.create_ssh_environment()
self.copy_distribution_specific()
self.install_base_packages()
self.bootstrap_packages()
self.stop_container()
def destroy(self):
c = lxc.Container(self.name)
if c.defined:
question = "Delete container {}?".format(self.name)
answer = self.u.query_yes_no(question, default="no")
if answer == True:
self.p.msg("Delete container in 2 seconds ...\n", color="red", stoptime=2.0)
c.stop()
if not c.destroy():
self.p.msg("Failed to destroy the container!\n", color="red")
sys.exit(1)
else:
self.p.msg("Container {} not available, cannot delete non-existing\n".format(self.name))
def start(self):
c = lxc.Container(self.name)
if not c.defined:
self.p.msg("Topology not created, at least {} not created".format(self.name), color="red")
sys.exit(1)
return
c.start()
def stop(self):
c = lxc.Container(self.name)
if not c.defined:
self.p.msg("Topology not created, at least {} not created".format(self.name), color="red")
sys.exit(1)
return
c.stop()
class Terminal(Host):
def graphviz_repr(self):
iface_info = ""
for k, v in sorted(self.config['terminal-data']['interfaces'].items()):
a = v['ipv4-addr']
n = v['ipv4-addr-netmask']
c = "{}/{}".format(a, n)
iface_info += "<font point-size=\"4\">{} IPv4: {}<br/></font>\n".format(k, c)
t = "Terminal"
fmt = "label = <<font color=\"blue\">{}</font><br/>".format(self.name)
fmt += iface_info
fmt += "<font point-size=\"6\">{}</font>>".format(t)
fmt += ",shape = \"box\""
return fmt
def __str__(self):
return "Terminal({})".format(self.name)
class Router(Host):
def graphviz_repr(self):
iface_info = ""
for k, v in sorted(self.config['terminal-data']['interfaces'].items()):
a = v['ipv4-addr']
n = v['ipv4-addr-netmask']
c = "{}/{}".format(a, n)
iface_info += "<font point-size=\"4\">{} IPv4: {}<br/></font>\n".format(k, c)
t = "Router"
fmt = "label = <<font color=\"blue\">{}</font><br/>".format(self.name)
fmt += iface_info
fmt += "<font point-size=\"6\">{}</font>>".format(t)
fmt += ",shape = \"box\""
return fmt
def __str__(self):
return "Router({})".format(self.name)
class UE(Host):
def graphviz_repr(self):
iface_info = ""
for k, v in sorted(self.config['terminal-data']['interfaces'].items()):
a = v['ipv4-addr']
n = v['ipv4-addr-netmask']
c = "{}/{}".format(a, n)
iface_info += "<font point-size=\"4\">{} IPv4: {}<br/></font>\n".format(k, c)
t = "UE"
fmt = "label = <<font color=\"blue\">{}</font><br/>".format(self.name)
fmt += iface_info
fmt += "<font point-size=\"6\">{}</font>>".format(t)
fmt += ",shape = \"box\""
return fmt
def __str__(self):
return "UE({})".format(self.name)
class Bridge:
def __init__(self, name, p, u, c, h):
self.name = name
self.p = p
self.u = u
self.c = c
self.netem = self.__deserialize_netem(h)
def __construct_netem_cmd(self, data):
cmd = ""
for k, v in data.items():
if type(v) == list:
fv = ""
for vv in v:
fv += "{} ".format(vv)
elif type(v) == str:
fv = v
else:
raise "format not supported {}".format(type(v))
cmd += " {} {}".format(k, fv)
return cmd
def __construct_netem_atoms(self, data):
return data
def __parse_netem_static(self, data):
d = dict()
d["class"] = data["class"]
d["description"] = data["description"]
d["cmd-start"] = self.__construct_netem_cmd(data["data"])
d["atoms"] = self.__construct_netem_atoms(data["data"])
return d
def __parse_netem_dynamic(self, data):
d = dict()
d["class"] = data["class"]
d["description"] = data["description"]
d["cmd-start"] = self.__construct_netem_cmd(data["data"])
d["atoms"] = self.__construct_netem_atoms(data["data"])
ar = []
for line in data["op-data"]:
dd = dict()
dd["time"] = line[0]
dd["cmd"] = self.__construct_netem_cmd(line[1])
dd["atoms"] = self.__construct_netem_atoms(line[1])
ar.append(dd)
d["cmd-runs"] = ar
return d
def __deserialize_netem(self, h):
if h is None:
return None
if "description" not in h:
raise ConfigurationException("Netem class has no description: {}\n".format(h))
if "class" not in h:
raise ConfigurationException("Netem class has no class: {}\n".format(h))
if "data" not in h:
raise ConfigurationException("Netem class has no data: {}\n".format(h))
if h["class"] == "dynamic" and not "op-data" in h:
raise ConfigurationException("Netem class is dyanmic but no op-data given{}\n".format(h))
if h["class"] == "static":
return self.__parse_netem_static(h)
# dynmic case
return self.__parse_netem_dynamic(h)
def __str__(self):
return "Bridge({})".format(self.name)
@staticmethod
def create_debug_bridge():
sys.stderr.write("Create debug bridge: {}\n".format(DEBUG_BRIDGE_NAME))
brige_path = os.path.join("/sys/class/net", DEBUG_BRIDGE_NAME)
if os.path.isdir(brige_path):
sys.stderr.write("debug bridge {} already created\n".format(DEBUG_BRIDGE_NAME))
return
Utils.sexec("brctl addbr {}".format(DEBUG_BRIDGE_NAME))
Utils.sexec("brctl setfd {} 0".format(DEBUG_BRIDGE_NAME))
Utils.sexec("brctl sethello {} 5".format(DEBUG_BRIDGE_NAME))
Utils.sexec("ip link set dev {} up".format(DEBUG_BRIDGE_NAME))
Utils.sexec("ip addr add {}/{} dev {}".format(DEBUG_IFACE_V4_ADDR, DEBUG_IFACE_V4_MASK, DEBUG_BRIDGE_NAME))
@staticmethod
def destroy_debug_bridge():
brige_path = os.path.join("/sys/class/net", DEBUG_BRIDGE_NAME)
if not os.path.isdir(brige_path):
return
sys.stderr.write("Delete bridge {}\n".format(DEBUG_BRIDGE_NAME))
Utils.sexec("ip link set dev {} down".format(DEBUG_BRIDGE_NAME))
Utils.sexec("brctl delbr {}".format(DEBUG_BRIDGE_NAME))
@staticmethod
def netem_exec(bridge_name, cmd):
cmd = "tc qdisc change dev {} root netem {}".format(bridge_name, cmd)
print(" bridge exec: {}".format(cmd))
Utils.sexec(cmd)
def create(self):
self.p.msg("Create bridge: {}\n".format(self.name))
brige_path = os.path.join("/sys/class/net", self.name)
if os.path.isdir(brige_path):
self.p.msg("bridge {} already created\n".format(self.name), color="magenta")
return
self.u.exec("brctl addbr {}".format(self.name))
self.u.exec("brctl setfd {} 0".format(self.name))
self.u.exec("brctl sethello {} 5".format(self.name))
self.u.exec("ip link set dev {} up".format(self.name))
def destroy(self):
brige_path = os.path.join("/sys/class/net", self.name)
if not os.path.isdir(brige_path):
return
self.p.msg("Delete bridge {}\n".format(self.name))
self.u.exec("ip link set dev {} down".format(self.name))
self.u.exec("brctl delbr {}".format(self.name))
def graphviz_repr(self):
netem = " "
if self.netem and 'cmd' in self.netem:
netem = "Netem: {}".format(self.netem['cmd'])
fmt = "label = <<font point-size=\"6\">Bridge: {}</font><br/>".format(self.name)
fmt += "<font point-size=\"4\">{}</font>>".format(netem)
fmt += ",shape = \"rect\""
return fmt
def __connected_interfaces(self):
path = "/sys/devices/virtual/net/{}/brif/".format(self.name)
if not os.path.isdir(path):
self.p.msg("device not available, topology started?", color="red")
return None
return os.listdir(path)
def start_netem(self):
if not self.netem:
# nothin to do, skip this bridge
return
veth_names = self.__connected_interfaces()
for veth_name in veth_names:
self.p.msg("apply netem rule to interface {}\n".format(veth_name), color=None)
self.p.msg(" netem cmd: {}\n".format(self.netem["cmd"]), color=None)
self.u.exec("tc qdisc add dev {} root netem {}".format(veth_name, self.netem["cmd"]))
class Printer:
def __init__(self, verbose=False):
self.verbose = verbose
self.init_colors()
def init_colors(self):
self.color_palette = {
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'magenta':'\033[35m',
'cyan': '\033[36m',
'lightred': '\033[91m',
'lightgreen': '\033[92m',
'lightyellow': '\033[93m',
'lightblue': '\033[94m',
'lightmagenta':'\033[95m',
'lightcyan': '\033[96m',
'end':'\033[0m'
}
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
if not is_a_tty:
for key, value in self.color_palette.items():
self.color_palette[key] = ""
def set_verbose(self):
self.verbose = True
def err(self, msg):
sys.stderr.write(msg)
def verbose(self, msg):
if not self.verbose:
return
sys.stderr.write(msg)
def msg(self, msg, stoptime=None, color="yellow", clear=False):
if clear: self.clear()
if color:
if color in self.color_palette:
msg = "{}{}{}".format(self.color_palette[color], msg, self.color_palette['end'])
else:
raise InternalException("Color not known")
ret = sys.stdout.write(msg) - 1
if stoptime:
time.sleep(stoptime)
return ret
def line(self, length, char='-'):
sys.stdout.write(char * length + "\n")
def msg_underline(self, msg, pre_news=0, post_news=0):
str_len = len(msg)
if pre_news:
self.msg("\n" * pre_news)
self.msg(msg)
self.msg("\n" + '=' * str_len)
if post_news:
self.msg("\n" * post_news)
def clear(self):
os.system("clear")
class Utils:
def exec(self, args):
print("execute: \"{}\"".format(args))
os.system(args)
@staticmethod
def sexec(args):
print("execute: \"{}\"".format(args))
os.system(args)
def query_yes_no(self, question, default="yes"):
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
def valid_url(self, url):
import urllib.parse
# see https://docs.python.org/3.0/library/urllib.parse.html
# for valid attributes to check
to_check = ("scheme", "netloc")
token = urllib.parse.urlparse(url)
return all([getattr(token, qualifying_attr) for qualifying_attr in to_check])
@staticmethod
def get_tree_size(path):
total = 0
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
total += Utils.get_tree_size(entry.path)
else:
total += entry.stat(follow_symlinks=False).st_size
return total
@staticmethod
def human_byte_size(size):
suffixes = ('B','KB','MB','GB','TB')
suffix_index = 0
while size > 1024 and suffix_index < len(suffixes) - 1:
suffix_index += 1
size = size / 1024.0
return "{:.2f}{}".format(size, suffixes[suffix_index])
class Configuration():
def __init__(self, topology=None):
self.db = self.load_configuration("conf.json")
self.topology_name = topology
def load_configuration(self, filename):
with open(filename) as json_data:
d = json.load(json_data)
json_data.close()
return d
def topologies(self):
r = []
for k, v in self.db["topologies"].items():
r.append([k, v["description"]])
return r
def is_valid(self):
for topology in self.db["topologies"]:
if self.topology_name == topology:
return True
raise ArgumentException("topology not found: {}".format(self.topology_name))
def terminal_gen_config(self, terminal_data):
d = {}
# standard data always present
e = "auto lo\n"
e += "iface lo inet loopback\n\n"
# upstream interface towards "internet"
e += "auto inet0\n"
e += "iface inet0 inet dhcp\n\n"
# for debug interface
e += "auto {}\n".format(DEBUG_IFACE_NAME)
e += "iface {} inet static\n".format(DEBUG_IFACE_NAME)
e += " address {}\n".format(terminal_data['interface-debug']["ipv4-addr"])
e += " netmask {}\n\n".format(terminal_data['interface-debug']["ipv4-addr-netmask"])
# Debian Network section
for interface_name, interface_data in terminal_data["interfaces"].items():
e += "auto {}\n".format(interface_name)
e += "iface {} inet static\n".format(interface_name)
e += " address {}\n".format(interface_data["ipv4-addr"])
e += " netmask {}\n".format(interface_data["ipv4-addr-netmask"])
if "post-up" in interface_data:
assert isinstance(interface_data["post-up"], list)
for line in interface_data["post-up"]:
e += " post-up {}\n".format(line)
e += "\n"
d["conf-debian-interface"] = e
# LXC section
e = "lxc.network.type = veth\n"
e += "lxc.network.name = {}\n".format(INET_IFACE_NAME)
e += "lxc.network.flags = up\n"
e += "lxc.network.link = {}\n".format(INET_BRIDGE_NAME)
e += "lxc.network.hwaddr = 00:11:xx:xx:xx:xx\n\n"
# LXC section for debug interface
e += "lxc.network.type = veth\n"
e += "lxc.network.name = {}\n".format(DEBUG_IFACE_NAME)
e += "lxc.network.flags = up\n"
e += "lxc.network.link = {}\n".format(DEBUG_BRIDGE_NAME)
e += "lxc.network.hwaddr = 00:00:xx:xx:xx:xx\n\n"
for interface_name, interface_data in terminal_data["interfaces"].items():
e += "lxc.network.type = veth\n"
e += "lxc.network.name = {}\n".format(interface_name)
e += "lxc.network.flags = up\n"
e += "lxc.network.link = {}\n".format(interface_data["lxr-link"])
e += "lxc.network.hwaddr = {}\n\n".format(interface_data["lxr-hw-addr"])
d["conf-lxc"] = e
return d
def host_handle(self, name):
d = dict()
for i in ("terminals", "router", "ue"):
if name in self.db["devices"][i]:
terminal = self.db["devices"][i][name]
d['terminal-data'] = terminal
d['config'] = self.terminal_gen_config(terminal)
return d
raise ConfigurationException("entity (router, terminal, ...) not found: {}".format(name))
def link_class_by_name(self, name):
if "link-classes" not in self.db:
return None
if name not in self.db["link-classes"]:
self.p.msg("link-class not available: {}\n".format(self.db["link-classes"]))
sys.exit(1)
return self.db["link-classes"][name]
def bridge_handle(self, bridge_name):
topo_db = self.db["topologies"][self.topology_name]
if "netem" not in topo_db:
# nothing to do
return
netem = self.db["topologies"][self.topology_name]["netem"]
for netem_entry in netem:
bridge, netem_conf = netem_entry
entry_bridge_name = bridge.split('(')[1].split(')')[0]
if entry_bridge_name != bridge_name:
continue
return self.link_class_by_name(netem_conf)
return None
def create_entity_object(self, entry_type, entry_name, p, u, c):
if entry_type == "Router":
h = self.host_handle(entry_name)
return Router(entry_name, p, u, c, h)
if entry_type == "Terminal":
h = self.host_handle(entry_name)
return Terminal(entry_name, p, u, c, h)
if entry_type == "UE":
h = self.host_handle(entry_name)
return UE(entry_name, p, u, c, h)
if entry_type == "Bridge":
h = self.bridge_handle(entry_name)
return Bridge(entry_name, p, u, c, h)
assert False
def create_topology_db(self, topology_name, p, u, c):
if not self.topology_name in self.db["topologies"]:
raise ArgumentException("Topology {} not available".format(self.topology_name))
topo = self.db["topologies"][self.topology_name]
g = TopologyDb(None, directed=True)
for item in topo["map"]:
entries = item.split()
assert len(entries) == 3
assert entries[1] == "<->"
# src
entity_pair = entries[0].split('(')
entity_type = entity_pair[0]
entity_name = entity_pair[1].split(')')[0]
o1 = self.create_entity_object(entity_type, entity_name, p, u, c)
# dst
entity_pair = entries[2].split('(')
entity_type = entity_pair[0]
entity_name = entity_pair[1].split(')')[0]
o2 = self.create_entity_object(entity_type, entity_name, p, u, c)
g.add(o1, o2)
return g
class BridgeCreator():
def __init__(self, utils, printer, name):
self.u = utils
self.p = printer
self.bridge_name = name
def create(self):
brige_path = os.path.join("/sys/class/net", self.bridge_name)
if os.path.isdir(brige_path):
self.p.msg("bridge {} already created\n".format(self.bridge_name))
return
self.u.exec("brctl addbr {}".format(self.bridge_name))
self.u.exec("brctl setfd {} 0".format(self.bridge_name))
self.u.exec("brctl sethello {} 5".format(self.bridge_name))
self.u.exec("ip link set dev {} up".format(self.bridge_name))
class TopologyCreate():
def __init__(self):
uid0_required()
self.u = Utils()
self.p = Printer()
self.parse_local_options()
def parse_local_options(self):
parser = argparse.ArgumentParser()
parser.add_argument( "-v", "--verbose", dest="verbose", default=False,
action="store_true", help="show verbose")
parser.add_argument("topology", help="name of the topology", type=str)
self.args = parser.parse_args(sys.argv[2:])
if self.args.verbose:
self.p.set_verbose()
def start_container(self, host):
c = lxc.Container(host.name)
if c.defined:
c.start()
def tmp_dig_fd_new(self, string):
name = os.path.join(TMPDIR, string)
fd = open(name,"w")
return fd, name
def run(self):
try:
self.c = Configuration(topology=self.args.topology)
except ArgumentException as e:
print("not a valid topology: {}".format(e))
sys.exit(1)
self.p.msg("Create topology {}\n".format(self.args.topology), stoptime=1.0)
topology_db = self.c.create_topology_db(self.args.topology, self.p, self.u, self.c)
topology_db.destroy_bridges()
topology_db.destroy_hosts()
# create bridges first, if not already created
Bridge.destroy_debug_bridge()
Bridge.create_debug_bridge()
for bridge in topology_db.get_bridges():
bridge.create()
for host in topology_db.get_hosts():
host.create()
self.p.msg("Start container:\n")
for host in topology_db.get_hosts():
self.p.msg(" {}\n".format(host.name))
self.start_container(host)
cnt_size_byte = Utils.get_tree_size("/var/lib/lxc/")
cnt_size_human = Utils.human_byte_size(cnt_size_byte)
self.p.msg("Created container size {}\n".format(cnt_size_human))
class TopologyGraph():
def __init__(self):
self.u = Utils()
self.p = Printer()
self.parse_local_options()
self.file_out_name = "topology-graph.png"
def parse_local_options(self):
parser = argparse.ArgumentParser()
parser.add_argument("topology", help="name of the topology", type=str)
self.args = parser.parse_args(sys.argv[2:])
def tmp_dig_fd_new(self, string):
name = os.path.join(TMPDIR, string)
fd = open(name, "w")
return fd, name
def gen_digraph_image(self, topology_db):
d = topology_db.gen_digraph()
fd, name = self.tmp_dig_fd_new("digraph.data")
fd.write(d)
os.fsync(fd); fd.close()
self.p.msg("Generate topology file: {}\n".format(self.file_out_name), color=None)
os.system("cat {} | dot -Tpng -Gsize=20,80\! -Gdpi=200 > {}".format(name, self.file_out_name))
def run(self):
try:
self.c = Configuration(topology=self.args.topology)
except ArgumentException as e:
self.p.msg("Not a valid topology: {}".format(e))
sys.exit(1)
topology_db = self.c.create_topology_db(self.args.topology, self.p, self.u, self.c)
self.p.msg("Generate graph of topopolgy\n")
self.gen_digraph_image(topology_db)
class TopologyConnect():
def __init__(self):
uid0_required()
self.u = Utils()
self.p = Printer()
self.parse_local_options()
def parse_local_options(self):
parser = argparse.ArgumentParser()
parser.add_argument("topology", help="name of the topology", type=str)
self.args = parser.parse_args(sys.argv[2:])