-
Notifications
You must be signed in to change notification settings - Fork 3
/
subutai.py
812 lines (704 loc) · 26.9 KB
/
subutai.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2018 Fernando H R Silva <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: subutai
short_description: Subutai container module. This modules manage all life cicle of subutai containers.
description:
- Subutai is a daemon written in Golang whose main task is to receive commands from the Subutai Social
management server and execute them on Resource Hosts.
Behind such a seemingly simple task are complex procedures like bidirectional ssl communication, gpg
message encryption, different health and security checks, etc.
version_added: "2.6"
options:
name:
description:
- Name of container or network.
network:
description:
- Define network operations, like Configuring network tunnel for containers in subutai, vxlan tunnels,
and network maps.
Subutai VXLAN is network layer built on top of P2P swarms and intended to be environment communication
bridges between physically separate hosts. Each Subutai environment has its own separate VXLAN tunnel
so all internal network traffic goes through isolated channels, doesn't matter if environment located
on single peer or distributed between multiple peers.
The tunnel feature is based on SSH tunnels and works in combination with Subutai Helpers and serves as
an easy solution for bypassing NATs. In Subutai, tunnels are used to access the SS management server's
web UI from the Bazaar, and open direct connection to containers, etc. There are two types of channels
local (default), which is created from destination address to host and global, from destination to
Subutai Helper node. Tunnels may also be set to be permanent (default) or temporary (ttl in seconds).
The default destination port is 22.
Subutai tunnels have a continuous state checking mechanism which keeps opened tunnels alive and closes
outdated tunnels to keep the system network connections clean. This mechanism may re-create a tunnel if
it was dropped unintentionally (system reboot, network interruption, etc.), but newly created tunnels
will have different "entrance" address.
choices: [ 'tunnel', 'map', 'vxlan', 'proxy' ]
state:
description:
- Indicates the desired container state are installed.
default: 'present'
choices: [ 'absent', 'present', 'latest', 'started', 'stopped' ]
check:
description:
- Check for updates without installation.
type: bool
source:
description:
- Set the source for promoting.
ipaddr:
description:
- IPv4 address, ie 192.168.1.1/24
vlan:
description:
- VLAN tag.
ttl:
description:
- Tunnels may also be set to be permanent or temporary (ttl in seconds).
globalFlag:
description:
- There are two types of channels - local, which is created from destination address to host and global from destination to Subutai Helper node.
type: bool
template:
description:
- A flag to specify if changes will affect template or a container
type: bool
protocol:
description:
- Specifies required protocol for mapping and might be http, https, tcp or udp.
choices: [ 'http', 'https', 'tcp', 'udp' ]
internal:
description:
- Peer's internal socket that should be exposed. Format should be <ip>/<port>
external:
description:
- Optional parameter which shows desired RH socket where internal socket should be mapped.
If more than one container mapped to one RH port, those containers are being put to the same backend group.
Allowed port value must be in range of 1000-65535
domain:
description:
- Should be only specified for http and https protocols mapping.
cert:
description:
- Path to SSL pem certificate for https protocol.
map_policy:
description:
- Balancing methods (round-robin by default, least_time, hash, ip_hash).
choices: [ 'round-robin', 'least_time', 'hash', 'ip_hash' ]
sslbackend :
description:
- SSL backend in https upstream.
vxlan:
description:
- Vxlan name.
remoteip:
description:
- Remote IP address.
vni:
description:
- VXLAN tunnel VNI.
interface:
description:
- Interface name
hash:
description:
- hash
key:
description:
- key
localPeepIPAddr:
description:
- localPeepIPAddr
portrange :
description:
- portrange
host:
description:
- Add host to domain on VLAN.
proxy_policy:
description:
- Set load balance policy (rr|lb|hash).
choices: [ 'lb', 'rr', 'hash' ]
file:
description:
- Pem certificate file.
author:
- "Fernando Silva (@liquuid)"
'''
EXAMPLES = '''
- name: run subutai import nginx
subutai:
name: nginx
state: present
- name: run subutai destroy nginx
subutai:
name: nginx
state: absent
- name: run subutai destroy template nginx
subutai:
name: nginx
state: absent
template: true
- name: upgrade nginx
subutai:
name: nginx
state: latest
- name: subutai tunnel add 10.10.0.20
subutai:
network: tunnel
state: present
ipaddr: 10.10.0.20
- name: subutai tunnel add 10.10.0.30:8080 300 -g
subutai:
network: tunnel
state: present
ipaddr: 10.10.0.30:8080
ttl: 300
globalFlag: true
- name: subutai tunnel del 10.10.0.30:8080
subutai:
network: tunnel
state: absent
ipaddr: 10.10.0.30:8080
- name: subutai tunnel del 10.10.0.20:8080
subutai:
network: tunnel
state: absent
ipaddr: 10.10.0.20:22
- name: map container's 172.16.31.3 port 3306 to the random port on RH
subutai:
network: map
state: present
protocol: tcp
internal: 172.16.31.3:3306
- name: add 172.16.31.4:3306 to the same group
subutai:
network: map
state: present
protocol: tcp
internal: 172.16.31.4:3306
external: 46558
- name: remove container 172.16.31.3 from mapping
subutai:
network: map
state: absent
protocol: tcp
internal: 172.16.31.3:3306
external: 46558
- name: map 172.16.25.12:80 to RH's 8080 with domain name example.com
subutai:
network: map
state: present
protocol: http
internal: 172.16.25.12:80
external: 8080
domain: example.com
- name: add container to existing example.com domain
subutai:
network: map
state: present
protocol: http
internal: 172.16.25.13:80
external: 8080
domain: example.com
- name: adding subutai vxlan tunnel
subutai:
network: vxlan
state: present
vxlan: vxlan1
remoteip: 10.220.22.2
vlan: 100
vni: 12345
- name: removing subutai vxlan tunnel
subutai:
network: vxlan
state: absent
vxlan: vxlan1
- name: add domain example.com to 100 vlan
subutai:
network: proxy
state: present
vlan: 100
domain: example.com
- name: add domain example.com to 100 vlan
subutai:
network: proxy
state: present
vlan: 100
host: 10.10.0.20
- name: delete domain example.com
subutai:
conetwork: proxy
state: absent
vlan: 100
domain: example.com
- name: delete host 10.10.0.20
subutai:
conetwork: proxy
state: absent
vlan: 100
host: 10.10.0.20
'''
RETURN = '''
container:
description: Container affected.
type: string
returned: always
sample: "apache"
stderr:
description: Error output from subutai container
type: string
returned: success, when need
sample: "FATA[2018-03-09 00:10:29] Extracting tgz, read /var/lib/lxc: is a directory"
'''
import subprocess
from ansible.module_utils.basic import AnsibleModule
class Container():
def __init__(self):
# parameters
self.module_args = dict(
name=dict(type='str', required=False),
template=dict(type='bool', required=False),
network=dict(type='str', choices=[
'tunnel', 'map', 'vxlan', 'proxy']),
source=dict(type='str', required=False),
check=dict(type='bool', required=False),
ipaddr=dict(type='str', required=False),
vlan=dict(type='str', required=False),
ttl=dict(type='str', required=False),
globalFlag=dict(type='bool', required=False),
state=dict(type='str', default='present', choices=[
'absent', 'present', 'latest', 'started', 'stopped']),
protocol=dict(type='str', required=False, choices=[
'http', 'https', 'tcp', 'udp']),
internal=dict(type='str', required=False),
external=dict(type='str', required=False),
domain=dict(type='str', required=False),
cert=dict(type='str', required=False),
map_policy=dict(type='str', required=False, choices=[
'round-robin', 'least_time', 'hash', 'ip_hash']),
proxy_policy=dict(type='str', required=False,
choices=['lb', 'rr', 'hash']),
sslbackend=dict(type='str', required=False),
vxlan=dict(type='str', required=False),
remoteip=dict(type='str', required=False),
vni=dict(type='str', required=False),
interface=dict(type='str', required=False),
hash=dict(type='str', required=False),
key=dict(type='str', required=False),
localPeepIPAddr=dict(type='str', required=False),
portrange=dict(type='str', required=False),
host=dict(type='str', required=False),
file=dict(type='str', required=False),
)
self.module = AnsibleModule(
argument_spec=self.module_args,
supports_check_mode=True,
required_one_of=[['name', 'network']],
required_if=[
["network", "tunnel", ["ipaddr"]],
["network", "map", ["protocol"]],
["network", "vxlan", ["vxlan"]],
]
)
# skell to result
self.result = self.module.params.copy()
self.result['changed'] = False
self.result['message'] = ''
# check mode, don't made any changes
if self.module.check_mode:
self._exit()
self.args = []
if self.module.params['check']:
self.args.append("-c")
if self.module.params['name']:
if self.module.params['state'] == 'present':
self._import()
if self.module.params['state'] == 'absent':
if self.module.params['template']:
self.args.append("-t")
self._destroy()
if self.module.params['state'] == 'latest':
self._update()
if self.module.params['state'] == 'started':
self._start()
if self.module.params['state'] == 'stopped':
self._stop()
if self.module.params['network'] == 'tunnel':
self._tunnel()
if self.module.params['network'] == 'map':
self._map()
if self.module.params['network'] == 'vxlan':
self._vxlan()
if self.module.params['network'] == 'proxy':
self._proxy()
def _start(self):
if self._is_running():
self.result['changed'] = False
self._exit()
# verify if container is already installed
if not self._is_installed():
self.result['changed'] = True
self.result['message'] = 'not installed'
self._subutai_cmd("import")
# try start container
if self._subutai_cmd("start"):
self._return_fail("Start Error")
if self._is_running():
self.result['changed'] = True
else:
# try start container
if self._subutai_cmd("start"):
self._return_fail("Start Error")
if self._is_running():
self.result['changed'] = True
self._exit()
def _stop(self):
# verify if container is already installed
if not self._is_installed():
self.result['changed'] = True
self.result['message'] = 'not installed'
self._subutai_cmd("import")
# try stop container
if self._subutai_cmd("stop"):
self._return_fail("Stop Error")
if self._is_running():
self.result['changed'] = True
else:
if not self._is_running():
self.result['changed'] = False
self._exit()
# try start container
if self._subutai_cmd("stop"):
self._return_fail("Stop Error")
if not self._is_running():
self.result['changed'] = True
self._exit()
def _update(self):
# verify if container is already installed
if not self._is_installed():
self.result['changed'] = True
self.result['message'] = 'not installed'
self._subutai_cmd("import")
self._exit()
else:
if self._subutai_cmd("start"):
self._return_fail("Start Error")
# try update container
if self._subutai_cmd("update"):
self._return_fail("Update Error")
self.result['changed'] = True
self._exit()
def _destroy(self):
if not self._is_installed():
self.result['changed'] = False
self._exit()
else:
# try destroy container
out = self._subutai_cmd("destroy")
if out:
self._return_fail("Destroy Error: " + str(out))
self.result['changed'] = True
self._exit()
def _import(self):
# verify if container is already installed
if self._is_installed():
self.result['changed'] = False
self.result['message'] = 'already installed'
else:
# try install container
out = self._subutai_cmd("import")
if out:
self._return_fail("Import Error: " + str(out))
if self._is_installed():
self.result['changed'] = True
self._exit()
def _tunnel(self):
if self.module.params['ttl']:
self.args.append(self.module.params['ttl'])
if self.module.params['globalFlag']:
self.args.append("-g")
if self.module.params['state'] == "present":
if not self._exists_tunnel():
try:
err = subprocess.Popen(
["/usr/bin/subutai", "tunnel", "add", self.module.params['ipaddr']] + self.args, stderr=subprocess.PIPE).stderr.read()
if err:
self.result['stderr'] = err
self._return_fail(err)
else:
self.result['changed'] = True
self._exit()
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
else:
self.result['changed'] = False
self.result['stderr'] = "Tunnel already exist"
self._exit()
elif self.module.params['state'] == "absent":
if self._exists_tunnel():
try:
err = subprocess.Popen(
["/usr/bin/subutai", "tunnel", "del", self.module.params['ipaddr']], stderr=subprocess.PIPE).stderr.read()
if err:
self.result['stderr'] = err
self._return_fail(err)
else:
self.result['changed'] = True
self._exit()
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
else:
self.result['changed'] = False
self.result['stderr'] = "Tunnel do not exist"
self._exit()
else:
self._return_fail(err)
def _map(self):
self.args.append(self.module.params['protocol'])
if self.module.params['internal']:
self.args.append("--internal")
self.args.append(self.module.params['internal'])
if self.module.params['external']:
self.args.append("--external")
self.args.append(self.module.params['external'])
if self.module.params['domain']:
self.args.append("--domain")
self.args.append(self.module.params['domain'])
if self.module.params['cert']:
self.args.append("--cert")
self.args.append(self.module.params['cert'])
if self.module.params['map_policy']:
self.args.append("--policy")
self.args.append(self.module.params['map_policy'])
if self.module.params['sslbackend']:
self.args.append("--sslbackend")
self.args.append(self.module.params['sslbackend'])
if self.module.params['state'] == 'absent':
self.args.append("--remove")
try:
err = subprocess.Popen(["/usr/bin/subutai", "map", self.module.params['protocol']
] + self.args, stderr=subprocess.PIPE).stderr.read()
if err:
if "already exists" in err:
self.result['changed'] = False
self._exit()
else:
self.result['stderr'] = err
self._return_fail(err)
else:
self.result['changed'] = True
self._exit()
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
def _vxlan(self):
if self.module.params['remoteip']:
self.args.append("--remoteip")
self.args.append(self.module.params['remoteip'])
if self.module.params['vlan']:
self.args.append("--vlan")
self.args.append(self.module.params['vlan'])
if self.module.params['vni']:
self.args.append("--vni")
self.args.append(self.module.params['vni'])
if self.module.params['state'] == "present":
try:
err = subprocess.Popen(
["/usr/bin/subutai", "vxlan", "--create", self.module.params['vxlan']] + self.args, stderr=subprocess.PIPE).stderr.read()
if err:
self.result['stderr'] = err
self._return_fail(err)
else:
if self.module.params['vxlan'] in self._exists_vxlan():
self.result['changed'] = True
self._exit()
else:
self._return_fail(err)
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
elif self.module.params['state'] == "absent":
try:
err = subprocess.Popen(
["/usr/bin/subutai", "vxlan", "--delete", self.module.params['vxlan']], stderr=subprocess.PIPE).stderr.read()
if err:
self.result['stderr'] = err
self._return_fail(err)
else:
if self.module.params['vxlan'] not in self._exists_vxlan():
self.result['changed'] = True
self._exit()
else:
self._return_fail(err)
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
else:
self._return_fail(err)
def _proxy(self):
check_args = []
if self.module.params['domain']:
self.args.append("--domain")
self.args.append(self.module.params['domain'])
check_args.append("-d")
if self.module.params['host']:
self.args.append("--host")
self.args.append(self.module.params['host'])
check_args.append("-h")
check_args.append(self.module.params['host'])
if self.module.params['proxy_policy']:
self.args.append("--policy")
self.args.append(self.module.params['proxy_policy'])
if self.module.params['file']:
self.args.append("--file")
self.args.append(self.module.params['file'])
if self.module.params['state'] == "present":
try:
out = subprocess.Popen(
["/usr/bin/subutai", "proxy", "check", self.module.params['vlan']] + check_args, stdout=subprocess.PIPE).stdout.read()
if out:
self.result['changed'] = False
self._exit()
else:
err = subprocess.Popen(
["/usr/bin/subutai", "proxy", "add", self.module.params['vlan']] + self.args, stderr=subprocess.PIPE).stderr.read()
if err:
self.result['stderr'] = err
self._return_fail(err)
else:
self.result['changed'] = True
self._exit()
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
elif self.module.params['state'] == "absent":
try:
err = subprocess.Popen(
["/usr/bin/subutai", "proxy", "del", self.module.params['vlan']] + check_args, stderr=subprocess.PIPE).stderr.read()
if err:
self.result['stderr'] = err
self._return_fail(err)
else:
self.result['changed'] = True
self.result['message'] = str(self.args)
self._exit()
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
else:
self._return_fail(err)
def _exists_vxlan(self):
try:
return subprocess.Popen(["/usr/bin/subutai", "vxlan", "-l"], stdout=subprocess.PIPE).stdout.read()
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
def _exit(self):
self.module.exit_json(**self.result)
def _return_fail(self, err_msg):
self.result['stderr'] = err_msg
self.result['changed'] = False
self.module.fail_json(msg='[Err] ' + err_msg, **self.result)
def _is_installed(self):
try:
out = subprocess.Popen(
["/usr/bin/subutai", "list"], stdout=subprocess.PIPE).stdout.read()
if self.module.params['name'] + '\n' in out:
return True
else:
return False
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
def _exists_tunnel(self):
try:
out = subprocess.Popen(
["/usr/bin/subutai", "tunnel", "list"], stdout=subprocess.PIPE).stdout.read()
if self.module.params['ipaddr'] in out:
return True
else:
return False
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
def _is_running(self):
try:
out = subprocess.Popen(
["/usr/bin/subutai", "list", "-i", self.module.params['name']], stdout=subprocess.PIPE).stdout.read()
if bytes("RUNNING") in out:
return True
else:
return False
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
def _subutai_cmd(self, cmd):
try:
msg = subprocess.Popen(
["/usr/bin/subutai", cmd, self.module.params['name']] + self.args, stderr=subprocess.PIPE).stderr.read()
return msg
except OSError as e:
if "[Errno 2] No such file or directory" in str(e):
self.result['changed'] = False
self._return_fail("Subutai is not installed")
else:
self.result['changed'] = False
self._return_fail("OS Error " + str(e))
def main():
Container()
if __name__ == '__main__':
main()