forked from ome/openmicroscopy
/
cli.py
executable file
·2401 lines (2064 loc) · 79.3 KB
/
cli.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 -*-
"""
Python driver for OMERO
Provides access to various OMERO.blitz server- and client-side
utilities, including starting and stopping servers, running
analyses, configuration, and more.
Usable via the ./omero script provided with the distribution
as well as from python via "import omero.cli; omero.cli.argv()"
Arguments are taken from (in order of priority): the run method
arguments, sys.argv, and finally from standard-in using the
cmd.Cmd.cmdloop method.
Josh Moore, josh at glencoesoftware.com
Copyright (c) 2007-2015, Glencoe Software, Inc.
See LICENSE for details.
"""
sys = __import__("sys")
cmd = __import__("cmd")
import re
import os
import subprocess
import socket
import traceback
import glob
import platform
import time
import shlex
import errno
from threading import Lock
from path import path
from omero_ext.argparse import ArgumentError
from omero_ext.argparse import ArgumentTypeError
from omero_ext.argparse import ArgumentParser
from omero_ext.argparse import FileType
from omero_ext.argparse import Namespace
from omero_ext.argparse import _SubParsersAction
# Help text
from omero_ext.argparse import RawTextHelpFormatter
from omero_ext.argparse import SUPPRESS
from omero.util.concurrency import get_event
import omero
#
# Static setup
#
try:
from omero_version import omero_version
VERSION = omero_version
except ImportError:
VERSION = "Unknown" # Usually during testing
DEBUG = 0
if "DEBUG" in os.environ:
try:
DEBUG = int(os.environ["DEBUG"])
except ValueError:
DEBUG = 1
print "Deprecated warning: use the 'bin/omero --debug=x [args]' to debug"
print "Running omero with debugging == 1"
OMERODOC = """
Command-line tool for local and remote interactions with OMERO.
"""
OMEROSHELL = """OMERO Python Shell. Version %s""" % str(VERSION)
OMEROHELP = """Type "help" for more information, "quit" or Ctrl-D to exit"""
OMEROSUBS = """Use %(prog)s <subcommand> -h for more information."""
OMEROSUBM = """<subcommand>"""
OMEROCLI = path(__file__).expand().dirname()
OMERODIR = os.getenv('OMERODIR', None)
if OMERODIR is not None:
OMERODIR = path(OMERODIR)
else:
OMERODIR = OMEROCLI.dirname().dirname().dirname()
COMMENT = re.compile("^\s*#")
RELFILE = re.compile("^\w")
LINEWSP = re.compile("^\s*\w+\s+")
#
# Possibilities:
# - Always return and print any output
# - Have a callback on the fired event
# - how should state machine work?
# -- is the last control stored somwhere? in a stack history[3]
# -- or do they all share a central memory? self.ctx["MY_VARIABLE"]
# - In almost all cases, mark a flag in the CLI "lastError" and continue,
# allowing users to do something of the form: on_success or on_fail
#####################################################
#
# Exceptions
#
class NonZeroReturnCode(Exception):
def __init__(self, rv, *args):
self.rv = rv
Exception.__init__(self, *args)
#####################################################
#
class HelpFormatter(RawTextHelpFormatter):
"""
argparse.HelpFormatter subclass which cleans up our usage, preventing very
long lines in subcommands.
"""
def __init__(self, prog, indent_increment=2, max_help_position=40,
width=None):
RawTextHelpFormatter.__init__(
self, prog, indent_increment, max_help_position, width)
self._action_max_length = 20
def _split_lines(self, text, width):
return [text.splitlines()[0]]
class _Section(RawTextHelpFormatter._Section):
def __init__(self, formatter, parent, heading=None):
# if heading:
# heading = "\n%s\n%s" % ("=" * 40, heading)
RawTextHelpFormatter._Section.__init__(
self, formatter, parent, heading)
class WriteOnceNamespace(Namespace):
"""
Namespace subclass which prevents overwriting any values by accident.
"""
def __setattr__(self, name, value):
if hasattr(self, name):
raise Exception("%s already has field %s"
% (self.__class__.__name__, name))
else:
return Namespace.__setattr__(self, name, value)
class Parser(ArgumentParser):
"""
Extension of ArgumentParser for simplifying the
_configure() code in most Controls
"""
def __init__(self, *args, **kwargs):
kwargs["formatter_class"] = HelpFormatter
ArgumentParser.__init__(self, *args, **kwargs)
self._positionals.title = "Positional Arguments"
self._optionals.title = "Optional Arguments"
self._optionals.description = "In addition to any higher level options"
self._sort_args = True
def sub(self):
return self.add_subparsers(
title="Subcommands", description=OMEROSUBS, metavar=OMEROSUBM)
def add(self, sub, func, help=None, **kwargs):
if help is None:
help = func.__doc__
parser = sub.add_parser(
func.im_func.__name__, help=help, description=help)
parser.set_defaults(func=func, **kwargs)
return parser
def add_limit_arguments(self):
self.add_argument(
"--limit", help="maximum number of return values (default=25)",
type=int, default=25)
self.add_argument(
"--offset", help="number of entries to skip (default=0)",
type=int, default=0)
def add_style_argument(self):
from omero.util.text import list_styles
self.add_argument(
"--style", help="use alternative output style (default=sql)",
choices=list_styles())
def add_login_arguments(self):
group = self.add_argument_group(
'Login arguments', ENV_HELP + """
Optional session arguments:
""")
group.add_argument(
"-C", "--create", action="store_true",
help="Create a new session regardless of existing ones")
group.add_argument("-s", "--server", help="OMERO server hostname")
group.add_argument("-p", "--port", help="OMERO server port")
group.add_argument("-g", "--group", help="OMERO server default group")
group.add_argument("-u", "--user", help="OMERO username")
group.add_argument("-w", "--password", help="OMERO password")
group.add_argument(
"-k", "--key",
help="OMERO session key (UUID of an active session)")
group.add_argument(
"--sudo", metavar="ADMINUSER",
help="Create session as this admin. Changes meaning of password!")
group.add_argument(
"-q", "--quiet", action="store_true",
help="Quiet mode. Causes most warning and diagnostic messages to "
"be suppressed.")
def add_group_print_arguments(self):
printgroup = self.add_mutually_exclusive_group()
printgroup.add_argument(
"--long", action="store_true", default=True,
help="Print comma-separated list of all groups (default)")
printgroup.add_argument(
"--count", action="store_true", default=False,
help="Print count of all groups")
def add_user_print_arguments(self):
printgroup = self.add_mutually_exclusive_group()
printgroup.add_argument(
"--count", action="store_true", default=True,
help="Print count of all users and owners (default)")
printgroup.add_argument(
"--long", action="store_true", default=False,
help="Print comma-separated list of all users and owners")
def add_user_sorting_arguments(self):
sortgroup = self.add_mutually_exclusive_group()
sortgroup.add_argument(
"--sort-by-id", action="store_true", default=True,
help="Sort users by ID (default)")
sortgroup.add_argument(
"--sort-by-login", action="store_true", default=False,
help="Sort users by login")
sortgroup.add_argument(
"--sort-by-first-name", action="store_true", default=False,
help="Sort users by first name")
sortgroup.add_argument(
"--sort-by-last-name", action="store_true", default=False,
help="Sort users by last name")
sortgroup.add_argument(
"--sort-by-email", action="store_true", default=False,
help="Sort users by email")
def add_group_sorting_arguments(self):
sortgroup = self.add_mutually_exclusive_group()
sortgroup.add_argument(
"--sort-by-id", action="store_true", default=True,
help="Sort groups by ID (default)")
sortgroup.add_argument(
"--sort-by-name", action="store_true", default=False,
help="Sort groups by name")
def set_args_unsorted(self):
self._sort_args = False
def _check_value(self, action, value):
# converted value must be one of the choices (if specified)
if action.choices is not None and value not in action.choices:
msg = 'invalid choice: %r\n\nchoose from:\n' % value
choices = list(action.choices)
if self._sort_args:
choices = sorted(choices)
msg += self._format_list(choices)
raise ArgumentError(action, msg)
def _format_list(self, choices):
lines = ["\t"]
if choices:
while len(choices) > 1:
choice = choices.pop(0)
lines[-1] += ("%s, " % choice)
if len(lines[-1]) > 62:
lines.append("\t")
lines[-1] += choices.pop(0)
return "\n".join(lines)
class ProxyStringType(object):
"""
To make use of the omero.proxy_to_instance method,
an instance can be passed to add_argument with a default
value: add_argument(..., type=ProxyStringType("Image"))
which will take either a proxy string of the form:
"Image:1" or simply the ID itself: "1"
"""
def __init__(self, default=None):
self.default = default
def __call__(self, s):
try:
return omero.proxy_to_instance(s, default=self.default)
except omero.ClientError, ce:
raise ValueError(str(ce))
def __repr__(self):
return "proxy"
class NewFileType(FileType):
"""
Extension of the argparse.FileType to prevent
overwrite existing files.
"""
def __call__(self, s):
if s != "-" and os.path.exists(s):
raise ArgumentTypeError("File exists: %s" % s)
return FileType.__call__(self, s)
class ExistingFile(FileType):
"""
Extension of the argparse.FileType that requires
an existing file.
"""
def __call__(self, s):
if s != "-" and not os.path.exists(s):
raise ArgumentTypeError("File does not exist: %s" % s)
if s != "-":
return FileType.__call__(self, s)
else:
return s
class DirectoryType(FileType):
"""
Extension of the argparse.FileType to only allow
existing directories.
"""
def __call__(self, s):
p = path(s)
if not p.exists():
raise ArgumentTypeError("Directory does not exist: %s" % s)
elif not p.isdir():
raise ArgumentTypeError("Path is not a directory: %s" % s)
return str(p.abspath())
class ExceptionHandler(object):
"""
Location for all logic which maps from server exceptions
to specific states. This could likely be moved elsewhere
for general client-side usage.
"""
def is_constraint_violation(self, ve):
if isinstance(ve, omero.ValidationException):
if "org.hibernate.exception.ConstraintViolationException: " \
"could not insert" in str(ve):
return True
def handle_failed_request(self, rfe):
import Ice
if isinstance(rfe, Ice.OperationNotExistException):
return "Operation not supported by the server: %s" % rfe.operation
else:
return "Unknown Ice.RequestFailedException"
DEBUG_HELP = """
Set debug options for developers
The value to the debug argument is a comma-separated list of commands.
Available debugging choices:
'0' Disable debugging
'debug' Enable debugging at the first debug level
'1'-'9' Enable debugging at the specified debug level
'trace' Run the command with tracing enabled
'profile' Run the command with profiling enabled
Note "trace" and "profile" cannot be used simultaneously
Examples:
# Enabled debugging at level 1 and prints tracing
bin/omero --debug=debug,trace admin start
# Enabled debugging at level 1
bin/omero -d1 admin start
# Enabled debugging at level 3
bin/omero -d3 admin start
# Enable profiling
bin/omero -dp admin start
# Fails - cannot print tracing and profiling together
bin/omero -dt,p admin start
# Disable debugging
bin/omero -d0 admin start
"""
ENV_HELP = """Environment variables:
OMERO_USERDIR Set the base directory containing the user's files.
Default: $HOME/omero
OMERO_SESSIONDIR Set the base directory containing local sessions.
Default: $OMERO_USERDIR/sessions
OMERO_TMPDIR Set the base directory containing temporary files.
Default: $OMERO_USERDIR/tmp
"""
class Context:
"""Simple context used for default logic. The CLI registry which registers
the plugins installs itself as a fully functional Context.
The Context class is designed to increase pluggability. Rather than
making calls directly on other plugins directly, the pub() method
routes messages to other commands. Similarly, out() and err() should
be used for printing statements to the user, and die() should be
used for exiting fatally.
"""
def __init__(self, controls=None, params=None, prog=sys.argv[0]):
self.controls = controls
if self.controls is None:
self.controls = {}
self.params = params
if self.params is None:
self.params = {}
self.event = get_event(name="CLI")
self.dir = OMERODIR
self.isquiet = False
# This usage will go away and default will be False
self.isdebug = DEBUG
self.topics = {"debug": DEBUG_HELP, "env": ENV_HELP}
self.parser = Parser(prog=prog, description=OMERODOC)
self.subparsers = self.parser_init(self.parser)
def post_process(self):
"""
Runs further processing once all the controls have been added.
"""
sessions = self.controls["sessions"]
login = self.subparsers.add_parser(
"login", help="Shortcut for 'sessions login'",
description=sessions.login.__doc__)
login.set_defaults(func=lambda args: sessions.login(args))
sessions._configure_login(login)
logout = self.subparsers.add_parser(
"logout", help="Shortcut for 'sessions logout'")
logout.set_defaults(func=lambda args: sessions.logout(args))
sessions._configure_dir(logout)
def parser_init(self, parser):
parser.add_argument(
"-v", "--version", action="version",
version="%%(prog)s %s" % VERSION)
parser.add_argument(
"-d", "--debug",
help="Use 'help debug' for more information", default=SUPPRESS)
parser.add_argument(
"--path", action="append",
help="Add file or directory to plugin list. Supports globs.")
parser.add_login_arguments()
subparsers = parser.add_subparsers(
title="Subcommands", description=OMEROSUBS, metavar=OMEROSUBM)
return subparsers
def get(self, key, defvalue=None):
return self.params.get(key, defvalue)
def set(self, key, value=True):
self.params[key] = value
def safePrint(self, text, stream, newline=True):
"""
Prints text to a given string, capturing any exceptions.
"""
try:
stream.write(str(text))
if newline:
stream.write("\n")
else:
stream.flush()
except IOError, e:
if e.errno != errno.EPIPE:
raise
except:
print >>sys.stderr, "Error printing text"
print >>sys.stdout, text
if self.isdebug:
traceback.print_exc()
def pythonpath(self):
"""
Converts the current sys.path to a PYTHONPATH string
to be used by plugins which must start a new process.
Note: this was initially created for running during
testing when PYTHONPATH is not properly set.
"""
path = list(sys.path)
for i in range(0, len(path) - 1):
if path[i] == '':
path[i] = os.getcwd()
pythonpath = ":".join(path)
return pythonpath
def userdir(self):
"""
Returns a user directory (as path.path) which can be used
for storing configuration. The directory is guaranteed to
exist and be private (700) after execution.
"""
dir = path(os.path.expanduser("~")) / "omero" / "cli"
if not dir.exists():
dir.mkdir()
elif not dir.isdir():
raise Exception("%s is not a directory" % dir)
dir.chmod(0700)
return dir
def pub(self, args, strict=False):
self.safePrint(str(args), sys.stdout)
def input(self, prompt, hidden=False, required=False):
"""
Reads from standard in. If hidden == True, then
uses getpass
"""
try:
while True:
if hidden:
import getpass
rv = getpass.getpass(prompt)
else:
rv = raw_input(prompt)
if required and not rv:
self.out("Input required")
continue
return rv
except KeyboardInterrupt:
self.die(1, "Cancelled")
def out(self, text, newline=True):
"""
Expects a single string as argument.
"""
self.safePrint(text, sys.stdout, newline)
def err(self, text, newline=True):
"""
Expects a single string as argument.
"""
self.safePrint(text, sys.stderr, newline)
def dbg(self, text, newline=True, level=1):
"""
Passes text to err() if self.isdebug is set
"""
if self.isdebug >= level:
self.err(text, newline)
def die(self, rc, args):
raise Exception((rc, args))
def exit(self, args):
self.out(args)
self.interrupt_loop = True
def call(self, args):
self.out(str(args))
def popen(self, args):
self.out(str(args))
def sleep(self, time):
self.event.wait(time)
#####################################################
#
def admin_only(func):
"""
Checks that the current user is an admin or throws an exception.
"""
def _check_admin(*args, **kwargs):
args = list(args)
self = args[0]
plugin_args = args[1]
client = self.ctx.conn(plugin_args)
ec = client.sf.getAdminService().getEventContext()
if not ec.isAdmin:
self.error_admin_only(fatal=True)
return func(*args, **kwargs)
from omero.util.decorators import wraps
_check_admin = wraps(func)(_check_admin)
return _check_admin
class BaseControl(object):
"""Controls get registered with a CLI instance on loadplugins().
To create a new control, subclass BaseControl, implement _configure,
and end your module with::
try:
register("name", MyControl, HELP)
except:
if __name__ == "__main__":
cli = CLI()
cli.register("name", MyControl, HELP)
cli.invoke(sys.argv[1:])
This module should be put in the omero.plugins package.
All methods which do NOT begin with "_" are assumed to be accessible
to CLI users.
"""
###############################################
#
# Mostly reusable code
#
def __init__(self, ctx=None, dir=OMERODIR):
self.dir = path(dir) # Guaranteed to be a path
self.ctx = ctx
if self.ctx is None:
self.ctx = Context() # Prevents unncessary stop_event creation
def _isWindows(self):
p_s = platform.system()
if p_s == 'Windows':
return True
else:
return False
def _host(self):
"""
Return hostname of current machine. Termed to be the
value return from socket.gethostname() up to the first
decimal.
"""
if not hasattr(self, "hostname") or not self.hostname:
self.hostname = socket.gethostname()
if self.hostname.find(".") > 0:
self.hostname = self.hostname.split(".")[0]
return self.hostname
def _node(self, omero_node=None):
"""
Return the name of this node, using either the environment
vairable OMERO_NODE or _host(). Some subclasses may
override this functionality, most notably "admin" commands
which assume a node name of "master".
If the optional argument is not None, then the OMERO_NODE
environment variable will be set.
"""
if omero_node is not None:
os.environ["OMERO_NODE"] = omero_node
if "OMERO_NODE" in os.environ:
return os.environ["OMERO_NODE"]
else:
return self._host()
def _icedata(self, property):
"""
General data method for creating a path from an Ice property.
"""
try:
nodepath = self._properties()[property]
if RELFILE.match(nodepath):
nodedata = self.dir / path(nodepath)
else:
nodedata = path(nodepath)
created = False
if not nodedata.exists():
self.ctx.out("Creating "+nodedata)
nodedata.makedirs()
created = True
return (nodedata, created)
except KeyError, ke:
self.ctx.err(property + " is not configured")
self.ctx.die(4, str(ke))
def _initDir(self):
"""
Initialize the directory into which the current node will log.
"""
props = self._properties()
self._nodedata()
logdata = self.dir / path(props["Ice.StdOut"]).dirname()
if not logdata.exists():
self.ctx.out("Initializing %s" % logdata)
logdata.makedirs()
def _nodedata(self):
"""
Returns the data directory path for this node. This is determined
from the "IceGrid.Node.Data" property in the _properties()
map.
The directory will be created if it does not exist.
"""
data, created = self._icedata("IceGrid.Node.Data")
return data
def _regdata(self):
"""
Returns the data directory for the IceGrid registry.
This is determined from the "IceGrid.Registry.Data" property
in the _properties() map.
The directory will be created if it does not exist, and
a warning issued.
"""
data, created = self._icedata("IceGrid.Registry.Data")
def _pid(self):
"""
Returns a path of the form _nodedata() / (_node() + ".pid"),
i.e. a file named NODENAME.pid in the node's data directory.
"""
pidfile = self._nodedata() / (self._node() + ".pid")
return pidfile
def _cfglist(self):
"""
Returns a list of configuration files for this node. This
defaults to the internal configuration for all nodes,
followed by a file named NODENAME.cfg under the etc/
directory, following by PLATFORM.cfg if it exists.
"""
cfgs = self.dir / "etc"
internal = cfgs / "internal.cfg"
owncfg = cfgs / self._node() + ".cfg"
results = [internal, owncfg]
# Look for <platform>.cfg
p_s = platform.system()
p_c = cfgs / p_s + ".cfg"
if p_c.exists():
results.append(p_c)
return results
def _icecfg(self):
"""
Uses _cfglist() to return a string argument of the form
"--Ice.Config=..." suitable for passing to omero.client
as an argument.
"""
icecfg = "--Ice.Config=%s" % ",".join(self._cfglist())
return str(icecfg)
def _intcfg(self):
"""
Returns an Ice.Config string with only the internal configuration
file for connecting to the IceGrid Locator.
"""
intcfg = self.dir / "etc" / "internal.cfg"
intcfg.abspath()
return str("--Ice.Config=%s" % intcfg)
def _properties(self, prefix=""):
"""
Loads all files returned by _cfglist() into a new
Ice.Properties instance and return the map from
getPropertiesForPrefix(prefix) where the default is
to return all properties.
"""
import Ice
if getattr(self, "_props", None) is None:
self._props = Ice.createProperties()
for cfg in self._cfglist():
try:
self._props.load(str(cfg))
except Exception:
self.ctx.die(3, "Could not find file: " + cfg +
"\nDid you specify the proper node?")
return self._props.getPropertiesForPrefix(prefix)
def _ask_for_password(self, reason="", root_pass=None, strict=True):
while not root_pass or len(root_pass) < 1:
root_pass = self.ctx.input("Please enter password%s: "
% reason, hidden=True)
if not strict:
return root_pass
if root_pass is None or root_pass == "":
self.ctx.err("Password cannot be empty")
continue
confirm = self.ctx.input("Please re-enter password%s: "
% reason, hidden=True)
if root_pass != confirm:
root_pass = None
self.ctx.err("Passwords don't match")
continue
break
return root_pass
def get_subcommands(self):
"""Return a list of subcommands"""
parser = Parser()
self._configure(parser)
subparsers_actions = [action for action in parser._actions
if isinstance(action, _SubParsersAction)]
subcommands = []
for subparsers_action in subparsers_actions:
for choice, subparser in subparsers_action.choices.items():
subcommands.append(format(choice))
return subcommands
###############################################
#
# Methods likely to be implemented by subclasses
#
def _complete_file(self, f, dir=None):
"""
f: path part
"""
if dir is None:
dir = self.dir
else:
dir = path(dir)
p = path(f)
if p.exists() and p.isdir():
if not f.endswith(os.sep):
return [p.basename()+os.sep]
return [str(x)[len(f):] for x in p.listdir(
unreadable_as_empty=True)]
else:
results = [str(x.basename()) for x in dir.glob(f+"*")]
if len(results) == 1:
# Relative to cwd
maybe_dir = path(results[0])
if maybe_dir.exists() and maybe_dir.isdir():
return [results[0] + os.sep]
return results
def _complete(self, text, line, begidx, endidx):
try:
return self._complete2(text, line, begidx, endidx)
except:
self.ctx.dbg("Complete error: %s" % traceback.format_exc())
def _complete2(self, text, line, begidx, endidx):
items = shlex.split(line)
parser = getattr(self, "parser", None)
if parser:
result = []
actions = getattr(parser, "_actions")
if actions:
if len(items) > 1:
subparsers = [
x for x in actions
if x.__class__.__name__ == "_SubParsersAction"]
if subparsers:
subparsers = subparsers[0] # Guaranteed one
choice = subparsers.choices.get(items[-1])
if choice and choice._actions:
actions = choice._actions
if len(items) > 2:
actions = [] # TBD
for action in actions:
if action.__class__.__name__ == "_HelpAction":
result.append("-h")
elif action.__class__.__name__ == "_SubParsersAction":
result.extend(action.choices)
return ["%s " % x for x in result
if (not text or x.startswith(text)) and
line.find(" %s " % x) < 0]
# Fallback
completions = [method for method in dir(self)
if callable(getattr(self, method))]
return [str(method + " ") for method in completions
if method.startswith(text) and not method.startswith("_")]
def error_admin_only(self, msg="SecurityViolation: Admins only!",
code=111, fatal=True):
if fatal:
self.ctx.die(code, msg)
else:
self.ctx.err(msg)
class CLI(cmd.Cmd, Context):
"""
Command line interface class. Supports various styles of executing the
registered plugins. Each plugin is given the chance to update this class
by adding methods of the form "do_<plugin name>".
"""
class PluginsLoaded(object):
"""
Thread-safe class for storing whether or not all the plugins
have been loaded
"""
def __init__(self):
self.lock = Lock()
self.done = False
def get(self):
self.lock.acquire()
try:
return self.done
finally:
self.lock.release()
def set(self):
self.lock.acquire()
try:
self.done = True
finally:
self.lock.release()
def __init__(self, prog=sys.argv[0]):
"""
Also sets the "_client" field for this instance to None. Each cli
maintains a single active client. The "session" plugin is responsible
for the loading of the client object.
"""
cmd.Cmd.__init__(self)
Context.__init__(self, prog=prog)
self.prompt = 'omero> '
self.interrupt_loop = False
self.rv = 0 #: Return value to be returned
self._stack = [] #: List of commands being processed
self._client = None #: Single client for all activities
#: Paths to be loaded; initially official plugins
self._plugin_paths = [OMEROCLI / "plugins"]
self._pluginsLoaded = CLI.PluginsLoaded()
def assertRC(self):
if self.rv != 0:
raise NonZeroReturnCode(self.rv, "assert failed")
def invoke(self, line, strict=False, previous_args=None):
"""
Copied from cmd.py
"""
try:
line = self.precmd(line)
stop = self.onecmd(line, previous_args)
stop = self.postcmd(stop, line)
if strict:
self.assertRC()
finally:
if len(self._stack) == 0:
self.close()
else:
self.dbg("Delaying close for stack: %s"
% len(self._stack), level=2)
def invokeloop(self):
# First we add a few special commands to the loop
class PWD(BaseControl):
def __call__(self, args):
self.ctx.out(os.getcwd())
class LS(BaseControl):
def __call__(self, args):
for p in sorted(path(os.getcwd()).listdir(
unreadable_as_empty=True)):
self.ctx.out(str(p.basename()))
class CD(BaseControl):
def _complete(self, text, line, begidx, endidx):
RE = re.compile("\s*cd\s*")
m = RE.match(line)
if m:
replaced = RE.sub('', line)
return self._complete_file(replaced, path(os.getcwd()))
return []
def _configure(self, parser):
parser.set_defaults(func=self.__call__)
parser.add_argument("dir", help="Target directory")
def __call__(self, args):
os.chdir(args.dir)
self.register("pwd", PWD, "Print the current directory")
self.register("ls", LS, "Print files in the current directory")
self.register("dir", LS, "Alias for 'ls'")
self.register("cd", CD, "Change the current directory")
try:
self.selfintro = "\n".join([OMEROSHELL, OMEROHELP])
if not self.stdin.isatty():
self.selfintro = ""