/
utils.py
2332 lines (1936 loc) · 71.7 KB
/
utils.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
"""
Misc heavy lifting functions for cobbler
Copyright 2006-2009, Red Hat, Inc and Others
Michael DeHaan <michael.dehaan AT gmail>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
import sys
import os
import re
import copy
import socket
import glob
import random
import subprocess
import shutil
import string
import traceback
import errno
from cexceptions import FileNotFoundException, CX
import codes
import netaddr
import shlex
import field_info
import clogger
import yaml
import urllib2
import simplejson
import hashlib
def md5(key):
return hashlib.md5(key)
CHEETAH_ERROR_DISCLAIMER = """
# *** ERROR ***
#
# There is a templating error preventing this file from rendering correctly.
#
# This is most likely not due to a bug in Cobbler and is something you can fix.
#
# Look at the message below to see what things are causing problems.
#
# (1) Does the template file reference a $variable that is not defined?
# (2) is there a formatting error in a Cheetah directive?
# (3) Should dollar signs ($) be escaped that are not being escaped?
#
# Try fixing the problem and then investigate to see if this message goes
# away or changes.
#
"""
# From http://code.activestate.com/recipes/303342/
class Translator:
allchars = string.maketrans('', '')
def __init__(self, frm='', to='', delete='', keep=None):
if len(to) == 1:
to = to * len(frm)
self.trans = string.maketrans(frm, to)
if keep is None:
self.delete = delete
else:
self.delete = self.allchars.translate(self.allchars, keep.translate(self.allchars, delete))
def __call__(self, s):
return s.translate(self.trans, self.delete)
# placeholder for translation
def _(foo):
return foo
MODULE_CACHE = {}
SIGNATURE_CACHE = {}
_re_kernel = re.compile(r'(vmlinu[xz]|kernel.img)')
_re_initrd = re.compile(r'(initrd(.*).img|ramdisk.image.gz)')
_re_is_mac = re.compile(':'.join(('[0-9A-Fa-f][0-9A-Fa-f]',) * 6) + '$')
_re_is_ibmac = re.compile(':'.join(('[0-9A-Fa-f][0-9A-Fa-f]',) * 20) + '$')
# all logging from utils.die goes to the main log even if there
# is another log.
main_logger = None # the logger will be lazy loaded later
def die(logger, msg):
global main_logger
if main_logger is None:
main_logger = clogger.Logger()
# log the exception once in the per-task log or the main
# log if this is not a background op.
try:
raise CX(msg)
except:
if logger is not None:
log_exc(logger)
else:
log_exc(main_logger)
# now re-raise it so the error can fail the operation
raise CX(msg)
def log_exc(logger):
"""
Log an exception.
"""
(t, v, tb) = sys.exc_info()
logger.info("Exception occured: %s" % t)
logger.info("Exception value: %s" % v)
logger.info("Exception Info:\n%s" % string.join(traceback.format_list(traceback.extract_tb(tb))))
def get_exc(exc, full=True):
(t, v, tb) = sys.exc_info()
buf = ""
try:
getattr(exc, "from_cobbler")
buf = str(exc)[1:-1] + "\n"
except:
if not full:
buf = buf + str(t)
buf = "%s\n%s" % (buf, v)
if full:
buf = buf + "\n" + "\n".join(traceback.format_list(traceback.extract_tb(tb)))
return buf
def cheetah_exc(exc, full=False):
lines = get_exc(exc).split("\n")
buf = ""
for l in lines:
buf = buf + "# %s\n" % l
return CHEETAH_ERROR_DISCLAIMER + buf
def trace_me():
x = traceback.extract_stack()
bar = string.join(traceback.format_list(x))
return bar
def pretty_hex(ip, length=8):
"""
Pads an IP object with leading zeroes so that the result is
_length_ hex digits. Also do an upper().
"""
hexval = "%x" % ip.value
if len(hexval) < length:
hexval = '0' * (length - len(hexval)) + hexval
return hexval.upper()
def get_host_ip(ip, shorten=True):
"""
Return the IP encoding needed for the TFTP boot tree.
"""
ip = netaddr.ip.IPAddress(ip)
cidr = netaddr.ip.IPNetwork(ip)
if len(cidr) == 1: # Just an IP, e.g. a /32
return pretty_hex(ip)
else:
pretty = pretty_hex(cidr[0])
if not shorten or len(cidr) <= 8:
# not enough to make the last nibble insignificant
return pretty
else:
cutoff = (32 - cidr.prefixlen) / 4
return pretty[0:-cutoff]
def _IP(ip):
"""
Returns a netaddr.IP object representing ip.
If ip is already an netaddr.IP instance just return it.
Else return a new instance
"""
ip_class = netaddr.ip.IPAddress
if isinstance(ip, ip_class) or ip == "":
return ip
else:
return ip_class(ip)
def get_config_filename(sys, interface):
"""
The configuration file for each system pxe uses is either
a form of the MAC address of the hex version of the IP. If none
of that is available, just use the given name, though the name
given will be unsuitable for PXE configuration (For this, check
system.is_management_supported()). This same file is used to store
system config information in the Apache tree, so it's still relevant.
"""
interface = str(interface)
if interface not in sys.interfaces:
return None
if sys.name == "default":
return "default"
mac = sys.get_mac_address(interface)
ip = sys.get_ip_address(interface)
if mac is not None and mac != "":
return "01-" + "-".join(mac.split(":")).lower()
elif ip is not None and ip != "":
return get_host_ip(ip)
else:
return sys.name
def is_ip(strdata):
"""
Return whether the argument is an IP address.
"""
try:
_IP(strdata)
except:
return False
return True
def is_mac(strdata):
"""
Return whether the argument is a mac address.
"""
if strdata is None:
return False
return bool(_re_is_mac.match(strdata) or _re_is_ibmac.match(strdata))
def get_random_mac(api_handle, virt_type="xenpv"):
"""
Generate a random MAC address.
from xend/server/netif.py
return: MAC address string
"""
if virt_type.startswith("vmware"):
mac = [
0x00, 0x50, 0x56,
random.randint(0x00, 0x3f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff)
]
elif virt_type.startswith("xen") or virt_type.startswith("qemu") or virt_type.startswith("kvm"):
mac = [
0x00, 0x16, 0x3e,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff)
]
else:
raise CX("virt mac assignment not yet supported")
mac = ':'.join(map(lambda x: "%02x" % x, mac))
systems = api_handle.systems()
while (systems.find(mac_address=mac)):
mac = get_random_mac(api_handle)
return mac
def resolve_ip(strdata):
"""
Resolve the IP address and handle errors...
"""
try:
return socket.gethostbyname(strdata)
except:
return None
def find_matching_files(directory, regex):
"""
Find all files in a given directory that match a given regex.
Can't use glob directly as glob doesn't take regexen.
"""
files = glob.glob(os.path.join(directory, "*"))
results = []
for f in files:
if regex.match(os.path.basename(f)):
results.append(f)
return results
def find_highest_files(directory, unversioned, regex):
"""
Find the highest numbered file (kernel or initrd numbering scheme)
in a given directory that matches a given pattern. Used for
auto-booting the latest kernel in a directory.
"""
files = find_matching_files(directory, regex)
get_numbers = re.compile(r'(\d+).(\d+).(\d+)')
def max2(a, b):
"""Returns the larger of the two values"""
av = get_numbers.search(os.path.basename(a)).groups()
bv = get_numbers.search(os.path.basename(b)).groups()
ret = cmp(av[0], bv[0]) or cmp(av[1], bv[1]) or cmp(av[2], bv[2])
if ret < 0:
return b
return a
if len(files) > 0:
return reduce(max2, files)
# couldn't find a highest numbered file, but maybe there
# is just a 'vmlinuz' or an 'initrd.img' in this directory?
last_chance = os.path.join(directory, unversioned)
if os.path.exists(last_chance):
return last_chance
return None
def find_kernel(path):
"""
Given a directory or a filename, find if the path can be made
to resolve into a kernel, and return that full path if possible.
"""
if path is None:
return None
if os.path.isfile(path):
# filename = os.path.basename(path)
# if _re_kernel.match(filename):
# return path
# elif filename == "vmlinuz":
# return path
return path
elif os.path.isdir(path):
return find_highest_files(path, "vmlinuz", _re_kernel)
# For remote URLs we expect an absolute path, and will not
# do any searching for the latest:
elif file_is_remote(path) and remote_file_exists(path):
return path
return None
def remove_yum_olddata(path, logger=None):
"""
Delete .olddata files that might be present from a failed run
of createrepo.
# FIXME: verify this is still being used
"""
trythese = [
".olddata",
".repodata/.olddata",
"repodata/.oldata",
"repodata/repodata"
]
for pathseg in trythese:
olddata = os.path.join(path, pathseg)
if os.path.exists(olddata):
if logger is not None:
logger.info("removing: %s" % olddata)
shutil.rmtree(olddata, ignore_errors=False, onerror=None)
def find_initrd(path):
"""
Given a directory or a filename, see if the path can be made
to resolve into an intird, return that full path if possible.
"""
# FUTURE: try to match kernel/initrd pairs?
if path is None:
return None
if os.path.isfile(path):
# filename = os.path.basename(path)
# if _re_initrd.match(filename):
# return path
# if filename == "initrd.img" or filename == "initrd":
# return path
return path
elif os.path.isdir(path):
return find_highest_files(path, "initrd.img", _re_initrd)
# For remote URLs we expect an absolute path, and will not
# do any searching for the latest:
elif file_is_remote(path) and remote_file_exists(path):
return path
return None
def find_kickstart(url):
"""
Check if a kickstart url looks like an http, ftp, nfs or local path.
If a local path is used, cobbler will copy the kickstart and serve
it over http.
Return None if the url format does not look valid.
"""
if url is None:
return None
x = url.lstrip()
for y in ["http://", "nfs://", "ftp://", "/"]:
# make sure we get a lower-case protocol without
# affecting the rest of the string
x = re.sub(r"(?i)%s" % y, y, x, count=1)
if x.startswith(y):
if x.startswith("/") and not os.path.isfile(x):
return None
return x
return None
def read_file_contents(file_location, logger=None, fetch_if_remote=False):
"""
Reads the contents of a file, which could be referenced locally
or as a URI.
Returns None if file is remote and templating of remote files is
disabled.
Throws a FileNotFoundException if the file does not exist at the
specified location.
"""
# Local files:
if file_location.startswith("/"):
if not os.path.exists(file_location):
if logger:
logger.warning("File does not exist: %s" % file_location)
raise FileNotFoundException("%s: %s" % (_("File not found"), file_location))
try:
f = open(file_location)
data = f.read()
f.close()
return data
except:
if logger:
log_exc(logger)
raise
# Remote files:
if not fetch_if_remote:
return None
if file_is_remote(file_location):
try:
handler = urllib2.urlopen(file_location)
data = handler.read()
handler.close()
return data
except urllib2.HTTPError:
# File likely doesn't exist
if logger:
logger.warning("File does not exist: %s" % file_location)
raise FileNotFoundException("%s: %s" % (_("File not found"), file_location))
def remote_file_exists(file_url):
""" Return True if the remote file exists. """
try:
handler = urllib2.urlopen(file_url)
handler.close()
return True
except urllib2.HTTPError:
# File likely doesn't exist
return False
def file_is_remote(file_location):
"""
Returns true if the file is remote and referenced via a protocol
we support.
"""
# TODO: nfs and ftp ok too?
file_loc_lc = file_location.lower()
for prefix in ["http://"]:
if file_loc_lc.startswith(prefix):
return True
return False
def input_string_or_list(options):
"""
Accepts a delimited list of stuff or a list, but always returns a list.
"""
if options == "<<inherit>>":
return "<<inherit>>"
if options is None or options == "" or options == "delete":
return []
elif isinstance(options, list):
return options
elif isinstance(options, basestring):
tokens = shlex.split(options)
return tokens
else:
raise CX(_("invalid input type"))
def input_string_or_hash(options, allow_multiples=True):
"""
Older cobbler files stored configurations in a flat way, such that all values for strings.
Newer versions of cobbler allow dictionaries. This function is used to allow loading
of older value formats so new users of cobbler aren't broken in an upgrade.
"""
if options == "<<inherit>>":
options = {}
if options is None or options == "delete":
return (True, {})
elif isinstance(options, list):
raise CX(_("No idea what to do with list: %s") % options)
elif isinstance(options, basestring):
new_dict = {}
tokens = shlex.split(options)
for t in tokens:
tokens2 = t.split("=", 1)
if len(tokens2) == 1:
# this is a singleton option, no value
key = tokens2[0]
value = None
else:
key = tokens2[0]
value = tokens2[1]
# if we're allowing multiple values for the same key,
# check to see if this token has already been
# inserted into the dictionary of values already
if key in new_dict.keys() and allow_multiples:
# if so, check to see if there is already a list of values
# otherwise convert the dictionary value to an array, and add
# the new value to the end of the list
if isinstance(new_dict[key], list):
new_dict[key].append(value)
else:
new_dict[key] = [new_dict[key], value]
else:
new_dict[key] = value
# make sure we have no empty entries
new_dict.pop('', None)
return (True, new_dict)
elif isinstance(options, dict):
options.pop('', None)
return (True, options)
else:
raise CX(_("invalid input type"))
def input_boolean(value):
value = str(value)
if value.lower() in ["true", "1", "on", "yes", "y"]:
return True
else:
return False
def update_settings_file(data):
if 1:
# clogger.Logger().debug("in update_settings_file(): value is: %s" % str(value))
settings_file = file("/etc/cobbler/settings", "w")
yaml.safe_dump(data, settings_file)
settings_file.close()
return True
# except:
# return False
def grab_tree(api_handle, obj):
"""
Climb the tree and get every node.
"""
settings = api_handle.settings()
results = [obj]
parent = obj.get_parent()
while parent is not None:
results.append(parent)
parent = parent.get_parent()
results.append(settings)
return results
def blender(api_handle, remove_hashes, root_obj):
"""
Combine all of the data in an object tree from the perspective
of that point on the tree, and produce a merged hash containing
consolidated data.
"""
settings = api_handle.settings()
tree = grab_tree(api_handle, root_obj)
tree.reverse() # start with top of tree, override going down
results = {}
for node in tree:
__consolidate(node, results)
# hack -- s390 nodes get additional default kernel options
arch = results.get("arch", "?")
if arch.startswith("s390"):
keyz = settings.kernel_options_s390x.keys()
for k in keyz:
if k not in results:
results["kernel_options"][k] = settings.kernel_options_s390x[k]
# Get topmost object to determine which breed we're dealing with
parent = root_obj.get_parent()
if parent is None:
parent = root_obj
while parent.COLLECTION_TYPE is "profile" or parent.COLLECTION_TYPE is "system":
parent = parent.get_parent()
breed = parent.breed
if breed == "redhat":
# determine if we have room to add kssendmac to the kernel options line
kernel_txt = hash_to_string(results["kernel_options"])
if len(kernel_txt) < 244:
results["kernel_options"]["kssendmac"] = None
# convert post kernel options to string
if "kernel_options_post" in results:
results["kernel_options_post"] = hash_to_string(results["kernel_options_post"])
# make interfaces accessible without Cheetah-voodoo in the templates
# EXAMPLE: $ip == $ip0, $ip1, $ip2 and so on.
if root_obj.COLLECTION_TYPE == "system":
for (name, interface) in root_obj.interfaces.iteritems():
for key in interface.keys():
results["%s_%s" % (key, name)] = interface[key]
# just to keep templates backwards compatibile
if name == "intf0":
# prevent stomping on profile variables, which really only happens
# with the way we check for virt_bridge, which is a profile setting
# and an interface setting
if key not in results:
results[key] = interface[key]
# if the root object is a profile or system, add in all
# repo data for repos that belong to the object chain
if root_obj.COLLECTION_TYPE in ("profile", "system"):
repo_data = []
for r in results.get("repos", []):
repo = api_handle.find_repo(name=r)
if repo:
repo_data.append(repo.to_datastruct())
# FIXME: sort the repos in the array based on the
# repo priority field so that lower priority
# repos come first in the array
results["repo_data"] = repo_data
http_port = results.get("http_port", 80)
if http_port not in (80, "80"):
results["http_server"] = "%s:%s" % (results["server"], http_port)
else:
results["http_server"] = results["server"]
mgmt_parameters = results.get("mgmt_parameters", {})
mgmt_parameters.update(results.get("ks_meta", {}))
results["mgmt_parameters"] = mgmt_parameters
# sanitize output for koan and kernel option lines, etc
if remove_hashes:
results = flatten(results)
# the password field is inputed as escaped strings but Cheetah
# does weird things when expanding it due to multiple dollar signs
# so this is the workaround
if "default_password_crypted" in results:
results["default_password_crypted"] = results["default_password_crypted"].replace("\$", "$")
# add in some variables for easier templating
# as these variables change based on object type
if "interfaces" in results:
# is a system object
results["system_name"] = results["name"]
results["profile_name"] = results["profile"]
if "distro" in results:
results["distro_name"] = results["distro"]
elif "image" in results:
results["distro_name"] = "N/A"
results["image_name"] = results["image"]
elif "distro" in results:
# is a profile or subprofile object
results["profile_name"] = results["name"]
results["distro_name"] = results["distro"]
elif "kernel" in results:
# is a distro object
results["distro_name"] = results["name"]
elif "file" in results:
# is an image object
results["distro_name"] = "N/A"
results["image_name"] = results["name"]
return results
def flatten(data):
# convert certain nested hashes to strings.
# this is only really done for the ones koan needs as strings
# this should not be done for everything
if data is None:
return None
if "environment" in data:
data["environment"] = hash_to_string(data["environment"])
if "kernel_options" in data:
data["kernel_options"] = hash_to_string(data["kernel_options"])
if "kernel_options_post" in data:
data["kernel_options_post"] = hash_to_string(data["kernel_options_post"])
if "yumopts" in data:
data["yumopts"] = hash_to_string(data["yumopts"])
if "ks_meta" in data:
data["ks_meta"] = hash_to_string(data["ks_meta"])
if "template_files" in data:
data["template_files"] = hash_to_string(data["template_files"])
if "boot_files" in data:
data["boot_files"] = hash_to_string(data["boot_files"])
if "fetchable_files" in data:
data["fetchable_files"] = hash_to_string(data["fetchable_files"])
if "repos" in data and isinstance(data["repos"], list):
data["repos"] = " ".join(data["repos"])
if "rpm_list" in data and isinstance(data["rpm_list"], list):
data["rpm_list"] = " ".join(data["rpm_list"])
# note -- we do not need to flatten "interfaces" as koan does not expect
# it to be a string, nor do we use it on a kernel options line, etc...
return data
def uniquify(seq):
# credit: http://www.peterbe.com/plog/uniqifiers-benchmark
# FIXME: if this is actually slower than some other way, overhaul it
seen = {}
result = []
for item in seq:
if item in seen:
continue
seen[item] = 1
result.append(item)
return result
def __consolidate(node, results):
"""
Merge data from a given node with the aggregate of all
data from past scanned nodes. Hashes and arrays are treated
specially.
"""
node_data = node.to_datastruct()
# if the node has any data items labelled <<inherit>> we need to expunge them.
# so that they do not override the supernodes.
node_data_copy = {}
for key in node_data:
value = node_data[key]
if value != "<<inherit>>":
if isinstance(value, dict):
node_data_copy[key] = value.copy()
elif isinstance(value, list):
node_data_copy[key] = value[:]
else:
node_data_copy[key] = value
for field in node_data_copy:
data_item = node_data_copy[field]
if field in results:
# now merge data types seperately depending on whether they are hash, list,
# or scalar.
fielddata = results[field]
if isinstance(fielddata, dict):
# interweave hash results
results[field].update(data_item.copy())
elif isinstance(fielddata, list) or isinstance(fielddata, tuple):
# add to lists (cobbler doesn't have many lists)
# FIXME: should probably uniqueify list after doing this
results[field].extend(data_item)
results[field] = uniquify(results[field])
else:
# distro field gets special handling, since we don't
# want to overwrite it ever.
# FIXME: should the parent's field too? It will be over-
# written if there are multiple sub-profiles in
# the chain of inheritance
if field != "distro":
results[field] = data_item
else:
results[field] = data_item
# now if we have any "!foo" results in the list, delete corresponding
# key entry "foo", and also the entry "!foo", allowing for removal
# of kernel options set in a distro later in a profile, etc.
hash_removals(results, "kernel_options")
hash_removals(results, "kernel_options_post")
hash_removals(results, "ks_meta")
hash_removals(results, "template_files")
hash_removals(results, "boot_files")
hash_removals(results, "fetchable_files")
def hash_removals(results, subkey):
if subkey not in results:
return
scan = results[subkey].keys()
for k in scan:
if str(k).startswith("!") and k != "!":
remove_me = k[1:]
if remove_me in results[subkey]:
del results[subkey][remove_me]
del results[subkey][k]
def hash_to_string(hash):
"""
Convert a hash to a printable string.
used primarily in the kernel options string
and for some legacy stuff where koan expects strings
(though this last part should be changed to hashes)
"""
buffer = ""
if not isinstance(hash, dict):
return hash
for key in hash:
value = hash[key]
if not value:
buffer = buffer + str(key) + " "
elif isinstance(value, list):
# this value is an array, so we print out every
# key=value
for item in value:
buffer = buffer + str(key) + "=" + str(item) + " "
else:
buffer = buffer + str(key) + "=" + str(value) + " "
return buffer
def rsync_files(src, dst, args, logger=None, quiet=True):
"""
Sync files from src to dst. The extra arguments specified
by args are appended to the command
"""
if args is None:
args = ''
RSYNC_CMD = "rsync -a %%s '%%s' %%s %s --exclude-from=/etc/cobbler/rsync.exclude" % args
if quiet:
RSYNC_CMD += " --quiet"
else:
RSYNC_CMD += " --progress"
# Make sure we put a "/" on the end of the source
# and destination to make sure we don't cause any
# rsync weirdness
if not dst.endswith("/"):
dst = "%s/" % dst
if not src.endswith("/"):
src = "%s/" % src
spacer = ""
if not src.startswith("rsync://") and not src.startswith("/"):
spacer = ' -e "ssh" '
rsync_cmd = RSYNC_CMD % (spacer, src, dst)
try:
res = subprocess_call(logger, rsync_cmd)
if res != 0:
die(logger, "Failed to run the rsync command: '%s'" % rsync_cmd)
except:
return False
return True
def run_this(cmd, args, logger):
"""
A simple wrapper around subprocess calls.
"""
my_cmd = cmd % args
rc = subprocess_call(logger, my_cmd, shell=True)
if rc != 0:
die(logger, "Command failed")
def run_triggers(api, ref, globber, additional=[], logger=None):
"""
Runs all the trigger scripts in a given directory.
ref can be a cobbler object, if not None, the name will be passed
to the script. If ref is None, the script will be called with
no argumenets. Globber is a wildcard expression indicating which
triggers to run. Example: "/var/lib/cobbler/triggers/blah/*"
As of Cobbler 1.5.X, this also runs cobbler modules that match the globbing paths.
"""
# Python triggers first, before shell
if logger is not None:
logger.debug("running python triggers from %s" % globber)
modules = api.get_modules_in_category(globber)
for m in modules:
arglist = []
if ref:
arglist.append(ref.name)
for x in additional:
arglist.append(x)
if logger is not None:
logger.debug("running python trigger %s" % m.__name__)
rc = m.run(api, arglist, logger)
if rc != 0:
raise CX("cobbler trigger failed: %s" % m.__name__)
# now do the old shell triggers, which are usually going to be slower, but are easier to write
# and support any language
if logger is not None:
logger.debug("running shell triggers from %s" % globber)
triggers = glob.glob(globber)
triggers.sort()
for file in triggers:
try:
if file.startswith(".") or file.find(".rpm") != -1:
# skip dotfiles or .rpmnew files that may have been installed
# in the triggers directory
continue
arglist = [file]
if ref:
arglist.append(ref.name)
for x in additional:
if x:
arglist.append(x)
if logger is not None:
logger.debug("running shell trigger %s" % file)
rc = subprocess_call(logger, arglist, shell=False) # close_fds=True)
except:
if logger is not None:
logger.warning("failed to execute trigger: %s" % file)
continue
if rc != 0:
raise CX(_("cobbler trigger failed: %(file)s returns %(code)d") % {"file": file, "code": rc})
def get_family():
"""
Get family of running operating system.
Family is the base Linux distribution of a Linux distribution, with a set of common
"""
redhat_list = ("red hat", "redhat", "scientific linux", "fedora", "centos")
dist = check_dist()
for item in redhat_list:
if item in dist:
return "redhat"
if dist in ("debian", "ubuntu"):
return "debian"
if "suse" in dist:
return "suse"
return dist
def check_dist():
"""
Determines what distro we're running under.
"""
import platform
try:
return platform.linux_distribution()[0].lower().strip()
except AttributeError:
return platform.dist()[0].lower().strip()