-
Notifications
You must be signed in to change notification settings - Fork 33
/
admin.py
executable file
·2017 lines (1757 loc) · 73.2 KB
/
admin.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 python
# -*- coding: utf-8 -*-
"""
:author: Josh Moore, josh at glencoesoftware.com
OMERO Grid admin controller
This is a python wrapper around icegridregistry/icegridnode for master
and various other tools needed for administration.
Copyright 2008-2016 Glencoe Software, Inc. All Rights Reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
from __future__ import division
from __future__ import print_function
from builtins import str
from future.utils import bytes_to_native_str
from future.utils import isbytes
from past.utils import old_div
from builtins import object
import re
import os
import sys
import platform
import datetime
import time
from glob import glob
from math import ceil
from zipfile import ZipFile
import omero
import omero.config
from omero.grid import RawAccessRequest
from omero.cli import admin_only
from omero.cli import CLI
from omero.cli import DirectoryType
from omero.cli import NonZeroReturnCode
from omero.cli import DiagnosticsControl
from omero.cli import UserGroupControl
from omero.install.config_parser import PropertyParser
from omero.plugins.prefs import \
WriteableConfigControl, with_config
from omero.install.windows_warning import windows_warning, WINDOWS_WARNING
from omero_ext import portalocker
from omero_ext.path import path
from omero_ext.which import whichall
from omero_ext.argparse import FileType
from omero_version import ice_compatibility
try:
import pywintypes
import win32service
import win32evtlogutil
import win32api
import win32security
has_win32 = True
except ImportError:
has_win32 = False
DEFAULT_WAIT = 300
CHECKUPGRADE_USERAGENT = "test"
HELP = """Administrative tools including starting/stopping OMERO.
Environment variables:
OMERO_MASTER
OMERO_NODE
Configuration properties:
omero.windows.user
omero.windows.pass
omero.windows.servicename
omero.web.application_server.port
omero.web.server_list
""" + "\n" + "="*50 + "\n"
if platform.system() == 'Windows':
HELP += ("\n\n%s" % WINDOWS_WARNING)
class AdminControl(DiagnosticsControl,
WriteableConfigControl,
UserGroupControl):
def _complete(self, text, line, begidx, endidx):
"""
Returns a file after "deploy", "start", or "startasync"
and otherwise delegates to the BaseControl
"""
for s in (" deploy ", " start ", " startasync "):
length = len(s)
i = line.find(s)
if i >= 0:
f = line[i+length:]
return self._complete_file(f)
return WriteableConfigControl._complete(
self, text, line, begidx, endidx)
def _configure(self, parser):
sub = parser.sub()
parser = self._add_diagnostics(parser, sub)
parser.add_argument(
"--all-jars", action="store_true",
help="Show information for all jars")
self.add_error(
"NOT_WINDOWS", 123,
"Not Windows")
self.add_error(
"SETUP", 200,
"Error during service user set up: (%s) %s")
self.add_error(
"RUNNING", 201,
"%s is already running. Use stop first")
self.add_error(
"NO_SERVICE", 202,
"%s service deleted.")
self.add_error(
"BAD_CONFIG", 300,
"Bad configuration: No IceGrid.Node.Data property")
self.add_error(
"WIN_CONFIG", 400, r"""
%s is not in this directory. Aborting...
Please see the installation instructions on modifying
the files for your installation (%s)
with bin\winconfig.bat
""")
self.add_error(
"NO_WIN32", 666,
"Could not import win32service and/or win32evtlogutil")
self.actions = {}
class Action(object):
def __init__(this, name, help, wait=False):
this.parser = sub.add_parser(name, help=help,
description=help)
this.parser.set_defaults(func=getattr(self, name))
self.actions[name] = this.parser
if wait:
this.parser.add_argument(
"--wait", type=float, default=DEFAULT_WAIT,
help="Seconds to wait for operation")
Action(
"start",
"""Start icegridnode daemon and waits for required components to \
come up, i.e. status == 0
If the first argument can be found as a file, it will be deployed as the
application descriptor rather than etc/grid/default.xml. All other arguments
will be used as targets to enable optional sections of the descriptor.
On Windows, two arguments (-u and -w) specify the Windows service Log On As
user credentials. If not specified, omero.windows.user and omero.windows.pass
will be used.""",
wait=True)
Action("startasync", "The same as start but returns immediately",)
Action("restart", "stop && start", wait=True)
Action(
"restartasync", """The same as restart but returns as soon as \
starting has begun.""",
wait=True)
Action("status", """Status of server
Returns with 0 status if a node ping is successful and if some SessionManager
returns an OMERO-specific exception on a bad login. This can be used in shell
scripts, e.g.:
$ omero admin status && echo "server started"
""")
Action(
"stop",
"""Initiates node shutdown and waits for status to return a \
non-0 value""",
wait=True)
Action("stopasync", "The same as stop but returns immediately")
Action(
"deploy",
"""Deploy the given deployment descriptor. See etc/grid/*.xml
If the first argument is not a file path, etc/grid/default.xml will be
deployed by default. Same functionality as start, but requires that the node
already be running. This may automatically restart some server components.""")
Action(
"ice", "Drop user into icegridadmin console or execute arguments")
fixpyramids = Action(
"fixpyramids",
"Remove empty pyramid pixels files (admins only)").parser
removepyramids = Action(
"removepyramids",
"""Remove pyramid pixels files (admins only) according to endianness.
By default pyramids with big and little-endianness will be deleted.
To delete pyramids with little-endianness equals to true use --endian=little.
Examples:
omero admin removepyramids --dry-run
omero admin removepyramids --dry-run --endian=little
omero admin removepyramids --dry-run --imported-after YYYY-mm-dd
""").parser
# See cleanse options below
email = Action(
"email",
"""Send administrative emails to users.
Administrators can contact OMERO users and groups of
users based on configured email settings. A subject
and some text are required. If no text is passed on
the command-line or if "-" is passed, then text will
be read from the standard input.
Examples:
# Send the contents of a file to everyone
# except inactive users.
omero admin email --everyone Subject < some_file.text
# Include inactive users in the email
omero admin email --everyone --inactive ...
# Contact a single group
omero admin email --group-name system \\
Subject short message
# Contact a list of users
omero admin email --user-id 10 \\
--user-name ralph \\
Subject ...
""").parser
email.add_argument(
"subject",
help="Required subject for the mail")
email.add_argument(
"text", nargs="*",
help=("All further arguments are combined "
"to form the body. stdin if none or '-' "
"is given."))
email.add_argument(
"--everyone", action="store_true",
help=("Contact everyone in the system regardless "
"of other arguments."))
email.add_argument(
"--inactive", action="store_true",
help="Do not filter inactive users.")
self._add_wait(email)
self.add_user_and_group_arguments(email,
action="append",
exclusive=False)
Action(
"rewrite",
"""Regenerate the IceGrid configuration files
Regenerates the IceGrid configuration files from the template files and the
current configuration properties. Recalculates the JVM configuration settings
and replaces the memory settings as well as the port and host properties under
the corresponding application descriptors.
""")
Action(
"jvmcfg",
"Display JVM configuration settings based on the current system")
Action(
"waitup",
"Used by start after calling startasync to wait on status==0",
wait=True)
Action(
"waitdown",
"Used by stop after calling stopasync to wait on status!=0",
wait=True)
reindex = Action(
"reindex",
"""Re-index the Lucene index
Command-line tool for re-indexing the database. This command must be run on the
machine where the FullText directory is located. In most cases, you will want
to disable the background indexer before running most of these commands.
See https://docs.openmicroscopy.org/latest/omero/sysadmins/search.html
for more information.
Examples:
# 1. Reset the 'last indexed' counter. Defaults to 0
omero admin reindex --reset 0
# 2. Delete the contents of a corrupt FullText directory
omero admin reindex --wipe
# 3. Run indexer in the foreground. Disable the background first
omero admin reindex --foreground
# Foreground indexing is NOT currently working.
Other commands (usually unnecessary):
# Index all objects in the database.
omero admin reindex --full
# Index one specific class
omero admin reindex --class ome.model.core.Image
# Passing arguments to Java
JAVA_OPTS="-Dlogback.configurationFile=stderr.xml" \\
omero admin reindex --foreground
JAVA_OPTS="-Xdebug -Xrunjdwp:server=y,transport=\
dt_socket,address=8787,suspend=y" \\
omero admin reindex --foreground
""").parser
reindex.add_argument(
"--jdwp", action="store_true",
help="Activate remote debugging")
reindex.add_argument(
"--mem", default="1024m",
help="Heap size to use")
reindex.add_argument(
"--batch", default="500",
help="Number of items to index before reporting status")
reindex.add_argument(
"--merge-factor", "--merge_factor", default="100",
help=("Higher means merge less frequently. "
"Faster but needs more RAM"))
reindex.add_argument(
"--ram-buffer-size", "--ram_buffer_size", default="1000",
help=("Number of MBs to use for the indexing. "
"Higher is faster."))
reindex.add_argument(
"--lock-factory", "--lock_factory", default="native",
help=("Choose Lucene lock factory by class or "
"'native', 'simple', 'none'"))
group = reindex.add_mutually_exclusive_group()
group.add_argument(
"--prepare", action="store_true",
help="Disables the background indexer in preparation for indexing")
group.add_argument(
"--full", action="store_true",
help="Reindexes all non-excluded tables sequentially")
group.add_argument(
"--events", action="store_true",
help="Reindexes all non-excluded event logs chronologically")
group.add_argument(
"--reset", default=None,
help="Reset the index counter")
group.add_argument(
"--dryrun", action="store_true",
help=("Run through all events, incrementing the counter. "
"NO INDEXING OCCURS"))
group.add_argument(
"--foreground", action="store_true",
help=("Run indexer in the foreground"))
group.add_argument(
"--class", nargs="+",
help="Reindexes the given classes sequentially")
group.add_argument(
"--wipe", action="store_true",
help="Delete the existing index files")
group.add_argument(
"--finish", action="store_true",
help="Re-enables the background indexer after for indexing")
sessionlist = Action(
"sessionlist", "List currently running sessions (deprecated)") \
.parser
sessionlist.add_login_arguments()
cleanse = Action("cleanse", """Remove binary data files from OMERO (admins only)
Deleting an object from OMERO currently may not remove all the binary data.
Use this command either manually or in a cron job periodically to remove
Pixels, empty directories, and other data.
This is done by checking that for all the files in the given directory, a
matching entry exists on the server. THE /OMERO DIRECTORY MUST MATCH THE
DATABASE YOU ARE RUNNING AGAINST.
This command must be run on the machine where, for example, /OMERO/ is
located.
Examples:
omero admin cleanse --dry-run /OMERO # Lists files that will be \
deleted
omero admin cleanse /OMERO # Actually delete them.
omero admin cleanse /volumes/data/OMERO # Delete from a standard \
location.
""").parser
for x in (cleanse, fixpyramids):
x.add_argument(
"--dry-run", action="store_true",
help="Print out which files would be deleted")
x.add_argument(
"data_dir", type=DirectoryType(),
help="omero.data.dir directory value e.g. /OMERO")
x.add_login_arguments()
removepyramids.add_argument(
"--dry-run", action="store_true",
help="Print out which files would be deleted")
removepyramids.add_argument(
"--endian", choices=("little", "big", "both"), default="both",
help="Delete pyramid with given endianness. "
"If not specified, all will be removed.")
removepyramids.add_argument(
"--imported-after", metavar="DATE",
help="Delete pyramid imported after a given date. "
"Expected format YYYY-mm-dd")
removepyramids.add_argument(
"--limit", metavar="MAX_NUMBER",
help="Set the limit of pyramids to remove in one call. "
"Values greater than 500 (default) are not supported")
removepyramids.add_login_arguments()
self._add_wait(removepyramids)
Action("checkwindows", "Run simple check of the local installation "
"(Windows-only)")
Action("checkice", "Run simple check of the Ice installation")
Action("events", "Print event log (Windows-only)")
Action(
"checkupgrade", "Check whether a server upgrade is available")
log = Action("log", "Add a custom log message to "
"the server log").parser
log.add_argument(
"--level",
help="The log level: trace, debug, info, warn or error "
"(default: info)", default="info")
log.add_argument(
"repo",
help="The repo uuid (e.g. ScriptRepo)")
log.add_argument(
"message",
help="The log message to add")
log.add_login_arguments()
self.actions["ice"].add_argument(
"argument", nargs="*",
help="""Arguments joined together to make an Ice command. If not \
present, the user will enter a console""")
self.actions["status"].add_argument(
"node", nargs="?", default="master")
self.actions["status"].add_argument(
"--nodeonly", action="store_true",
help="If set, then only tests if the icegridnode is running")
for name in ("start", "startasync", "restart", "restartasync", "stop",
"stopasync"):
self.actions[name].add_argument(
"--force-rewrite", action="store_true",
help="Force the configuration to be rewritten before checking"
" the server status")
for name in ("start", "restart"):
self.actions[name].add_argument(
"--foreground", action="store_true",
help="Start server in foreground mode (no daemon/service)")
for name in ("start", "startasync", "restart", "restartasync"):
self.actions[name].add_argument(
"-u", "--user",
help="Windows Service Log On As user name.")
self.actions[name].add_argument(
"-w", "--password", metavar="PW",
help="Windows Service Log On As user password.")
for name in ("start", "startasync", "deploy", "restart",
"restartasync"):
self.actions[name].add_argument(
"file", nargs="?",
help="Application descriptor. If not provided, a default"
" will be used")
self.actions[name].add_argument(
"targets", nargs="*",
help="Targets within the application descriptor which "
" should be activated. Common values are: \"debug\", "
"\"trace\" ")
# DISABLED = """ see: http://www.zeroc.com/forums/bug-reports/\
# 4237-sporadic-freeze-errors-concurrent-icegridnode-access.html
# restart [filename] [targets] : Calls stop followed by start \
# args
# restartasync [filename] [targets] : Calls stop followed by \
# startasync args
# """
#
# Windows utility methods
#
if has_win32:
def _get_service_name(unused, config):
try:
return config.as_map()["omero.windows.servicename"]
except KeyError:
return 'OMERO'
def _query_service(unused, svc_name):
hscm = win32service.OpenSCManager(
None, None, win32service.SC_MANAGER_ALL_ACCESS)
try:
try:
hs = win32service.OpenService(
hscm, svc_name, win32service.SERVICE_ALL_ACCESS)
except Exception:
return "DOESNOTEXIST"
try:
q = win32service.QueryServiceStatus(hs)
type, state, ctrl, err, svcerr, svccp, svcwh = q
if state == win32service.SERVICE_STOPPED:
return "STOPPED"
else:
return "unknown"
finally:
win32service.CloseServiceHandle(hs)
finally:
win32service.CloseServiceHandle(hscm)
def _stop_service(self, svc_name):
hscm = win32service.OpenSCManager(
None, None, win32service.SC_MANAGER_ALL_ACCESS)
try:
hs = win32service.OpenService(
hscm, svc_name, win32service.SC_MANAGER_ALL_ACCESS)
win32service.ControlService(
hs, win32service.SERVICE_CONTROL_STOP)
win32service.DeleteService(hs)
self.ctx.out("%s service deleted." % svc_name)
finally:
win32service.CloseServiceHandle(hs)
win32service.CloseServiceHandle(hscm)
def _start_service(self, config, descript, svc_name, pasw, user):
output = self._query_service(svc_name)
# Now check if the server exists
if 0 <= output.find("DOESNOTEXIST"):
binpath = """icegridnode.exe "%s" --deploy "%s" --service\
%s""" % (self._icecfg(), descript, svc_name)
# By default: "NT Authority\Local System"
if not user:
try:
user = config.as_map()["omero.windows.user"]
except KeyError:
user = None
if user is not None and len(user) > 0:
if "\\" not in user:
computername = win32api.GetComputerName()
user = "\\".join([computername, user])
try:
# See #9967, code based on http://mail.python.org/\
# pipermail/python-win32/2010-October/010791.html
self.ctx.out("Granting SeServiceLogonRight to service"
" user \"%s\"" % user)
policy_handle = win32security.LsaOpenPolicy(
None, win32security.POLICY_ALL_ACCESS)
sid_obj, domain, tmp = \
win32security.LookupAccountName(None, user)
win32security.LsaAddAccountRights(
policy_handle, sid_obj, ('SeServiceLogonRight',))
win32security.LsaClose(policy_handle)
except pywintypes.error as details:
self.raise_error("SETUP", details[0], details[2])
if not pasw:
try:
pasw = config.as_map()["omero.windows.pass"]
except KeyError:
pasw = self._ask_for_password(
" for service user \"%s\"" % user)
else:
pasw = None
hscm = win32service.OpenSCManager(
None, None, win32service.SC_MANAGER_ALL_ACCESS)
try:
self.ctx.out("Installing %s Windows service." % svc_name)
hs = win32service.CreateService(
hscm, svc_name, svc_name,
win32service.SERVICE_ALL_ACCESS,
win32service.SERVICE_WIN32_OWN_PROCESS,
win32service.SERVICE_AUTO_START,
win32service.SERVICE_ERROR_NORMAL, binpath, None, 0,
None, user, pasw)
self.ctx.out("Successfully installed %s Windows service."
% svc_name)
win32service.CloseServiceHandle(hs)
finally:
win32service.CloseServiceHandle(hscm)
# Then check if the server is already running
if 0 <= output.find("RUNNING"):
self.raise_error("RUNNING", svc_name)
# Finally, try to start the service - delete if startup fails
hscm = win32service.OpenSCManager(
None, None, win32service.SC_MANAGER_ALL_ACCESS)
try:
try:
hs = win32service.OpenService(
hscm, svc_name, win32service.SC_MANAGER_ALL_ACCESS)
win32service.StartService(hs, None)
self.ctx.out("Starting %s Windows service." % svc_name)
except pywintypes.error as details:
self.ctx.out("%s service startup failed: (%s) %s"
% (svc_name, details[0], details[2]))
win32service.DeleteService(hs)
self.raise_error("NO_SERVICE", svc_name)
finally:
win32service.CloseServiceHandle(hs)
win32service.CloseServiceHandle(hscm)
def events(self, svc_name):
def DumpRecord(record):
if str(record.SourceName) == svc_name:
self.ctx.out("Time: %s" % record.TimeWritten)
self.ctx.out("Rec: %s" % record.RecordNumber)
for si in record.StringInserts:
self.ctx.out(si)
self.ctx.out("="*20)
win32evtlogutil.FeedEventLogRecords(DumpRecord)
else:
def events(self, svc_name):
self.raise_error("NO_WIN32")
def _query_service(self, svc_name):
self.raise_error("NO_WIN32")
def _start_service(self, config, descript, svc_name, pasw, user):
self.raise_error("NO_WIN32")
def _stop_service(self, svc_name):
self.raise_error("NO_WIN32")
#
# End Windows Methods
#
def _node(self, omero_node=None):
"""
Overrides the regular node() logic to return the value of
OMERO_MASTER or "master"
"""
if omero_node is not None:
os.environ["OMERO_MASTER"] = omero_node
if "OMERO_MASTER" in os.environ:
return os.environ["OMERO_MASTER"]
else:
return "master"
def _get_etc_dir(self):
"""Return path to directory containing configuration files"""
return old_div(self.ctx.dir, "etc")
def _get_grid_dir(self):
"""Return path to directory containing Gridconfiguration files"""
return old_div(self._get_etc_dir(), "grid")
def _get_templates_dir(self):
"""Return path to directory containing templates"""
return self.ctx.dir / "etc" / "templates"
def _cmd(self, *command_arguments):
"""
Used to generate an icegridadmin command line argument list
"""
command = ["icegridadmin", self._intcfg()]
command.extend(command_arguments)
return command
def _descript(self, args):
if args.file is not None:
# Relative to cwd
descript = path(args.file).abspath()
if not descript.exists():
self.ctx.dbg("No such file: %s -- Using as target" % descript)
args.targets.insert(0, args.file)
descript = None
else:
descript = None
if descript is None:
__d__ = "default.xml"
if self._isWindows():
__d__ = "windefault.xml"
descript = old_div(self._get_grid_dir(), __d__)
self.ctx.err("No descriptor given. Using %s"
% os.path.sep.join(["etc", "grid", __d__]))
return descript
def checkwindows(self, args):
r"""
Checks that the templates file as defined in etc\Windows.cfg
can be found.
"""
self.check_access(os.R_OK)
if not self._isWindows():
self.raise_error("NOT_WINDOWS")
import Ice
key = "IceGrid.Node.Data"
properties = Ice.createProperties([self._icecfg()])
nodedata = properties.getProperty(key)
if not nodedata:
self.raise_error("BAD_CONFIG")
nodepath = path(nodedata)
pp = nodepath.parpath(self.ctx.dir)
if pp:
return
if nodepath == r"c:\omero_dist\var\master":
self.ctx.out("Found default value: %s" % nodepath)
self.ctx.out("Attempting to correct...")
from omero.install.win_set_path import win_set_path
count = win_set_path(dir=self.ctx.dir)
if count:
return
self.raise_error("WIN_CONFIG", nodedata, self.ctx.dir)
##############################################
#
# Commands
#
@with_config
def startasync(self, args, config):
"""
First checks for a valid installation, then checks the grid,
then registers the action: "node HOST start"
"""
self.check_access(mask=os.R_OK, config=config)
self.checkice()
self.check_node(args)
if not self.check_internal_cfg() or args.force_rewrite:
self.rewrite(args, config, force=True)
if 0 == self.status(args, node_only=True, can_force_rewrite=True):
self.ctx.die(876, "Server already running")
if not args.force_rewrite:
self.rewrite(args, config)
if self._isWindows():
self.checkwindows(args)
self.check_lock(config)
try:
config['omero.db.poolsize']
except KeyError:
self.ctx.out(
"WARNING: Your server has not been configured for production "
"use.\nSee https://docs.openmicroscopy.org/omero/latest/"
"sysadmins/server-performance.html?highlight=poolsize\n"
"for more information.")
self._initDir()
# Do a check to see if we've started before.
self._regdata()
self.check([])
command = None
descript = self._descript(args)
foreground = hasattr(args, "foreground") and args.foreground
if self._isWindows():
if foreground:
command = """icegridnode.exe "%s" --deploy "%s" %s\
""" % (self._icecfg(), descript, args.targets)
else:
user = args.user
pasw = args.password
svc_name = "%s.%s" % (
self._get_service_name(config), args.node)
self._start_service(config, descript, svc_name, pasw, user)
else:
if foreground:
command = ["icegridnode", "--nochdir", self._icecfg(),
"--deploy", str(descript)] + args.targets
else:
command = ["icegridnode", "--daemon", "--pidfile",
str(self._pid()), "--nochdir", self._icecfg(),
"--deploy", str(descript)] + args.targets
if command is not None:
self.ctx.rv = self.ctx.call(command)
@with_config
def start(self, args, config):
self.startasync(args, config)
try:
self.waitup(args)
except NonZeroReturnCode as nzrc:
# stop() may itself throw,
# if it does not, then we rethrow
# the original
self.ctx.err('Calling "stop" on remaining components')
self.stop(args, config)
raise nzrc
@with_config
def deploy(self, args, config):
self.rewrite(args, config)
self.check_access()
self.checkice()
descript = self._descript(args)
# TODO : Doesn't properly handle whitespace
# Though users can workaround with something like:
# omero admin deploy etc/grid/a\\\\ b.xml
command = ["icegridadmin", self._intcfg(), "-e",
" ".join(["application", "update", str(descript)] +
args.targets)]
self.ctx.call(command)
def check_internal_cfg(self):
internal_cfg = self._cfglist()[0]
return os.path.exists(internal_cfg)
@windows_warning
def status(self, args, node_only=False, can_force_rewrite=False):
self.check_node(args)
if not self.check_internal_cfg():
error_msg = 'Missing internal configuration.'
if can_force_rewrite:
error_msg += ' Pass --force-rewrite to the command.'
else:
error_msg += ' Run `omero admin rewrite`.'
self.ctx.die(574, error_msg)
command = self._cmd("-e", "node ping %s" % self._node())
self.ctx.rv = self.ctx.popen(command).wait() # popen
# node_only implies that "up" need not check for all
# of blitz to be accessible but just that if the node
# is running.
if not node_only:
node_only = getattr(args, "nodeonly", False)
if self.ctx.rv == 0 and not node_only:
try:
import Ice
ic = Ice.initialize([self._intcfg()])
try:
sm = self.session_manager(ic)
try:
sm.create("####### STATUS CHECK ########", None)
# Not adding "omero.client.uuid"
except omero.WrappedCreateSessionException:
# Only the server will throw one of these
self.ctx.dbg("Server reachable")
self.ctx.rv = 0
finally:
ic.destroy()
except Exception as exc:
self.ctx.rv = 1
self.ctx.dbg("Server not reachable: "+str(exc))
return self.ctx.rv
def wait_for_icedb(self, args, config):
"""
Since the stop and start are separately protected by
the lock on config.xml, we need to wait for some time
to hopefully let the icegridnode process release the
file locks.
"""
self.ctx.sleep(1) # put in sleep to try to prevent "db locked" (#7325)
@with_config
def restart(self, args, config):
if not self.stop(args, config):
self.ctx.die(54, "Failed to shutdown")
self.wait_for_icedb(args, config)
self.start(args, config)
@with_config
def restartasync(self, args, config):
if not self.stop(args, config):
self.ctx.die(54, "Failed to shutdown")
self.wait_for_icedb(args, config)
self.startasync(args, config)
def waitup(self, args):
"""
Loops 30 times with 10 second pauses waiting for status()
to return 0. If it does not, then ctx.die() is called.
"""
self.check_access(os.R_OK)
self.ctx.out("Waiting on startup. Use CTRL-C to exit")
count, loop_secs, time_msg = self.loops_and_wait(args)
while True:
count = count - 1
if count == 0:
self.ctx.die(43, "\nFailed to startup some components after"
" %s" % time_msg)
elif 0 == self.status(args, node_only=False):
break
else:
self.ctx.out(".", newline=False)
self.ctx.sleep(loop_secs)
def waitdown(self, args):
"""
Returns true if the server went down
"""
self.check_access(os.R_OK)
self.ctx.out("Waiting on shutdown. Use CTRL-C to exit")
count, loop_secs, time_msg = self.loops_and_wait(args)
while True:
count = count - 1
if count == 0:
self.ctx.die(44, "\nFailed to shutdown some components after"
" %s" % time_msg)
return False
elif 0 != self.status(args, node_only=True):
break
else:
self.ctx.out(".", newline=False)
self.ctx.sleep(loop_secs)
self.ctx.rv = 0
return True
def loops_and_wait(self, args):
"""
If present, get the wait time from the args argument
and calculate the number of loops and the wait time
needed. If not present in args, use a default value.
"""
if not hasattr(args, "wait"):
# This might happen if a new command starts using
# waitup/waitdown without setting wait=True for
# Action()
args.wait = DEFAULT_WAIT
total_secs = args.wait
loop_secs = old_div(total_secs, 30.0)
return 30, loop_secs, "%s seconds" % total_secs
@with_config
def stopasync(self, args, config):
"""
Returns true if the server was already stopped
"""
self.check_node(args)
if args.force_rewrite:
self.rewrite(args, config, force=True)
if 0 != self.status(args, node_only=True, can_force_rewrite=True):
self.ctx.err("Server not running")
return True
elif self._isWindows():
svc_name = "%s.%s" % (self._get_service_name(config), args.node)
output = self._query_service(svc_name)
if 0 <= output.find("DOESNOTEXIST"):
self.ctx.die(203, "%s does not exist. Use 'start' first."
% svc_name)
self._stop_service(svc_name)
else:
command = self._cmd("-e", "node shutdown %s" % self._node())
try:
self.ctx.call(command)
except NonZeroReturnCode as nzrc:
self.ctx.rv = nzrc.rv
self.ctx.out("Was the server already stopped?")
@with_config
def stop(self, args, config):
if not self.stopasync(args, config):