Repository navigation
Expand file tree
/
Copy pathlxc.py
More file actions
4778 lines (3966 loc) · 152 KB
/
Copy pathlxc.py
File metadata and controls
4778 lines (3966 loc) · 152 KB
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
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name: