-
Notifications
You must be signed in to change notification settings - Fork 131
/
nxService.py
1692 lines (1511 loc) · 63.4 KB
/
nxService.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# ===================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# See license.txt for license information.
# ===================================
from contextlib import contextmanager
import subprocess
import os
import sys
import glob
import codecs
import imp
import time
import copy
import re
import fnmatch
from functools import reduce
protocol = imp.load_source('protocol', '../protocol.py')
nxDSCLog = imp.load_source('nxDSCLog', '../nxDSCLog.py')
helperlib = imp.load_source('helperlib', '../helperlib.py')
LG = nxDSCLog.DSCLog
# [ClassVersion("1.0.0"),FriendlyName("nxService"), SupportsInventory()]
# class MSFT_nxServiceResource : OMI_BaseResource
# {
# [key, InventoryFilter] string Name;
# [write,required,ValueMap{"init", "upstart", "systemd"},Values{"init","upstart","systemd"}, InventoryFilter] string Controller;
# [write, InventoryFilter] boolean Enabled;
# [write,ValueMap{"Running", "Stopped"},Values{"Running", "Stopped"}, InventoryFilter] string State;
# [read] string Path;
# [read] string Description;
# [read] string Runlevels;
# };
global show_mof
show_mof = False
def init_vars(Name, Controller, Enabled, State):
if Name is None:
Name = ''
if Name == '*':
Name = ''
if Controller is None or Controller == '*':
Controller = GetController()
if Enabled is None:
Enabled = False
Enabled = (Enabled == True)
if State is None:
State = ''
return Name, Controller.lower(), Enabled, State.lower()
def Set_Marshall(Name, Controller, Enabled, State):
if helperlib.CONFIG_SYSCONFDIR_DSC == "omsconfig":
return [-1]
(Name, Controller, Enabled, State) = init_vars(
Name, Controller, Enabled, State)
if Controller == '':
return [-1]
retval = Set(Name, Controller, Enabled, State)
return retval
def Test_Marshall(Name, Controller, Enabled, State):
if helperlib.CONFIG_SYSCONFDIR_DSC == "omsconfig":
return [-1]
(Name, Controller, Enabled, State) = init_vars(
Name, Controller, Enabled, State)
if Controller == '':
return [-1]
retval = Test(Name, Controller, Enabled, State)
return retval
def Get_Marshall(Name, Controller, Enabled, State):
arg_names = list(locals().keys())
arg_names.append('Path')
arg_names.append('Runlevels')
arg_names.append('Description')
(Name, Controller, Enabled, State) = init_vars(
Name, Controller, Enabled, State)
if Controller == '':
return [-1], {}
retval = 0
(retval, Name, Controller, Enabled, State, Path, Description, Runlevels) = Get(
Name, Controller, Enabled, State)
Name = protocol.MI_String(Name)
Controller = protocol.MI_String(Controller)
Enabled = protocol.MI_Boolean(Enabled)
State = protocol.MI_String(State)
Path = protocol.MI_String(Path)
Description = protocol.MI_String(Description)
Runlevels = protocol.MI_String(Runlevels)
retd = {}
ld = locals()
for k in arg_names:
retd[k] = ld[k]
return retval, retd
def Inventory_Marshall(Name, Controller, Enabled, State):
FilterEnabled = (Enabled != None)
(Name, Controller, Enabled, State) = init_vars(
Name, Controller, Enabled, State)
if Controller == '':
return -1, {"__Inventory": {}}
sc = ServiceContext(Name, Controller, Enabled, State)
sc.FilterEnabled = FilterEnabled
if not GetAll(sc):
return -1, {"__Inventory": {}}
for srv in sc.services_list:
srv['Name'] = protocol.MI_String(srv['Name'])
srv['Controller'] = protocol.MI_String(srv['Controller'])
srv['Enabled'] = protocol.MI_Boolean(srv['Enabled'])
if 'running' in srv['State'].lower():
srv['State'] = protocol.MI_String('Running')
else:
srv['State'] = protocol.MI_String('Stopped')
srv['Path'] = protocol.MI_String(srv['Path'])
srv['Description'] = protocol.MI_String(srv['Description'])
srv['Runlevels'] = protocol.MI_String(srv['Runlevels'])
Inventory = protocol.MI_InstanceA(sc.services_list)
retd = {}
retd["__Inventory"] = Inventory
return 0, retd
#
# Begin user defined DSC functions
#
def SetShowMof(a):
global show_mof
show_mof = a
def ShowMof(op, Name, Controller, Enabled, State):
if not show_mof:
return
mof = ''
mof += op + ' nxService MyService'
mof += '{\n'
mof += ' Name = "' + Name + '"\n'
mof += ' Controller = "' + Controller + '"\n'
mof += ' Enabled = ' + str(Enabled) + '\n'
mof += ' State = "' + State + '"\n'
mof += '}\n'
f = open('./test_mofs.log', 'a')
Print(mof, file=f)
LG().Log('INFO', mof)
f.close()
def Print(s, file=sys.stdout):
file.write(s + '\n')
@contextmanager
def opened_w_error(filename, mode="r"):
"""
This context ensures the file is closed.
"""
try:
f = codecs.open(filename, encoding='utf-8', mode=mode)
except IOError as err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
def RunGetOutput(cmd, no_output, chk_err=True):
"""
Wrapper for subprocess.check_output.
Execute 'cmd'. Returns return code and STDOUT,
trapping expected exceptions.
Reports exceptions to Error if chk_err parameter is True
"""
def check_output(no_output, *popenargs, **kwargs):
r"""Backport from subprocess module from python 2.7"""
if 'stdout' in kwargs:
raise ValueError(
'stdout argument not allowed, it will be overridden.')
if no_output:
out_file = None
else:
out_file = subprocess.PIPE
process = subprocess.Popen(stdout=out_file, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output
# Exception classes used by this module.
class CalledProcessError(Exception):
def __init__(self, returncode, cmd, output=None):
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return "Command '%s' returned non-zero exit status %d" \
% (self.cmd, self.returncode)
output = b''
try:
output = check_output(no_output, cmd, stderr=subprocess.STDOUT, shell=True)
if output is None:
output = b''
except CalledProcessError as e:
if chk_err:
Print('CalledProcessError. Error Code is ' +
str(e.returncode), file=sys.stderr)
LG().Log(
'ERROR', 'CalledProcessError. Error Code is '
+ str(e.returncode))
Print(
'CalledProcessError. Command string was '
+ e.cmd, file=sys.stderr)
LG().Log(
'ERROR', 'CalledProcessError. Command string was ' + e.cmd)
Print('CalledProcessError. Command result was ' +
(e.output[:-1]).decode('ascii', 'ignore'), file=sys.stderr)
LG().Log(
'ERROR', 'CalledProcessError. Command result was '
+ (e.output[:-1]).decode('ascii', 'ignore'))
if no_output:
return e.returncode, None
else:
return e.returncode, e.output.decode('ascii', 'ignore')
if no_output:
return 0, None
else:
return 0, output.decode('ascii', 'ignore')
def RunGetOutputNoStderr(cmd, no_output, chk_err=True):
"""
Wrapper for subprocess.check_output without stderr.
Execute 'cmd'. Returns return code and STDOUT,
trapping expected exceptions.
Reports exceptions to Error if chk_err parameter is True
"""
def check_output(no_output, *popenargs, **kwargs):
r"""Backport from subprocess module from python 2.7"""
if 'stdout' in kwargs:
raise ValueError(
'stdout argument not allowed, it will be overridden.')
if no_output:
out_file = None
else:
out_file = subprocess.PIPE
process = subprocess.Popen(stdout=out_file, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output
# Exception classes used by this module.
class CalledProcessError(Exception):
def __init__(self, returncode, cmd, output=None):
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return "Command '%s' returned non-zero exit status %d" \
% (self.cmd, self.returncode)
output = b''
try:
output = check_output(no_output, cmd, stderr=subprocess.DEVNULL, shell=True)
if output is None:
output = b''
except CalledProcessError as e:
if chk_err:
Print('CalledProcessError. Error Code is ' +
str(e.returncode), file=sys.stderr)
LG().Log(
'ERROR', 'CalledProcessError. Error Code is '
+ str(e.returncode))
Print(
'CalledProcessError. Command string was '
+ e.cmd, file=sys.stderr)
LG().Log(
'ERROR', 'CalledProcessError. Command string was ' + e.cmd)
Print('CalledProcessError. Command result was ' +
(e.output[:-1]).decode('ascii', 'ignore'), file=sys.stderr)
LG().Log(
'ERROR', 'CalledProcessError. Command result was '
+ (e.output[:-1]).decode('ascii', 'ignore'))
if no_output:
return e.returncode, None
else:
return e.returncode, e.output.decode('ascii', 'ignore')
if no_output:
return 0, None
else:
return 0, output.decode('ascii', 'ignore')
systemctl_path = "/usr/bin/systemctl"
upstart_start_path = "/sbin/start"
upstart_stop_path = "/sbin/stop"
upstart_status_path = "/sbin/status"
if os.path.exists('/sbin'):
os.environ['PATH']=os.environ['PATH']+':/sbin'
code, out = RunGetOutput('which service', False, False)
initd_service = out.strip('\n')
initd_chkconfig = "/sbin/chkconfig"
initd_invokerc = "/usr/sbin/invoke-rc.d"
initd_updaterc = "/usr/sbin/update-rc.d"
lsb_install_initd = "/usr/lib/lsb/install_initd"
lsb_remove_initd = "/usr/lib/lsb/remove_initd"
runlevel_path = "/sbin/runlevel"
def ReadFile(path):
"""
Safely attempt to read a file,
ensuring file is always closed at exit.
Return the data and the exception object.
The data is None if an error occurred.
The error is None if the data was read.
Log results to stderr.
"""
d = None
error = None
with opened_w_error(path, 'rb') as (F, error):
if error:
Print("Exception opening file " + path + " Error Code: " +
str(error.errno) +
" Error: " + error.message + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception opening file " + path +
" Error Code: " +
str(error.errno) + " Error: " + error.message +
error.strerror)
else:
d = F.read()
return d, error
def WriteFile(path, contents):
"""
Safely attempt to write data to a file,
replacing the existing file or creating it and
ensuring file is always closed at exit.
Return the exception object.
The error is None if the data was written.
Log results to stderr.
"""
error = None
with opened_w_error(path, 'wb+') as (F, error):
if error:
Print("Exception opening file " + path + " Error Code: " +
str(error.errno) +
" Error: " + error.message + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception opening file " + path +
" Error Code: " +
str(error.errno) + " Error: " + error.message +
error.strerror)
else:
F.write(contents)
return error
def Process(params, no_output=False):
line = ''
spc = ''
for p in params:
line += (spc + p)
if len(spc) is 0:
spc = ' '
code, out = RunGetOutput(line, no_output, False)
return (out, out, code)
def StartService(sc):
if sc.Controller == "systemd":
(process_stdout, process_stderr, retval) = Process(
[systemctl_path, "start", sc.Name])
if retval is not 0:
Print("Error: " + systemctl_path + " start " + sc.Name +
" failed: " + process_stderr, file=sys.stderr)
LG().Log('ERROR', "Error: " + systemctl_path +
" start " + sc.Name + " failed: " + process_stderr)
return [-1]
elif sc.Controller == "upstart":
(process_stdout, process_stderr, retval) = Process(
[upstart_start_path, sc.Name])
if retval is not 0:
Print("Error: " + upstart_start_path +
" failed: " + process_stderr, file=sys.stderr)
LG().Log(
'ERROR', "Error: " + upstart_start_path
+ " failed: " + process_stderr)
return [-1]
elif sc.Controller == "init":
check_state_program = initd_service
if os.path.isfile(initd_invokerc) and os.path.isfile(initd_updaterc):
check_state_program = initd_invokerc
(process_stdout, process_stderr, retval) = Process(
[check_state_program, sc.Name, "start"])
if retval is not 0:
Print("Error: " + check_state_program +
" failed: " + process_stderr, file=sys.stderr)
LG().Log(
'ERROR', "Error: " + check_state_program
+ " failed: " + process_stderr)
return [-1]
if not IsServiceRunning(sc):
Print("Error: " + sc.Name + " start failed: " +
process_stderr, file=sys.stderr)
LG().Log('ERROR', "Error: " + sc.Name +
" start failed: " + process_stderr)
return [-1]
return [0]
def StopService(sc):
if sc.Controller == "systemd":
(process_stdout, process_stderr, retval) = Process(
[systemctl_path, "stop", sc.Name])
if retval is not 0:
Print("Error: " + systemctl_path + " failed: " +
process_stderr, file=sys.stderr)
LG().Log(
'ERROR', "Error: " + systemctl_path
+ " failed: " + process_stderr)
return [-1]
elif sc.Controller == "upstart":
(process_stdout, process_stderr, retval) = Process(
[upstart_stop_path, sc.Name])
if retval is not 0:
Print("Error: " + upstart_stop_path +
" failed: " + process_stderr, file=sys.stderr)
LG().Log(
'ERROR', "Error: " + upstart_stop_path
+ " failed: " + process_stderr)
return [-1]
elif sc.Controller == "init":
check_state_program = initd_service
if os.path.isfile(initd_invokerc) and os.path.isfile(initd_updaterc):
check_state_program = initd_invokerc
(process_stdout, process_stderr, retval) = Process(
[check_state_program, sc.Name, "stop"])
if retval is not 0:
Print("Error: " + check_state_program +
" failed: " + process_stderr, file=sys.stderr)
LG().Log(
'ERROR', "Error: " + check_state_program
+ " failed: " + process_stderr)
return [-1]
if IsServiceRunning(sc):
Print("Error: " + sc.Name + " stop failed: " +
process_stderr, file=sys.stderr)
LG().Log('ERROR', "Error: " + sc.Name +
" stop failed: " + process_stderr)
return [-1]
return [0]
def GetRunLevel():
(process_stdout, process_stderr, retval) = Process([runlevel_path])
if retval is not 0:
Print("Error: " + runlevel_path + " failed: " +
process_stderr, file=sys.stderr)
LG().Log(
'ERROR', "Error: " + runlevel_path + " failed: " + process_stderr)
return -1
tokens = process_stdout.split(" ")
if len(tokens) is not 2:
Print("Error: unexpected number of tokens from " +
runlevel_path + ". stdout: " + process_stdout, file=sys.stderr)
LG().Log('ERROR', "Error: unexpected number of tokens from " +
runlevel_path + ". stdout: " + process_stdout)
return -1
return int(tokens[1])
def DetermineInitState(stdout):
if "is running" in stdout or "start/running" in stdout \
or "..running" in stdout:
return True
elif stdout.strip() == "running":
return True
elif "(running)" in stdout:
return True
else:
return False
def DetermineInitEnabled(stdout, runlevel):
tokens = stdout.split()
tokens = tokens[1:]
if runlevel > (len(tokens) - 1):
Print("runlevel " + str(runlevel) +
" not found in chkconfig", file=sys.stderr)
LG().Log(
'ERROR', "runlevel " + str(runlevel) + " not found in chkconfig")
return False
runlevel_tokens = tokens[runlevel].split(":")
if len(runlevel_tokens) is not 2:
Print(
"Unable to determine format for chkconfig run level",
file=sys.stderr)
LG().Log(
'ERROR', "Unable to determine format for chkconfig run level")
return False
if runlevel_tokens[1] == "on":
return True
else:
return False
def GetSystemdState(sc):
(process_stdout, process_stderr, retval) = Process(
[systemctl_path, "status", sc.Name])
if retval is 0:
if '(running)' in process_stdout:
return "running"
return "stopped"
def TestSystemdState(sc):
if sc.State and sc.State != GetSystemdState(sc):
return False
return True
def GetSystemdEnabled(sc):
(process_stdout, process_stderr, retval) = Process(
[systemctl_path, "is-enabled", sc.Name])
if retval is 0:
return True
else:
return False
def TestSystemdEnabled(sc):
if sc.Enabled is not GetSystemdEnabled(sc):
return False
return True
def TestSystemd(sc):
if not SystemdExists():
return [-1]
if not TestSystemdState(sc):
return [-1]
if not TestSystemdEnabled(sc):
return [-1]
return [0]
def GetUpstartState(sc):
(process_stdout, process_stderr, retval) = Process(
[upstart_status_path, sc.Name])
if retval is not 0:
Print("Error: " + upstart_status_path +
" failed: " + process_stderr, file=sys.stderr)
LG().Log('ERROR', "Error: " + upstart_status_path +
" failed: " + process_stderr)
return ""
if (sc.Name + " start") in process_stdout:
return "running"
else:
return "stopped"
def TestUpstartState(sc):
if sc.State and sc.State != GetUpstartState(sc):
return False
return True
def GetUpstartEnabled(sc):
if os.path.isfile("/etc/init/" + sc.Name + ".conf"):
start_on_exists = False
start_on_is_enabled = False
stop_on_exists = False
stop_on_is_enabled = False
file_lines, error = ReadFile("/etc/init/" + sc.Name + ".conf")
if error is not None:
Print(
"Error reading:/etc/init/" + sc.Name + ".conf",
file=sys.stderr)
LG().Log('ERROR', "Error reading:/etc/init/" +
sc.Name + ".conf")
return "Error"
for full_line in file_lines.splitlines():
# everything after a '#' character is a comment, so strip it off
line = full_line.split("#")[0]
if "start on" in line:
start_on_exists = True
if ("(" in line) or ("and" in line) or ("or" in line):
return "Complex"
elif "start on runlevel [" in line:
runlevel = GetRunLevel()
specified_runlevel_digits = line.split("[")[1][:-1]
if str(runlevel) in specified_runlevel_digits:
start_on_is_enabled = True
else:
start_on_is_enabled = False
if "!" in specified_runlevel_digits:
start_on_is_enabled = not start_on_is_enabled
else:
return "Complex"
if "stop on" in line:
stop_on_exists = True
if ("(" in line) or ("and" in line) or ("or" in line):
return "Complex"
elif "stop on runlevel [" in line:
runlevel = GetRunLevel()
specified_runlevel_digits = line.split("[")[1][:-1]
if str(runlevel) in specified_runlevel_digits:
stop_on_is_enabled = True
else:
stop_on_is_enabled = False
if "!" in specified_runlevel_digits:
stop_on_is_enabled = not stop_on_is_enabled
else:
return "Complex"
if not start_on_exists and not stop_on_exists: # not upstart
if os.path.islink('/etc/init.d/' + sc.Name) and \
os.readlink('/etc/init.d/' + sc.Name) \
== '/lib/init/upstart-job':
# this is a 'converted' init script, check the default rc2.d
# for smylink to conf file. if so its enabled.
file_list = os.listdir('/etc/rc2.d')
for f in file_list:
f = '/etc/rc2.d/' + f
if os.path.islink(f) and os.readlink(f) == \
"../init.d/" + sc.Name:
return True
return False
(process_stdout, process_stderr, retval) = Process(
['chkconfig', sc.Name, '']) # try init style
if retval is 0:
if 'off' not in process_stdout:
return True
return False
if start_on_exists and start_on_is_enabled:
if stop_on_exists and stop_on_is_enabled:
Print("Error: Having trouble determining whether service " +
sc.Name + " is enabled or disabled.", file=sys.stderr)
LG().Log('ERROR',
"Error: Having trouble determining whether service " +
sc.Name + " is enabled or disabled.")
return "Complex"
else:
return True
else:
return False
Print("Error: Unable to find line containing 'start on' in " +
sc.Name + ".conf", file=sys.stderr)
LG().Log('ERROR',
"Error: Unable to find line containing 'start on' in " +
sc.Name + ".conf")
return False
else:
Print("Error: conf file does not exist for service named " +
sc.Name, file=sys.stderr)
LG().Log('ERROR',
"Error: conf file does not exist for service named " +
sc.Name)
return False
def TestUpstartEnabled(sc):
currently_enabled = GetUpstartEnabled(sc)
if currently_enabled == "Complex":
Print("Error: Cannot modify 'Enabled' state for service " + sc.Name +
", conf file too complex. Please use the File provider to " +
"write your own conf file for this service.", file=sys.stderr)
LG().Log('ERROR', "Error: Cannot modify 'Enabled' state for service "
+ sc.Name +
", conf file too complex. Please use the File provider to " +
" writeyour own conf file for this service.")
return False
return currently_enabled
def TestUpstart(sc):
if not UpstartExists():
return [-1]
if not TestUpstartState(sc):
return [-1]
if sc.Enabled is not TestUpstartEnabled(sc):
return [-1]
return [0]
def GetInitState(sc):
check_state_program = initd_service
# debian style init. These are missing in redhat.
if os.path.isfile(initd_invokerc) and os.path.isfile(initd_updaterc):
check_state_program = initd_service
if os.path.isfile(initd_service):
check_state_program = initd_service
else: # invoke the service directly
check_state_program = '/etc/init.d/'
if check_state_program == '/etc/init.d/':
(process_stdout, process_stderr, retval) = Process(
[check_state_program + sc.Name, "status"], True)
if retval is not 0:
Print("Error: " + check_state_program +
sc.Name + " status failed: ", file=sys.stderr)
LG().Log('ERROR', "Error: " + check_state_program +
sc.Name + " status failed: ")
if IsServiceRunning(sc):
return "running"
else:
return "stopped"
else:
(process_stdout, process_stderr, retval) = Process(
[check_state_program, sc.Name, "status"])
if retval is not 0:
if IsServiceRunning(sc):
return "running"
else:
return "stopped"
if DetermineInitState(process_stdout):
return "running"
else:
return "stopped"
def TestInitState(sc):
if sc.State and sc.State != GetInitState(sc):
return False
return True
def GetInitEnabled(sc):
runlevel = GetRunLevel()
if os.path.isfile(initd_invokerc) and os.path.isfile(initd_updaterc):
# A service is enabled if a symbolic link
# exists in /etc/rc${RUNLEVEL}.d/ with the name:
# S??${sc.Name}
matched_files = glob.glob(
"/etc/rc" + str(runlevel) + ".d/S??" + sc.Name)
for f in matched_files:
if os.path.islink(f):
return True
return False
else:
check_enabled_program = initd_chkconfig
(process_stdout, process_stderr, retval) = Process(
[check_enabled_program, "--list", sc.Name])
if retval is not 0:
Print("Error: " + check_enabled_program +
" failed: " + process_stderr, file=sys.stderr)
LG().Log('ERROR', "Error: " + check_enabled_program +
" failed: " + process_stderr)
return False
if DetermineInitEnabled(process_stdout, runlevel):
return True
else:
return False
def TestInitEnabled(sc):
if sc.Enabled is not GetInitEnabled(sc):
return False
return True
def TestInit(sc):
if not InitExists():
return [-1]
if not TestInitState(sc):
return [-1]
if not TestInitEnabled(sc):
return [-1]
return [0]
def SystemdExists():
global systemctl_path
code, out = RunGetOutput('which systemctl', False, False)
if code is 0:
systemctl_path = out.strip()
return True
else:
return False
def UpstartExists():
if (os.path.isfile('/sbin/upstart-local-bridge')
or os.path.isfile('/sbin/upstart-udev-bridge')) \
and os.path.isfile(upstart_start_path) \
and os.path.isfile(upstart_stop_path) \
and os.path.isfile(upstart_status_path):
return True
else:
return False
def InitExists():
if os.path.isfile(initd_service) and os.path.isfile(initd_chkconfig):
return True
elif os.path.isfile(initd_invokerc) and os.path.isfile(initd_updaterc):
return True
else:
return False
def ServiceExistsInSystemd(sc):
(process_stdout, process_stderr, retval) = Process(
[systemctl_path, "status", sc.Name])
if retval is not 0:
if "Loaded: loaded" in process_stdout:
return True
else:
return False
else:
return True
def ServiceExistsInUpstart(sc):
(process_stdout, process_stderr, retval) = Process(
[upstart_status_path, sc.Name])
if retval is not 0:
return False
else:
return True
def ServiceExistsInInit(sc):
check_state_program = initd_service
if os.path.isfile(initd_invokerc) and os.path.isfile(initd_updaterc):
check_state_program = initd_invokerc
(process_stdout, process_stderr, retval) = Process(
[check_state_program, sc.Name, "status"])
if "unrecognized service" in process_stderr \
or "no such service" in process_stderr \
or "not found" in process_stderr:
Print(process_stderr, file=sys.stderr)
LG().Log('INFO', process_stderr)
return False
else:
return True
def CreateSystemdService(sc):
Print("Error: systemd services cannot be created from the service " +
"provider. Please use the file provider to create a systemd " +
"conf file, then modify the service using this service provider.",
file=sys.stderr)
LG().Log('ERROR',
"Error: systemd services cannot be created from the service provider. \
Please use the file provider to create a systemd conf file, \
then modify the service using this service provider.")
return [-1]
def ModifySystemdService(sc):
if sc.Enabled is True:
(process_stdout, process_stderr, retval) = Process(
[systemctl_path, "enable", sc.Name + '.service'])
if retval is not 0:
Print("Error: " + systemctl_path + " enable " + sc.Name +
" failed: " + process_stderr, file=sys.stderr)
LG().Log('ERROR', "Error: " + systemctl_path +
" enable " + sc.Name + " failed: " + process_stderr)
return [-1]
elif sc.Enabled is False:
(process_stdout, process_stderr, retval) = Process(
[systemctl_path, "disable", sc.Name + '.service'])
if retval is not 0:
Print("Error: " + systemctl_path + " disable " + sc.Name +
" failed: " + process_stderr, file=sys.stderr)
LG().Log('ERROR', "Error: " + systemctl_path +
" disable " + sc.Name + " failed: " + process_stderr)
return [-1]
(process_stdout, process_stderr, retval) = Process(
[systemctl_path, "status", sc.Name + '.service'])
# retval may be non zero even if service exists for 'status'.
if 'No such file or directory' in process_stdout:
Print("Error: " + systemctl_path + " status " + sc.Name +
" failed: " + process_stderr, file=sys.stderr)
LG().Log('ERROR', "Error: " + systemctl_path +
" status " + sc.Name + " failed: " + process_stderr)
return [-1]
if 'Active: active' in process_stdout:
Print("Running", file=sys.stderr)
LG().Log('INFO', "Running")
if sc.State and sc.State != "running":
return StopService(sc)
else:
Print("Stopped", file=sys.stderr)
LG().Log('INFO', "Stopped")
if sc.State and sc.State != "stopped":
return StartService(sc)
return [0]
def CreateUpstartService(sc):
Print("Error: Upstart services cannot be created from the service " +
"provider. Please use the file provider to create an upstart " +
"conf file, then modify the service using this service provider.",
file=sys.stderr)
LG().Log('ERROR',
"Error: Upstart services cannot be created from the service " +
"provider. Please use the file provider to create an upstart " +
"conf file, then modify the service using this service provider.")
return [-1]
def ModifyUpstartConfFile(sc):
if os.path.isfile("/etc/init/" + sc.Name + ".conf"):
file_lines, error = ReadFile("/etc/init/" + sc.Name + ".conf")
if len(file_lines) is 0 or error is not None:
Print("Error: Conf file unable to be read for service " +
sc.Name, file=sys.stderr)
LG().Log(
'ERROR', "Error: Conf file unable to be read for service " +
sc.Name)
return False
outfile = ""
start_on_exists = False
stop_on_exists = False
for full_line in file_lines.splitlines():
line = full_line.split("#")[0]
if "start on" in line or "stop on" in line and not start_on_exists:
# If we got to this point, we can assume that we're allowed to
# modify the conf file. No need to check for a "Complex" conf
# file.
start_on_exists = True
if sc.Enabled is True:
outfile += "start on runlevel [2345]\n"
outfile += "stop on runlevel [!2345]\n"
elif sc.Enabled is False:
outfile += "stop on runlevel [0123456]\n"
elif "start on" in line or "stop on" in line and start_on_exists:
continue # its xtra now
else:
outfile += full_line + "\n"
if start_on_exists or stop_on_exists:
if WriteFile("/etc/init/" + sc.Name + ".conf", outfile) \
is not None:
Print(
"Error: Unable to write conf file for service " + sc.Name,
file=sys.stderr)
LG().Log(
'ERROR', "Error: Unable to write conf file for service " +
sc.Name)