-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathSystemAdministratorClientCLI.py
More file actions
1279 lines (1164 loc) · 49.9 KB
/
SystemAdministratorClientCLI.py
File metadata and controls
1279 lines (1164 loc) · 49.9 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
#!/usr/bin/env python
########################################################################
"""System Administrator Client Command Line Interface"""
import atexit
import datetime
import os
import pprint
import readline
import sys
import time
from DIRAC import gConfig, gLogger
from DIRAC.Core.Base.CLI import CLI, colorize
from DIRAC.Core.Security.ProxyInfo import getProxyInfo
from DIRAC.Core.Utilities import List
from DIRAC.Core.Utilities.Extensions import extensionsByPriority
from DIRAC.Core.Utilities.File import mkDir
from DIRAC.Core.Utilities.PrettyPrint import printTable
from DIRAC.Core.Utilities.PromptUser import promptUser
from DIRAC.FrameworkSystem.Client.ComponentInstaller import gComponentInstaller
from DIRAC.FrameworkSystem.Client.ComponentMonitoringClient import (
ComponentMonitoringClient,
)
from DIRAC.FrameworkSystem.Client.SystemAdministratorClient import (
SystemAdministratorClient,
)
from DIRAC.FrameworkSystem.Client.SystemAdministratorIntegrator import (
SystemAdministratorIntegrator,
)
from DIRAC.FrameworkSystem.Utilities import MonitoringUtilities
from DIRAC.MonitoringSystem.Client.MonitoringClient import MonitoringClient
class SystemAdministratorClientCLI(CLI):
"""Line oriented command interpreter for administering DIRAC components"""
def __init__(self, host=None):
CLI.__init__(self)
# Check if Port is given
self.host = None
self.port = None
self.prompt = f"[{colorize('no host', 'yellow')}]> "
if host:
self.__setHost(host)
self.cwd = ""
self.previous_cwd = ""
self.homeDir = ""
self.runitComponents = ["service", "agent", "executor", "consumer"]
# store history
histfilename = os.path.basename(sys.argv[0])
historyFile = os.path.expanduser(f"~/.dirac/{histfilename[0:-3]}.history")
mkDir(os.path.dirname(historyFile))
if os.path.isfile(historyFile):
readline.read_history_file(historyFile)
readline.set_history_length(1000)
atexit.register(readline.write_history_file, historyFile)
def __setHost(self, host):
hostList = host.split(":")
self.host = hostList[0]
if len(hostList) == 2:
self.port = hostList[1]
else:
self.port = None
gLogger.notice(f"Pinging {self.host}...")
result = self.__getClient().ping()
if result["OK"]:
colorHost = colorize(host, "green")
else:
self._errMsg(f"Could not connect to {self.host}: {result['Message']}")
colorHost = colorize(host, "red")
self.prompt = f"[{colorHost}]> "
def __getClient(self):
return SystemAdministratorClient(self.host, self.port)
def do_set(self, args):
"""
Set options
usage:
set host <hostname> - Set the hostname to work with
set project <project> - Set the project to install/upgrade in the host
"""
if not args:
gLogger.notice(self.do_set.__doc__)
return
cmds = {"host": (1, self.__do_set_host), "project": (1, self.__do_set_project)}
args = List.fromChar(args, " ")
for cmd in cmds:
if cmd == args[0]:
if len(args) != 1 + cmds[cmd][0]:
self._errMsg("Missing arguments")
gLogger.notice(self.do_set.__doc__)
return
return cmds[cmd][1](args[1:])
self._errMsg("Invalid command")
gLogger.notice(self.do_set.__doc__)
return
def __do_set_host(self, args):
host = args[0]
if host.find(".") == -1 and host != "localhost":
self._errMsg("Provide the full host name including its domain")
return
self.__setHost(host)
def __do_set_project(self, args):
project = args[0]
result = self.__getClient().setProject(project)
if not result["OK"]:
self._errMsg(f"Cannot set project: {result['Message']}")
else:
gLogger.notice(f"Project set to {project}")
def do_show(self, args):
"""
Show list of components with various related information
usage:
show software - show components for which software is available
show installed - show components installed in the host with runit system
show setup - show components set up for automatic running in the host
show project - show project to install or upgrade
show status - show status of the installed components
show database - show status of the databases
show mysql - show status of the MySQL server
show log <system> <service|agent> [nlines]
- show last <nlines> lines in the component log file
show info - show version of software and setup
show doc <type> <system> <name>
- show documentation for a given service or agent
show host - show host related parameters
show hosts - show all available hosts
show ports [host] - show all ports used by a host. If no host is given, the host currently connected to is used
show installations [ list | current | -n <Name> | -h <Host> | -s <System> | -m <Module> | -t <Type> | -itb <InstallationTime before>
| -ita <InstallationTime after> | -utb <UnInstallationTime before> | -uta <UnInstallationTime after> ]*
- show all the installations of components that match the given parameters
show profile <system> <component> [ -s <size> | -h <host> | -id <initial date DD/MM/YYYY> | -it <initial time hh:mm>
| -ed <end date DD/MM/YYYY | -et <end time hh:mm> ]*
- show <size> log lines of profiling information for a component in the machine <host>
show errors [*|<system> <service|agent>]
- show error count for the given component or all the components
in the last hour and day
"""
argss = args.split()
if not argss:
gLogger.notice(self.do_show.__doc__)
return
option = argss[0]
del argss[0]
if option == "software":
client = SystemAdministratorClient(self.host, self.port)
result = client.getSoftwareComponents()
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice("")
pprint.pprint(result["Value"])
elif option == "installed":
client = SystemAdministratorClient(self.host, self.port)
result = client.getInstalledComponents()
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice("")
pprint.pprint(result["Value"])
elif option == "setup":
client = SystemAdministratorClient(self.host, self.port)
result = client.getSetupComponents()
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice("")
pprint.pprint(result["Value"])
elif option == "project":
result = SystemAdministratorClient(self.host, self.port).getProject()
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice(f"Current project is {result['Value']}")
elif option == "status":
client = SystemAdministratorClient(self.host, self.port)
result = client.getOverallStatus()
if not result["OK"]:
self._errMsg(result["Message"])
else:
fields = ["System", "Name", "Module", "Type", "Setup", "Installed", "Runit", "Uptime", "PID"]
records = []
rDict = result["Value"]
for compType in rDict:
for system in rDict[compType]:
components = sorted(rDict[compType][system])
for component in components:
record = []
if rDict[compType][system][component]["Installed"]:
module = str(rDict[compType][system][component]["Module"])
record += [system, component, module, compType.lower()[:-1]]
if rDict[compType][system][component]["Setup"]:
record += ["Setup"]
else:
record += ["NotSetup"]
if rDict[compType][system][component]["Installed"]:
record += ["Installed"]
else:
record += ["NotInstalled"]
record += [str(rDict[compType][system][component]["RunitStatus"])]
record += [str(rDict[compType][system][component]["Timeup"])]
record += [str(rDict[compType][system][component]["PID"])]
records.append(record)
printTable(fields, records)
elif option in ("database", "databases"):
client = SystemAdministratorClient(self.host, self.port)
if not gComponentInstaller.mysqlPassword:
gComponentInstaller.mysqlPassword = "LocalConfig"
gComponentInstaller.getMySQLPasswords()
result = client.getDatabases(gComponentInstaller.mysqlRootPwd)
if not result["OK"]:
self._errMsg(result["Message"])
return
resultSW = client.getAvailableDatabases()
if not resultSW["OK"]:
self._errMsg(resultSW["Message"])
return
sw = resultSW["Value"]
installed = result["Value"]
gLogger.notice("")
for db in sw:
if db in installed:
gLogger.notice(db.rjust(25), ": Installed")
else:
gLogger.notice(db.rjust(25), ": Not installed")
if not sw:
gLogger.notice("No database found")
elif option == "mysql":
client = SystemAdministratorClient(self.host, self.port)
result = client.getMySQLStatus()
if not result["OK"]:
self._errMsg(result["Message"])
elif result["Value"]:
gLogger.notice("")
for par, value in result["Value"].items():
gLogger.notice((par.rjust(28), ":", value))
else:
gLogger.notice("No MySQL database found")
elif option == "log":
self.getLog(argss)
elif option == "info":
client = SystemAdministratorClient(self.host, self.port)
result = client.getInfo()
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice("")
gLogger.notice("Setup:", result["Value"]["Setup"])
for e, v in result["Value"]["Extensions"].items():
gLogger.notice(f"{e} version", v)
gLogger.notice("")
elif option == "host":
client = SystemAdministratorClient(self.host, self.port)
result = client.getHostInfo()
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice("")
gLogger.notice("Host info:")
gLogger.notice("")
fields = ["Parameter", "Value"]
records = []
for parameter in result["Value"].items():
if parameter[0] == "Extension":
extensions = parameter[1].split(",")
for extension in extensions:
extensionName, extensionVersion = extension.split(":")
records.append([f"{extensionName}Version", str(extensionVersion)])
else:
records.append([parameter[0], str(parameter[1])])
printTable(fields, records)
elif option == "hosts":
client = ComponentMonitoringClient()
result = client.getHosts({}, False, False)
if not result["OK"]:
self._errMsg(f"Error retrieving the list of hosts: {result['Message']}")
else:
hostList = result["Value"]
gLogger.notice("")
gLogger.notice(" " + "Host".center(32) + " " + "CPU".center(34) + " ")
gLogger.notice("-" * 69)
for element in hostList:
gLogger.notice("|" + element["HostName"].center(32) + "|" + element["CPU"].center(34) + "|")
gLogger.notice("-" * 69)
gLogger.notice("")
elif option == "ports":
if not argss:
client = SystemAdministratorClient(self.host)
else:
hostname = argss[0]
del argss[0]
client = ComponentMonitoringClient()
result = client.hostExists({"HostName": hostname})
if not result["OK"]:
self._errMsg(result["Message"])
return
else:
if not result["Value"]:
self._errMsg("Given host does not exist")
return
client = SystemAdministratorClient(hostname)
result = client.getUsedPorts()
if not result["OK"]:
self._errMsg(result["Message"])
return
pprint.pprint(result["Value"])
elif option == "errors":
self.getErrors(argss)
elif option == "installations":
self.getInstallations(argss)
elif option == "doc":
if len(argss) > 2:
if argss[0] in ["service", "agent"]:
compType = argss[0]
compSystem = argss[1]
compModule = argss[2]
client = SystemAdministratorClient(self.host, self.port)
result = client.getComponentDocumentation(compType, compSystem, compModule)
if result["OK"]:
gLogger.notice(result["Value"])
else:
self._errMsg(result["Message"])
else:
gLogger.notice(self.do_show.__doc__)
else:
gLogger.notice(self.do_show.__doc__)
elif option == "profile":
if len(argss) > 1:
system = argss[0]
del argss[0]
component = argss[0]
del argss[0]
component = f"{system}_{component}"
argDict = {"-s": None, "-h": self.host, "-id": None, "-it": "00:00", "-ed": None, "-et": "00:00"}
key = None
for arg in argss:
if not key:
key = arg
else:
argDict[key] = arg
key = None
size = None
try:
if argDict["-s"]:
size = int(argDict["-s"])
except ValueError:
self._errMsg("Argument 'size' must be an integer")
return
host = argDict["-h"]
initialDate = argDict["-id"]
initialTime = argDict["-it"]
endingDate = argDict["-ed"]
endingTime = argDict["-et"]
if initialDate:
initialDate = f"{initialDate} {initialTime}"
else:
initialDate = ""
if endingDate:
endingDate = f"{endingDate} {endingTime}"
else:
endingDate = ""
client = MonitoringClient()
if size:
result = client.getLimitedData(host, component, size)
else:
result = client.getDataForAGivenPeriod(host, component, initialDate, endingDate)
if result["OK"]:
text = ""
headers = [list(result["Value"][0])]
for header in headers:
text += str(header).ljust(15)
gLogger.notice(text)
for record in result["Value"]:
for metric in record.values():
text += str(metric).ljust(15)
gLogger.notice(text)
else:
self._errMsg(result["Message"])
else:
gLogger.notice(self.do_show.__doc__)
else:
gLogger.notice("Unknown option:", option)
def getErrors(self, argss):
"""Get and gLogger.notice( out errors from the logs of specified components )"""
component = ""
if len(argss) < 1:
component = "*"
else:
system = argss[0]
if system == "*":
component = "*"
else:
if len(argss) < 2:
gLogger.notice("")
gLogger.notice(self.do_show.__doc__)
return
comp = argss[1]
component = "/".join([system, comp])
client = SystemAdministratorClient(self.host, self.port)
result = client.checkComponentLog(component)
if not result["OK"]:
self._errMsg(result["Message"])
else:
fields = ["System", "Component", "Last hour", "Last day", "Last error"]
records = []
for cname in result["Value"]:
system, component = cname.split("/")
errors_1 = result["Value"][cname]["ErrorsHour"]
errors_24 = result["Value"][cname]["ErrorsDay"]
lastError = result["Value"][cname]["LastError"]
lastError.strip()
if len(lastError) > 80:
lastError = lastError[:80] + "..."
records.append([system, component, str(errors_1), str(errors_24), lastError])
records.sort()
printTable(fields, records)
def getInstallations(self, argss):
"""Get data from the component monitoring database"""
display = "table"
installationFilter = {}
componentFilter = {}
hostFilter = {}
key = ""
for arg in argss:
if not key:
if arg == "list":
display = "list"
elif arg == "current":
installationFilter["UnInstallationTime"] = None
elif arg == "-t":
key = "Component.Type"
elif arg == "-m":
key = "Component.DIRACModule"
elif arg == "-s":
key = "Component.DIRACSystem"
elif arg == "-h":
key = "Host.HostName"
elif arg == "-n":
key = "Instance"
elif arg == "-itb":
key = "InstallationTime.smaller"
elif arg == "-ita":
key = "InstallationTime.bigger"
elif arg == "-utb":
key = "UnInstallationTime.smaller"
elif arg == "-uta":
key = "UnInstallationTime.bigger"
else:
if "Component." in key:
componentFilter[key.replace("Component.", "")] = arg
elif "Host." in key:
hostFilter[key.replace("Host.", "")] = arg
else:
if "Time." in key:
arg = datetime.datetime.strptime(arg, "%d-%m-%Y")
installationFilter[key] = arg
key = None
client = ComponentMonitoringClient()
result = client.getInstallations(installationFilter, componentFilter, hostFilter, True)
if not result["OK"]:
self._errMsg(f"Could not retrieve the installations: {result['Message']}")
installations = None
else:
installations = result["Value"]
if installations:
if display == "table":
gLogger.notice("")
gLogger.notice(
" "
+ "Num".center(5)
+ " "
+ "Host".center(20)
+ " "
+ "Name".center(20)
+ " "
+ "DIRACModule".center(20)
+ " "
+ "DIRACSystem".center(16)
+ " "
+ "Type".center(12)
+ " "
+ "Installed on".center(18)
+ " "
+ "Install by".center(12)
+ " "
+ "Uninstalled on".center(18)
+ " "
+ "Uninstall by".center(12)
)
gLogger.notice(("-") * 164)
gLogger.notice(("-") * 164)
for i, installation in enumerate(installations):
if not installation["InstalledBy"]:
installedBy = ""
else:
installedBy = installation["InstalledBy"]
if not installation["UnInstalledBy"]:
uninstalledBy = ""
else:
uninstalledBy = installation["UnInstalledBy"]
if installation["UnInstallationTime"]:
uninstalledOn = installation["UnInstallationTime"].strftime("%d-%m-%Y %H:%M")
isInstalled = "No"
else:
uninstalledOn = ""
isInstalled = "Yes"
if display == "table":
gLogger.notice(
"|"
+ str(i + 1).center(5)
+ "|"
+ installation["Host"]["HostName"].center(20)
+ "|"
+ installation["Instance"].center(20)
+ "|"
+ installation["Component"]["DIRACModule"].center(20)
+ "|"
+ installation["Component"]["DIRACSystem"].center(16)
+ "|"
+ installation["Component"]["Type"].center(12)
+ "|"
+ installation["InstallationTime"].strftime("%d-%m-%Y %H:%M").center(18)
+ "|"
+ installedBy.center(12)
+ "|"
+ uninstalledOn.center(18)
+ "|"
+ uninstalledBy.center(12)
+ "|"
)
gLogger.notice(("-") * 164)
elif display == "list":
gLogger.notice("")
gLogger.notice("Installation: ".rjust(20) + str(i + 1))
gLogger.notice("Installed: ".rjust(20) + isInstalled)
gLogger.notice("Host: ".rjust(20) + installation["Host"]["HostName"])
gLogger.notice("Name: ".rjust(20) + installation["Instance"])
gLogger.notice("Module: ".rjust(20) + installation["Component"]["DIRACModule"])
gLogger.notice("System: ".rjust(20) + installation["Component"]["DIRACSystem"])
gLogger.notice("Type: ".rjust(20) + installation["Component"]["Type"])
gLogger.notice(
"Installed on: ".rjust(20) + installation["InstallationTime"].strftime("%d-%m-%Y %H:%M")
)
if installedBy != "":
gLogger.notice("Installed by: ".rjust(20) + installedBy)
if uninstalledOn != "":
gLogger.notice("Uninstalled on: ".rjust(20) + uninstalledOn)
gLogger.notice("Uninstalled by: ".rjust(20) + uninstalledBy)
else:
self._errMsg("No display mode was selected")
gLogger.notice("")
def getLog(self, argss):
"""Get the tail of the log file of the given component"""
if len(argss) < 2:
gLogger.notice("")
gLogger.notice(self.do_show.__doc__)
return
system = argss[0]
component = argss[1]
nLines = 40
if len(argss) > 2:
nLines = int(argss[2])
client = SystemAdministratorClient(self.host, self.port)
result = client.getLogTail(system, component, nLines)
if not result["OK"]:
self._errMsg(result["Message"])
elif result["Value"]:
for line in result["Value"]["_".join([system, component])].split("\n"):
gLogger.notice(" ", line)
else:
gLogger.notice("No logs found")
def do_install(self, args):
"""
Install various DIRAC components
usage:
install db <databaseName>
install service <system> <service> [-m <ModuleName>] [-p <Option>=<Value>] [-p <Option>=<Value>] ...
install agent <system> <agent> [-m <ModuleName>] [-p <Option>=<Value>] [-p <Option>=<Value>] ...
install executor <system> <executor> [-m <ModuleName>] [-p <Option>=<Value>] [-p <Option>=<Value>] ...
"""
result = getProxyInfo()
if not result["OK"]:
self._errMsg(result["Message"])
user = result["Value"]["username"]
argss = args.split()
hostSetup = extension = None
if not argss:
gLogger.notice(self.do_install.__doc__)
return
option = argss[0]
del argss[0]
# Databases
if option == "db":
if not argss:
gLogger.notice(self.do_install.__doc__)
return
database = argss[0]
client = SystemAdministratorClient(self.host, self.port)
result = client.getAvailableDatabases()
if not result["OK"]:
self._errMsg(f"Can not get database list: {result['Message']}")
return
if database not in result["Value"]:
self._errMsg(f"Unknown database {database}: ")
return
system = result["Value"][database]["System"]
dbType = result["Value"][database]["Type"]
if dbType == "MySQL":
if not gComponentInstaller.mysqlPassword:
gComponentInstaller.mysqlPassword = "LocalConfig"
gComponentInstaller.getMySQLPasswords()
result = client.installDatabase(database, gComponentInstaller.mysqlRootPwd)
if not result["OK"]:
self._errMsg(result["Message"])
return
extension, system = result["Value"]
result = client.getHostInfo()
if not result["OK"]:
self._errMsg(result["Message"])
return
else:
cpu = result["Value"]["CPUModel"]
hostname = self.host
if not result["OK"]:
self._errMsg(result["Message"])
return
if database != "InstalledComponentsDB":
result = MonitoringUtilities.monitorInstallation(
"DB", system.replace("System", ""), database, cpu=cpu, hostname=hostname, user=user
)
if not result["OK"]:
self._errMsg(result["Message"])
return
gComponentInstaller.mysqlHost = self.host
result = client.getInfo()
if not result["OK"]:
self._errMsg(result["Message"])
result = gComponentInstaller.addDatabaseOptionsToCS(gConfig, system, database, overwrite=True)
if not result["OK"]:
self._errMsg(result["Message"])
return
gLogger.notice(f"Database {database} from {extension}/{system} installed successfully")
# DIRAC components
elif option in self.runitComponents:
if len(argss) < 2:
gLogger.notice(self.do_install.__doc__)
return
system = argss[0]
del argss[0]
component = argss[0]
del argss[0]
specialOptions = {}
module = ""
for i in range(len(argss)):
if argss[i] == "-m":
specialOptions["Module"] = argss[i + 1]
module = argss[i + 1]
if argss[i] == "-p":
opt, value = argss[i + 1].split("=")
specialOptions[opt] = value
if module == component:
module = ""
client = SystemAdministratorClient(self.host, self.port)
# First need to update the CS
# result = client.addDefaultOptionsToCS( option, system, component )
gComponentInstaller.host = self.host
result = client.getInfo()
if not result["OK"]:
self._errMsg(result["Message"])
return
# Install Module section if not yet there
if module:
result = gComponentInstaller.addDefaultOptionsToCS(
gConfig, option, system, module, extensionsByPriority()
)
# in case of Error we must stop, this can happen when the module name is wrong...
if not result["OK"]:
self._errMsg(result["Message"])
return
# Add component section with specific parameters only
result = gComponentInstaller.addDefaultOptionsToCS(
gConfig,
option,
system,
component,
extensionsByPriority(),
specialOptions=specialOptions,
addDefaultOptions=True,
)
else:
# Install component section
result = gComponentInstaller.addDefaultOptionsToCS(
gConfig, option, system, component, extensionsByPriority(), specialOptions
)
if not result["OK"]:
self._errMsg(result["Message"])
return
# Then we can install and start the component
result = client.setupComponent(option, system, component, module)
if not result["OK"]:
self._errMsg(result["Message"])
return
compType = result["Value"]["ComponentType"]
runit = result["Value"]["RunitStatus"]
gLogger.notice(f"{compType} {system}_{component} is installed, runit status: {runit}")
# And register it in the database
result = client.getHostInfo()
if not result["OK"]:
self._errMsg(result["Message"])
return
else:
cpu = result["Value"]["CPUModel"]
hostname = self.host
if component == "ComponentMonitoring":
# Make sure that the service is running before trying to use it
nTries = 0
maxTries = 5
mClient = ComponentMonitoringClient()
result = mClient.ping()
while not result["OK"] and nTries < maxTries:
time.sleep(3)
result = mClient.ping()
nTries = nTries + 1
if not result["OK"]:
self._errMsg(
"ComponentMonitoring service taking too long to start, won't be logged into the database"
)
return
result = MonitoringUtilities.monitorInstallation(
"DB", system, "InstalledComponentsDB", cpu=cpu, hostname=hostname, user=user
)
if not result["OK"]:
self._errMsg(f"Error registering installation into database: {result['Message']}")
return
result = MonitoringUtilities.monitorInstallation(
option, system, component, module, cpu=cpu, hostname=hostname, user=user
)
if not result["OK"]:
self._errMsg(f"Error registering installation into database: {result['Message']}")
return
else:
gLogger.notice("Unknown option:", option)
def do_uninstall(self, args):
"""
Uninstall a DIRAC component or host along with all its components
usage:
uninstall db <database>
uninstall host <hostname>
uninstall <-f ForceLogUninstall> <system> <component>
"""
argss = args.split()
if not argss:
gLogger.notice(self.do_uninstall.__doc__)
return
# Retrieve user uninstalling the component
result = getProxyInfo()
if not result["OK"]:
self._errMsg(result["Message"])
user = result["Value"]["username"]
option = argss[0]
if option == "db":
del argss[0]
if not argss:
gLogger.notice(self.do_uninstall.__doc__)
return
component = argss[0]
client = SystemAdministratorClient(self.host, self.port)
result = client.getHostInfo()
if not result["OK"]:
self._errMsg(result["Message"])
return
else:
cpu = result["Value"]["CPUModel"]
hostname = self.host
result = client.getAvailableDatabases()
if not result["OK"]:
self._errMsg(result["Message"])
return
system = result["Value"][component]["System"]
result = MonitoringUtilities.monitorUninstallation(system, component, hostname=hostname, cpu=cpu, user=user)
if not result["OK"]:
self._errMsg(result["Message"])
return
result = client.uninstallDatabase(component)
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice(f"Successfully uninstalled {component}")
elif option == "host":
del argss[0]
if not argss:
gLogger.notice(self.do_uninstall.__doc__)
return
hostname = argss[0]
client = ComponentMonitoringClient()
result = client.hostExists({"HostName": hostname})
if not result["OK"]:
self._errMsg(result["Message"])
else:
if not result["Value"]:
self._errMsg("Given host does not exist")
else:
result = client.getHosts({"HostName": hostname}, True, False)
if not result["OK"]:
self._errMsg(result["Message"])
else:
host = result["Value"][0]
# Remove every installation associated with the host
for installation in host["Installations"]:
result = client.removeInstallations(installation, {}, {"HostName": hostname})
if not result["OK"]:
self._errMsg(result["Message"])
break
# Finally remove the host
result = client.removeHosts({"HostName": hostname})
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice(f"Host {hostname} was successfully removed")
else:
if option == "-f":
force = True
del argss[0]
else:
force = False
if len(argss) != 2:
gLogger.notice(self.do_uninstall.__doc__)
return
system, component = argss
client = SystemAdministratorClient(self.host, self.port)
monitoringClient = ComponentMonitoringClient()
result = monitoringClient.getInstallations(
{"Instance": component, "UnInstallationTime": None},
{"DIRACSystem": system},
{"HostName": self.host},
True,
)
if not result["OK"]:
self._errMsg(result["Message"])
return
if len(result["Value"]) < 1:
self._errMsg("Given component does not exist")
return
if len(result["Value"]) > 1:
self._errMsg("Too many components match")
return
removeLogs = False
if force:
removeLogs = True
else:
if result["Value"][0]["Component"]["Type"] in self.runitComponents:
result = promptUser("Remove logs?", ["y", "n"], "n")
if result["OK"]:
removeLogs = result["Value"] == "y"
result = client.uninstallComponent(system, component, removeLogs)
if not result["OK"]:
self._errMsg(result["Message"])
else:
gLogger.notice(f"Successfully uninstalled {system}/{component}")
result = client.getHostInfo()
if not result["OK"]:
self._errMsg(result["Message"])
return
else:
cpu = result["Value"]["CPUModel"]
hostname = self.host
result = MonitoringUtilities.monitorUninstallation(system, component, hostname=hostname, cpu=cpu, user=user)
if not result["OK"]:
return result
def do_start(self, args):
"""
Start services or agents or database server
usage:
start <system|*> <service|agent|*>
start mysql
"""
argss = args.split()
if len(argss) < 2:
gLogger.notice(self.do_start.__doc__)
return
option = argss[0]
del argss[0]
if option != "mysql":
if len(argss) < 1:
gLogger.notice(self.do_start.__doc__)
return
system = option
if system != "*":
component = argss[0]
else:
component = "*"
client = SystemAdministratorClient(self.host, self.port)
result = client.startComponent(system, component)
if not result["OK"]:
self._errMsg(result["Message"])
else:
if system != "*" and component != "*":
gLogger.notice(f"\n{system}_{component} started successfully, runit status:\n")
else:
gLogger.notice("\nComponents started successfully, runit status:\n")
for comp in result["Value"]:
gLogger.notice((comp.rjust(32), ":", result["Value"][comp]["RunitStatus"]))
else:
gLogger.notice("Not yet implemented")
def do_restart(self, args):
"""
Restart components (services, agents, executors)
usage:
restart <system|*> <service|agent|*>
"""
if not args:
gLogger.notice(self.do_restart.__doc__)
return
argss = args.split()