forked from opensvc/opensvc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostinstall
executable file
·1579 lines (1441 loc) · 49.6 KB
/
postinstall
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 python
import os
import errno
import shutil
import glob
import sys
import tempfile
import inspect
import time
try:
sysname, nodename, x, x, machine = os.uname()
except:
import platform
sysname, nodename, x, x, machine, x = platform.uname()
p0755 = int("0755", 8)
p0700 = int("0700", 8)
p0644 = int("0644", 8)
utf8patterns = ['UTF-8', 'UTF8', 'utf-8', 'utf8']
postinstall_d = sys.path[0]
if '/catalog/' in postinstall_d:
# hpux packaging subsystem executes the postinstall from dir
# /var/tmp/XXXXXXXXX/catalog/opensvc/commands/
postinstall_d = "/usr/share/opensvc/bin"
lsb = True
elif postinstall_d == "/usr/share/opensvc/bin":
lsb = True
else:
# windows install or unix execution from a non-lsb tree (ex: /opt/opensvc/)
lsb = False
if lsb:
pathsbin = "/usr/bin"
pathsvc = None
pathetc = "/etc/opensvc"
pathvar = "/var/lib/opensvc"
pathlck = '/var/lib/opensvc/lock'
pathtmp = "/var/tmp/opensvc"
pathlog = "/var/log/opensvc"
pathbin = "/usr/share/opensvc/bin"
pathlib = "/usr/share/opensvc/opensvc"
pathini = "/usr/share/opensvc/bin/init"
pathusr = None
else:
pathsbin = postinstall_d
pathsvc = os.path.realpath(os.path.join(pathsbin, '..'))
pathetc = os.path.join(pathsvc, 'etc')
pathvar = os.path.join(pathsvc, 'var')
pathlck = os.path.join(pathvar, 'lock')
pathtmp = os.path.join(pathsvc, 'tmp')
pathlog = os.path.join(pathsvc, 'log')
pathbin = postinstall_d
pathlib = os.path.join(pathsvc, 'opensvc')
pathini = os.path.join(pathsvc, 'bin', 'init')
pathusr = os.path.join(pathsvc, 'usr')
def any(iterable):
for element in iterable:
if element:
return True
return False
def make_sure_path_exists(path):
if os.path.exists(path):
return
os.makedirs(path, p0755)
def logit(msg, stdout=False, stderr=False):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
try:
import datetime
timestamp = str(datetime.datetime.now())
except:
timestamp = '?'
osvlog = os.path.join(pathlog, 'postinstall.log')
content = '['+calframe[1][3]+']['+timestamp+'] '+msg
f = open(osvlog, 'a')
f.write(content+'\n')
f.close()
if stdout:
sys.stdout.write(msg+"\n")
if stderr:
sys.stderr.write("error ==> %s\n" % (msg))
def osrun(cmd, stdout=False, stderr=False):
ret = None
if sysname == 'Windows':
logit("cmd [%s]"%cmd, stdout, stderr)
os.system(cmd)
else:
ret = os.WEXITSTATUS(os.system(cmd))
logit("cmd [%s] ret[%s]"%(cmd, ret), stdout, stderr)
if ret is not None:
return ret
make_sure_path_exists(pathlog)
if sysname == 'SunOS':
osvcfmri = 'svc:/site/application/opensvc:boot'
cmd = ['svcs', '-vl', osvcfmri, '2>/dev/null']
ret = osrun(' '.join(cmd))
if ret == 0:
# Solaris install from IPS package with standard FMRI
logit("Solaris postinstall check for first run", stdout=False)
cmd = ['svcprop', '-p', 'boot/firstrun', osvcfmri, '|', 'grep', 'done']
ret = osrun(' '.join(cmd))
if ret == 0:
logit("Solaris postinstall already executed. Exiting.", stdout=False)
sys.exit(0)
logit("\nStarting OpenSVC postinstall\n", stdout=True)
SolarisRootRelocate = False
if sysname == 'SunOS' and "PKG_INSTALL_ROOT" in os.environ and os.environ['PKG_INSTALL_ROOT'] != '/':
logit("SunOS PKG_INSTALL_ROOT <%s>"%(os.environ['PKG_INSTALL_ROOT']))
SolarisRootRelocate = True
variables = {
"pathsvc": pathsvc,
"pathsbin": pathsbin,
"pathbin": pathbin,
"pathetc": pathetc,
"pathvar": pathvar,
"pathtmp": pathtmp,
"pathlib": pathlib,
"pathlog": pathlog,
"pathusr": pathusr,
"SolarisRootRelocate": SolarisRootRelocate
}
for key in variables:
logit("var %s <%s>"%(key, variables[key]))
def install_cron():
logit("begin")
if sysname == 'Windows':
logit("windows not applicable")
return
else:
return install_cron_unix()
def install_winservice():
if sysname != 'Windows':
return
logit("begin")
logit("install OpenSVC agent winservice", stdout=True)
schedstop()
time.sleep(3)
schedremove()
schedinstall()
schedstart()
def schedremove():
logit("begin")
cmd = ' remove'
schedcmd(cmd)
def schedstart():
logit("begin")
cmd = ' start'
schedcmd(cmd)
def schedstop():
logit("begin")
cmd = ' stop'
schedcmd(cmd)
def schedinstall():
logit("begin")
cmd = ''
cmd += ' --username LocalSystem'
cmd += ' --startup auto'
cmd += ' install\n'
schedcmd(cmd)
def schedcmd(_cmd):
logit("begin")
logit("_cmd %s"%_cmd)
rc = '"'+sys.executable+'" "'+os.path.join(pathlib, 'osvcd_winservice.py')+'"'
cmd = "@echo off\n"
cmd += rc
cmd += _cmd
fd, fname = tempfile.mkstemp(dir=pathtmp, suffix='.cmd')
f = os.fdopen(fd, 'w')
f.write(cmd)
f.close()
import subprocess
subprocess.call([fname])
os.unlink(fname)
def save_file(infile):
logit("begin")
logit("infile <%s>"%infile)
if not os.path.exists(infile):
return True
try:
import datetime
timestamp = str(datetime.datetime.now())
tmp = timestamp.replace(" ", ".")
ts = tmp.replace(":", ".")
except:
ts = 'opensvc.postinstall'
ofname = os.path.basename(infile)
logit("ofname <%s>"%ofname)
nfname = ofname + '.crontab.' + ts
logit("nfname <%s>"%nfname)
outfile = os.path.join(os.sep, pathtmp, nfname)
logit("outfile <%s>"%outfile)
logit("saving file <%s> to <%s>"%(infile, outfile), stdout=True)
try:
shutil.copyfile(infile, outfile)
except:
import traceback
traceback.print_exc()
logit("error while trying to save file <%s> to <%s>"%(infile, outfile), stderr=True)
return False
return True
def install_cron_unix():
logit("begin")
"""install opensvc cron jobs
"""
remove_entries = [
'bin/nodemgr schedulers',
'bin/nodemgr compliance check',
'bin/svcmon ',
'bin/cron/opensvc',
'svcmgr resource monitor',
'svcmgr resource_monitor',
'nodemgr cron',
'perfagt.'+sysname,
]
purge = []
root_crontab = False
""" order of preference
"""
if sysname == 'SunOS':
if SolarisRootRelocate is True:
suncron = os.environ["PKG_INSTALL_ROOT"] + '/var/spool/cron/crontabs/root'
root_crontab_locs = suncron
else:
root_crontab_locs = ['/var/spool/cron/crontabs/root']
else:
root_crontab_locs = [
'/etc/cron.d/opensvc',
'/var/spool/cron/crontabs/root',
'/var/spool/cron/root',
'/var/cron/tabs/root',
'/usr/lib/cron/tabs/root',
]
for loc in root_crontab_locs:
logit("looping crontab location <%s>"%loc)
if os.path.exists(os.path.dirname(loc)):
if not root_crontab:
root_crontab = loc
logit("identifying <%s> as root crontab"%root_crontab)
elif os.path.exists(loc):
logit("adding <%s> to purge table"%loc)
purge.append(loc)
if not root_crontab:
logit("no root crontab found in usual locations <%s>"%str(root_crontab_locs), stderr=True)
return False
new = False
if os.path.exists(root_crontab):
try:
f = open(root_crontab, 'r')
new = f.readlines()
f.close()
logit("loaded crontab <%s> content <%s>"%(root_crontab, new))
except:
f.close()
import traceback
traceback.print_exc()
if not new:
logit("empty crontab found. skipping purge.", stderr=False)
if os.path.exists(root_crontab) and os.stat(root_crontab).st_size == 0:
logit("removing crontab %s"%root_crontab)
os.unlink(root_crontab)
return False
i = -1
for line in new:
i += 1
for re in remove_entries:
logit("looping re <%s>"%re)
if line.find(re) != -1:
logit("delete line <%s> from <%s>"%(re, root_crontab))
del new[i]
logit("saving crontab <%s>"%root_crontab)
try:
save_file(root_crontab)
except:
logit('Error while trying to backup crontab <%s>. skipping crontab update'%(root_crontab), stderr=True)
return False
logit("updating crontab <%s> with content <%s>"%(root_crontab, new))
try:
f = open(root_crontab, 'w')
f.write(''.join(new))
f.close()
except:
logit("error while trying to update crontab %s"%root_crontab, stderr=True)
f.close()
import traceback
traceback.print_exc()
""" Activate changes (actually only needed on HP-UX)
"""
if sysname in ("HP-UX", "SunOS") and root_crontab.find('/var/spool/') != -1:
logit("crontab activation requested")
cmd = ['crontab', root_crontab]
ret = osrun(' '.join(cmd))
for loc in purge:
try:
f = open(loc, 'r')
new = [line for line in f.readlines() if line.find('opensvc.daily') == -1 and line.find('svcmon --updatedb') == -1]
f.close()
f = open(loc, 'w')
f.write(''.join(new))
f.close()
except:
f.close()
import traceback
traceback.print_exc()
""" Clean up old standard file locations
"""
for f in ['/etc/cron.daily/opensvc', '/etc/cron.daily/opensvc.daily']:
if os.path.exists(f):
logit("removing %s"%f)
os.unlink(f)
def activate_chkconfig(svc):
logit("begin")
cmd = ['chkconfig', '--add', svc]
ret = osrun(' '.join(cmd))
if ret > 0:
return False
return True
def activate_systemd(launcher):
logit("begin")
systemdsvcs = ['opensvc-agent.service', 'opensvc-services.service']
for systemdsvc in systemdsvcs:
_activate_systemd(systemdsvc)
def _activate_systemd(systemdsvc):
if not os.path.islink('/lib') and os.path.isdir('/lib/systemd/system'):
systemd_unit_path = '/lib/systemd/system'
else:
systemd_unit_path = '/usr/lib/systemd/system'
systemd_unit_paths = [
systemd_unit_path,
'/etc/systemd/system/',
]
installed = False
for path in systemd_unit_paths:
if os.path.exists(os.path.dirname(path)):
# populate systemd tree with opensvc unit file
src = os.path.join(pathini, "systemd."+systemdsvc)
dst = os.path.join(path, systemdsvc)
try:
shutil.copyfile(src, dst)
os.chmod(dst, p0644)
installed = True
break
except IOError as exc:
if exc.errno == 30:
continue
logit("issue met while trying to install systemd unit file: %s"%str(exc), stderr=True)
except OSError as exc:
if exc.errno == 30:
continue
logit("issue met while trying to install systemd unit file: %s"%str(exc), stderr=True)
except Exception as exc:
logit("issue met while trying to install systemd unit file: %s"%str(exc), stderr=True)
if installed is not True:
logit("issue met while trying to identify suitable systemd unit file location", stderr=True)
else:
logit("installing %s systemd unit file in %s"%(systemdsvc, path), stdout=True)
# reset paths in ExecStart and ExecStop
osrun("sed -i 's@/usr/share/opensvc/bin@"+pathbin+"@' "+dst)
# reset path in PIDFile
osrun("sed -i 's@/var/lib/opensvc@"+pathvar+"@' "+dst)
# reload systemd configuration
logit("reloading systemd configuration", stdout=True)
cmd = ['systemctl', '-q', 'daemon-reload']
ret = osrun(' '.join(cmd))
if ret > 0:
logit("issue met during systemctl reload", stderr=True)
# enable opensvc agent startup through systemd
logit("enabling systemd configuration")
cmd = ['systemctl', '-q', 'disable', systemdsvc]
ret = osrun(' '.join(cmd))
cmd = ['systemctl', '-q', 'enable', systemdsvc]
ret = osrun(' '.join(cmd))
if ret > 0:
logit("issue met during systemctl enable", stderr=True)
def systemd_mgmt():
logit("begin")
cmd = ['systemctl', '--version', '>>/dev/null', '2>&1']
ret = osrun(' '.join(cmd))
if ret > 0:
return False
return True
def activate_ovm(launcher):
logit("begin")
activate_chkconfig('zopensvc')
def activate_redhat(launcher):
logit("begin")
activate_chkconfig('opensvc')
def activate_debian(launcher):
logit("begin")
cmd = ['update-rc.d', '-f', 'opensvc', 'remove']
ret = osrun(' '.join(cmd))
if ret > 0:
logit("issue met while trying to remove opensvc rc launchers", stderr=True)
return False
cmd = ['update-rc.d', 'opensvc', 'defaults']
ret = osrun(' '.join(cmd))
if ret > 0:
logit("issue met while trying to install opensvc rc launchers", stderr=True)
return False
return True
def activate_hpux(launcher):
logit("begin")
rc = "/sbin/init.d/opensvc"
links = ["/sbin/rc1.d/K010opensvc", "/sbin/rc2.d/K010opensvc", "/sbin/rc3.d/S990opensvc"]
if os.path.exists("/sbin/rc2.d/S990opensvc"):
logit("removing /sbin/rc2.d/S990opensvc")
os.unlink("/sbin/rc2.d/S990opensvc")
for l in links:
if not os.path.islink(l):
if os.path.exists(l):
logit("removing %s"%l)
os.unlink(l)
logit("create link %s -> %s"%(l, rc))
os.symlink(rc, l)
try:
f = open("/etc/rc.config.d/opensvc", "w")
f.write("RUN_OPENSVC=1\n")
f.close()
except:
logit("issue met while trying to install rc.config.d opensvc file", stderr=True)
f.close()
import traceback
traceback.print_exc()
return True
def activate_AIX(launcher):
logit("begin")
rc = "/etc/rc.d/init.d/opensvc"
links = ["/etc/rc.d/rc2.d/S990opensvc"]
for l in links:
if not os.path.islink(l):
if os.path.exists(l):
logit("removing %s"%l)
os.unlink(l)
logit("create link %s -> %s"%(l, rc))
os.symlink(rc, l)
return True
def activate_OSF1(launcher):
rc = "/sbin/init.d/opensvc"
links = ["/sbin/rc0.d/K010opensvc", "/sbin/rc2.d/K010opensvc", "/sbin/rc3.d/S990opensvc"]
for l in links:
if not os.path.islink(l):
if os.path.exists(l):
logit("removing %s"%l)
os.unlink(l)
logit("symlinking %s and %s"%(rc, l))
os.symlink(rc, l)
return True
def activate_SunOS(launcher):
logit("begin")
if SolarisRootRelocate is True:
rc = "/etc/init.d/opensvc"
links = [os.environ["PKG_INSTALL_ROOT"] + "/etc/rc0.d/K00opensvc", os.environ["PKG_INSTALL_ROOT"] + "/etc/rc3.d/S99opensvc"]
else:
rc = "/etc/init.d/opensvc"
links = ["/etc/rc0.d/K00opensvc", "/etc/rc3.d/S99opensvc"]
logit("rc <%s>"%rc)
for l in links:
logit("link <%s>"%l)
if not os.path.islink(l):
if os.path.exists(l):
logit("removing %s"%l)
os.unlink(l)
logit("symlinking %s and %s"%(rc, l))
os.symlink(rc, l)
return True
def activate_openrc(launcher):
logit("begin")
cmd = ['rc-update', '--help', '>>/dev/null 2>&1']
ret = osrun(' '.join(cmd))
if ret == 127:
logit("rc-update command not found, skipping opensvc init setup", stdout=True)
return False
cmd = ['rc-update', 'delete', '-a', 'opensvc']
ret = osrun(' '.join(cmd))
cmd = ['rc-update', 'add', 'opensvc', 'default']
ret = osrun(' '.join(cmd))
if ret > 0:
logit("issue met while trying to install opensvc rc launchers", stderr=True)
return False
return True
def activate_FreeBSD(launcher):
logit("begin")
cmd = ['sysrc', '-f', '/etc/rc.conf.d/opensvc', 'opensvc_enable=YES']
ret = osrun(' '.join(cmd))
if ret > 0:
logit("issue met while trying to install opensvc rc launchers", stderr=True)
return False
return True
def activate_Darwin(launcher):
logit("begin")
return True
def update_file(filename, srctext, replacetext):
logit("begin")
""" replace into filename srctext by replacetext
"""
import fileinput
for line in fileinput.input(filename, inplace=1):
if line.rstrip('\n') == srctext.rstrip('\n'):
line = replacetext
msg = line.rstrip('\n')
logit(msg, stdout=True)
fileinput.close()
def get_keyval_in(key, path2f):
logit("begin")
val = None
try:
f = open(path2f, 'r')
data = f.readlines()
f.close()
except:
f.close()
import traceback
traceback.print_exc()
for line in data:
if line.startswith(key):
val=line.split('=')[-1].strip()
logit("found value <%s> for key <%s> in file <%s>"%(val, key, path2f))
break
return val
def is_lang_utf8(file):
logit("begin")
lang = get_keyval_in('LANG', file)
if lang is not None:
if any(pattern in lang for pattern in utf8patterns):
return True
return False
def is_system_locale_utf8():
"""
Check if system locale is utf8
"""
logit("begin")
localetmp = pathtmp + '/locale.postinstall'
cmd = ['locale', '>', localetmp]
ret = osrun(' '.join(cmd))
if ret > 0:
logit("error while trying to query locale with command <%s>"%(cmd), stderr=True)
return False
try:
return is_lang_utf8(localetmp)
finally:
try:
os.unlink(localetmp)
except Exception:
pass
def is_osvc_locale_utf8(file):
"""
Check if osvc locale is utf8
"""
logit("begin")
return is_lang_utf8(file)
def appends2f(str, fname):
try:
f = open(fname, "a")
f.write(str + "\n")
f.close()
logit("added string <%s> to file <%s>"%(str, fname))
except:
logit("issue met while trying to append string <%s> to file <%s>"%(str, fname), stderr=True)
f.close()
import traceback
traceback.print_exc()
def find_locale():
logit("begin")
""" try to identify best utf8 locale
"""
localetmp = pathtmp + '/locale.all'
cmd = ['locale', '-a', '>', localetmp]
ret = osrun(' '.join(cmd))
if ret > 0:
logit("error while trying to build locale list with command <%s>"%(cmd), stderr=True)
return None
data = []
try:
f = open(localetmp, 'r')
while True:
try:
line = f.readline()
except Exception:
break
if not line:
break
data.append(line)
f.close()
except:
f.close()
import traceback
traceback.print_exc()
candidates = []
for l in data:
if any(pattern in l for pattern in utf8patterns):
candidates.append(l.strip())
logit("utf8 locale candidates <%s>"%(candidates))
for l in candidates:
if l.startswith('C'):
return l
for l in candidates:
if l.startswith('en_US'):
return l
for l in candidates:
if l.startswith('en_'):
return l
logit("no suitable utf8 locale found")
return None
def install_locale(path2file):
logit("begin")
""" install utf8 locale
"""
lang = get_keyval_in('LANG', path2file)
if lang is not None:
logit("LANG <%s> already set with non utf8 locale"%(lang), stderr=True)
else:
locale = find_locale()
if locale is not None:
appends2f("LANG=" + locale, path2file)
appends2f("export LANG", path2file)
def install_params(path2file):
logit("begin")
""" install template file with tunable variables
"""
if os.path.exists(path2file):
logit("file %s already present"%path2file)
return
src = os.path.join(pathini, 'opensvc.defaults.parameters')
with open(src, "r") as f:
buff = f.read()
if sys.executable != "/usr/bin/python":
buff += "OSVC_PYTHON=%s\n" % sys.executable
if os.path.join("share", "opensvc", "bin") not in __file__:
root_path = os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
buff += "OSVC_ROOT_PATH=%s\n" % root_path
try:
logit("writing new <%s>"%path2file)
with open(path2file, "w") as f:
f.write(buff)
os.chmod(path2file, p0644)
except:
import traceback
traceback.print_exc()
def os_release():
os_release_f = os.path.join(os.sep, "etc", "os-release")
data = {"ID": "==magic1234"}
if not os.path.exists(os_release_f):
return data
filep = open(os_release_f, "r")
try:
for line in filep.readlines():
line = line.strip("\n")
try:
var, val = line.split("=", 1)
except:
continue
data[var] = val.strip('"')
finally:
filep.close()
return data
def install_rc():
logit("begin")
"""install startup script
"""
params = None
copyrc = True
if reldata["ID"] in ("gentoo"):
rc = '/etc/init.d/opensvc'
params = '/etc/conf.d/opensvc'
src = os.path.join(pathini, 'opensvc.init.openrc')
if systemd_mgmt():
logit("gentoo with systemd")
copyrc = False
activate = activate_systemd
else:
logit("gentoo with openrc")
activate = activate_openrc
elif reldata["ID"] in ("ubuntu", "debian") or os.path.exists('/etc/debian_version'):
rc = '/etc/init.d/opensvc'
params = '/etc/default/opensvc'
src = os.path.join(pathini, 'opensvc.init.debian')
if systemd_mgmt():
logit("debian with systemd")
copyrc = False
activate = activate_systemd
else:
logit("debian with update-rc.d (rely on insserv)")
activate = activate_debian
elif reldata["ID"] == "arch" or os.path.exists('/etc/arch-release'):
rc = '/etc/init.d/opensvc'
params = '/etc/default/opensvc'
src = os.path.join(pathini, 'opensvc.init.debian')
if systemd_mgmt():
logit("arch with systemd")
copyrc = False
activate = activate_systemd
elif reldata["ID"] in ("sles", "caasp") or os.path.exists('/etc/SuSE-release'):
rc = '/etc/init.d/opensvc'
params = '/etc/sysconfig/opensvc'
src = os.path.join(pathini, 'opensvc.init.suse')
if systemd_mgmt():
logit("SuSE with systemd")
copyrc = False
activate = activate_systemd
else:
logit("SuSE with chkconfig (rely on insserv)")
activate = activate_redhat
elif reldata["ID"] in ("alpine") or os.path.exists('/etc/alpine-release'):
rc = '/etc/init.d/opensvc'
params = '/etc/conf.d/opensvc'
src = os.path.join(pathini, 'opensvc.init.openrc')
activate = activate_openrc
elif reldata["ID"] in ("centos", "rhel", "fedora") or os.path.exists('/etc/redhat-release'):
params = '/etc/sysconfig/opensvc'
src = os.path.join(pathini, 'opensvc.init.redhat')
try:
f = open('/etc/redhat-release', 'r')
buff = f.read()
f.close()
except:
buff = ""
if buff.find('Oracle VM server') != -1:
rc = '/etc/init.d/zopensvc'
activate = activate_ovm
else:
rc = '/etc/init.d/opensvc'
if systemd_mgmt():
logit("Red Hat with systemd")
copyrc = False
activate = activate_systemd
else:
logit("Red Hat with chkconfig (rely on insserv)")
activate = activate_redhat
elif sysname == "HP-UX":
rc = '/sbin/init.d/opensvc'
src = os.path.join(pathini, 'opensvc.init.hpux')
activate = activate_hpux
elif sysname == "SunOS":
if SolarisRootRelocate is True:
rc = os.environ["PKG_INSTALL_ROOT"] + '/etc/init.d/opensvc'
params = os.environ["PKG_INSTALL_ROOT"] + '/etc/default/opensvc'
src = os.environ["PKG_INSTALL_ROOT"] + os.path.join(pathini, 'opensvc.init.SunOS')
else:
rc = '/etc/init.d/opensvc'
params = '/etc/default/opensvc'
src = os.path.join(pathini, 'opensvc.init.SunOS')
activate = activate_SunOS
elif sysname == "OSF1":
rc = '/sbin/init.d/opensvc'
src = os.path.join(pathini, 'opensvc.init.OSF1')
activate = activate_OSF1
elif sysname == "FreeBSD":
rc = '/usr/local/etc/rc.d/opensvc'
params = '/etc/defaults/opensvc'
src = os.path.join(pathini, 'opensvc.init.FreeBSD')
activate = activate_FreeBSD
elif sysname == "AIX":
rc = '/etc/rc.d/init.d/opensvc'
src = os.path.join(pathini, 'opensvc.init.AIX')
activate = activate_AIX
elif sysname == "Darwin":
rc = '/Library/LaunchDaemons/com.opensvc.svcmgr.plist'
params = '/etc/defaults/opensvc'
src = os.path.join(pathini, 'darwin.com.opensvc.svcmgr.plist')
activate = activate_Darwin
elif sysname == 'Windows':
return False
else:
logit("could not select an init script: unsupported operating system", stderr=True)
return False
if os.path.islink(rc):
logit("removing link %s"%rc)
os.unlink(rc)
if copyrc:
logit("copying src launcher script to rc")
shutil.copyfile(src, rc)
os.chmod(rc, p0755)
if params is not None and not os.path.exists(params):
logit("installing default parameters file")
install_params(params)
if params is not None:
logit("checking locale setup")
if not is_system_locale_utf8() and not is_osvc_locale_utf8(params):
logit("locale is not utf8")
install_locale(params)
activate(src)
def gen_keys():
logit("begin")
if sysname == 'Windows':
return
home = os.path.expanduser("~root")
logit("home <%s>"%home)
if SolarisRootRelocate is True:
home = os.environ['PKG_INSTALL_ROOT'] + os.path.expanduser("~root")
logit("SunOS and relocatable install home is now <%s>"%home)
sshhome = os.path.join(home, ".ssh")
logit("sshhome <%s>"%sshhome)
if not os.path.exists(sshhome):
logit("create dir %s"%sshhome, stdout=True)
os.makedirs(sshhome, p0700)
priv = os.path.join(sshhome, "id_rsa")
pub = os.path.join(sshhome, "id_rsa.pub")
if os.path.exists(pub) or os.path.exists(priv):
logit("either %s or %s already exist"%(pub, priv))
return
cmd = ['ssh-keygen', '--help', '>>/dev/null 2>&1']
ret = osrun(' '.join(cmd))
if ret == 127:
logit("ssh-keygen command not found, skipping key creation", stdout=True)
return
cmd = ['ssh-keygen', '-t', 'rsa', '-b', '2048', '-P', '""', '-f', priv]
try:
ret = osrun(' '.join(cmd))
except:
logit("Error while trying to generate ssh keys")
def missing_dir(pathd):
logit("begin")
if not os.path.exists(pathd):
logit("create dir %s"%pathd, stdout=True)
os.makedirs(pathd, p0755)
def missing_dirs():
logit("begin")
missing_dir(pathlog)
missing_dir(pathtmp)
missing_dir(pathvar)
missing_dir(pathetc)
missing_dir(pathlck)
def move_env_to_conf():
for fpath in glob.glob(os.path.join(pathetc, "*.env")):
svcname = os.path.basename(fpath)[:-4]
new_basename = svcname+".conf"
new_fpath = os.path.join(pathetc, new_basename)
shutil.move(fpath, new_fpath)
def move_var_files_in_subdirs():
for fpath in glob.glob(os.path.join(pathvar, "last_*")):
dst = os.path.join(pathvar, "node")
if not os.path.exists(dst):
os.makedirs(dst)
fname = os.path.basename(fpath)
new_fpath = os.path.join(dst, fname)
logit("move %s to %s" % (fpath, new_fpath))
shutil.move(fpath, new_fpath)
for fpath in glob.glob(os.path.join(pathvar, "*_last_*")):
fname = os.path.basename(fpath)
svcname = fname.split("_last_")[0]
dst = os.path.join(pathvar, svcname)
if not os.path.exists(dst):
os.makedirs(dst)
fname = fname.replace(svcname+"_", "")
new_fpath = os.path.join(dst, fname)
logit("move %s to %s" % (fpath, new_fpath))
shutil.move(fpath, new_fpath)
for fpath in glob.glob(os.path.join(pathvar, "*.push")):
svcname = os.path.basename(fpath).split(".push")[0]
dst = os.path.join(pathvar, svcname)
if not os.path.exists(dst):
os.makedirs(dst)
fname = "last_pushed_env"
new_fpath = os.path.join(dst, fname)
logit("move %s to %s" % (fpath, new_fpath))
shutil.move(fpath, new_fpath)
def move_usr_to_opt():
logit("begin")
linksvc = os.path.join(os.sep, 'service')
old_pathsvc = os.path.join(os.sep, 'usr', 'local', 'opensvc')
old_pathvar = os.path.join(old_pathsvc, 'var')
old_pathetc = os.path.join(old_pathsvc, 'etc')
if os.path.exists(old_pathvar):
logit("found old var %s"%old_pathvar)
for f in glob.glob(old_pathvar+'/*'):
dst = os.path.join(pathvar, os.path.basename(f))
if os.path.exists(dst) and dst.find('host_mode') == -1:
logit("file %s already exist"%dst)
continue
if os.path.isdir(f):
logit("copying dir %s to %s"%(f, dst))
shutil.copytree(f, dst, symlinks=True)
elif os.path.islink(f):
linkto = os.readlink(f)
logit("create link %s -> %s"%(dst, linkto))
os.symlink(linkto, dst)
else:
logit("copying file %s to %s"%(f, dst))
shutil.copy2(f, dst)
if os.path.exists(old_pathetc):
logit("found old etc %s"%old_pathetc)
for f in glob.glob(old_pathetc+'/*'):
dst = os.path.join(pathetc, os.path.basename(f))
if os.path.exists(dst):
logit("file %s already exist"%dst)
continue
if os.path.islink(f):
linkto = os.readlink(f)
logit("create link %s -> %s"%(dst, linkto))
os.symlink(linkto, dst)
elif os.path.isdir(f):
logit("copying dir %s to %s"%(f, dst))
shutil.copytree(f, dst, symlinks=True)
else:
logit("copying file %s to %s"%(f, dst))
shutil.copy2(f, dst)
if os.path.exists(old_pathsvc):
logit("removing old_pathsvc %s"%old_pathsvc)
shutil.rmtree(old_pathsvc)
if os.path.islink(linksvc) and os.path.realpath(linksvc) == old_pathsvc:
logit("removing linksvc %s"%linksvc)
os.unlink(linksvc)