-
Notifications
You must be signed in to change notification settings - Fork 23
/
cmdline.py
executable file
·2434 lines (2100 loc) · 92.6 KB
/
cmdline.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
#
# cmdline.py -- Prototypes for GC3Libs-based scripts
#
# Copyright (C) 2010, 2011, 2012, 2014, 2015 University of Zurich
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""Prototype classes for GC3Libs-based scripts.
Classes implemented in this file provide common and recurring
functionality for GC3Libs command-line utilities and scripts. User
applications should implement their specific behavior by subclassing
and overriding a few customization methods.
There are currently two public classes provided here:
:class:`GC3UtilsScript`
Base class for all the GC3Utils commands. Implements a few methods
useful for writing command-line scripts that operate on jobs by ID.
:class:`SessionBasedScript`
Base class for the ``grosetta``/``ggamess``/``gcodeml`` scripts.
Implements a long-running script to submit and manage a large number
of jobs grouped into a "session".
:class:`SessionBasedDaemon`
Base class for GC3Pie daemons. Implements a long-running daemon with
XML-RPC interface and support for file/http/swift based inboxes
"""
__author__ = 'Riccardo Murri <riccardo.murri@uzh.ch>'
__docformat__ = 'reStructuredText'
# stdlib modules
import fnmatch
import logging
from logging.handlers import SysLogHandler
import math
import os
import os.path
import signal
import sys
from prettytable import PrettyTable
import time
import threading
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from collections import defaultdict
from prettytable import PrettyTable
import SimpleXMLRPCServer as sxmlrpc
import xmlrpclib
import json
import yaml
# 3rd party modules
import daemon
import cli # pyCLI
import cli.app
import cli._ext.argparse as argparse
# interface to Gc3libs
import gc3libs
import gc3libs.config
from gc3libs.compat import lockfile
from gc3libs.compat.lockfile.pidlockfile import PIDLockFile
import gc3libs.core
import gc3libs.exceptions
import gc3libs.persistence
import gc3libs.utils
import gc3libs.url
from gc3libs.quantity import Memory, GB, Duration, hours
from gc3libs.session import Session
from gc3libs.poller import get_poller, get_mask_description, events as notify_events
# types for command-line parsing; see
# http://docs.python.org/dev/library/argparse.html#type
def nonnegative_int(num):
"""
Raise `ArgumentTypeError` if `num` is a negative integer (<0), and
return `int(num)` otherwise. `num` can be any object which can be
converted to an int.
>>> nonnegative_int('1')
1
>>> nonnegative_int(1)
1
>>> nonnegative_int('-1') # doctest:+ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: '-1' is not a non-negative integer number.
>>> nonnegative_int(-1) # doctest:+ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: '-1' is not a non-negative integer number.
Please note that `0` and `'-0'` are ok:
>>> nonnegative_int(0)
0
>>> nonnegative_int(-0)
0
>>> nonnegative_int('0')
0
>>> nonnegative_int('-0')
0
Floats are ok too:
>>> nonnegative_int(3.14)
3
>>> nonnegative_int(0.1)
0
>>> nonnegative_int('ThisWillRaiseAnException') # doctest:+ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: 'ThisWillRaiseAnException' is not a non-negative ...
"""
try:
value = int(num)
if value < 0:
raise argparse.ArgumentTypeError(
"'%s' is not a non-negative integer number." % (num,))
return value
except ValueError:
raise argparse.ArgumentTypeError(
"'%s' is not a non-negative integer number." % (num,))
def positive_int(num):
"""
Raise `ArgumentTypeError` if `num` is not a *strictly* positive
integer (>0) and return `int(num)` otherwise. `num` can be any
object which can be converted to an int.
>>> positive_int('1')
1
>>> positive_int(1)
1
>>> positive_int('-1') # doctest:+ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: '-1' is not a positive integer number.
>>> positive_int(-1) # doctest:+ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: '-1' is not a positive integer number.
>>> positive_int(0) # doctest:+ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: '0' is not a positive integer number.
Floats are ok too:
>>> positive_int(3.14)
3
but please take care that float *greater* than 0 will fail:
>>> positive_int(0.1)
Traceback (most recent call last):
...
ArgumentTypeError: '0.1' is not a positive integer number.
Please note that `0` is NOT ok:
>>> positive_int(-0) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: '0' is not a positive integer number.
>>> positive_int('0') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: '0' is not a positive integer number.
>>> positive_int('-0') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: '-0' is not a positive integer number.
Any string which does cannot be converted to an integer will fail:
>>> positive_int('ThisWillRaiseAnException') # doctest:+ELLIPSIS
Traceback (most recent call last):
...
ArgumentTypeError: 'ThisWillRaiseAnException' is not a positive integer ...
"""
try:
value = int(num)
if value <= 0:
raise argparse.ArgumentTypeError(
"'%s' is not a positive integer number." % (num,))
return value
except ValueError:
raise argparse.ArgumentTypeError(
"'%s' is not a positive integer number." % (num,))
def existing_file(path):
gc3libs.utils.test_file(path,
os.F_OK | os.R_OK,
argparse.ArgumentTypeError)
return path
def executable_file(path):
gc3libs.utils.test_file(path,
os.F_OK | os.R_OK | os.X_OK,
argparse.ArgumentTypeError)
return path
def existing_directory(path):
gc3libs.utils.test_file(path,
os.F_OK | os.R_OK | os.X_OK,
argparse.ArgumentTypeError, isdir=True)
return path
def valid_directory(path):
if os.path.exists(path) and not os.path.isdir(path):
raise argparse.ArgumentTypeError(
"path '%s' already exists but is not a directory."
% (path,))
return path
# script classes
class _Script(cli.app.CommandLineApp):
"""
Base class for GC3Libs scripts.
By default, only the standard options ``-h``/``--help`` and
``-V``/``--version`` are considered; to add more, override
`setup_options`:meth:
There is no defaults for positional arguments, you *must* override
`setup_args`:meth: in derived classes.
"""
##
# CUSTOMIZATION METHODS
##
# The following are meant to be freely customized in derived scripts.
##
def setup_args(self):
"""
Set up command-line argument parsing.
The default command line parsing considers every argument as
an (input) path name; processing of the given path names is
done in `parse_args`:meth:
"""
raise NotImplementedError(
"Abstract method `_Script.setup_args()` called,"
" which should have been implemented in a derived class")
def setup_options(self):
"""
Override this method to add command-line options.
"""
pass
def parse_args(self):
"""
Do any parsing of the command-line arguments before the main
loop starts. This is the place to check validity of the
parameters passed as command-line arguments, and to perform
setup of shared data structures and default values.
The default implementation does nothing; you are free to
override this method in derived classes.
"""
pass
def cleanup(self):
"""
Method called when the script is interrupted
"""
pass
##
# pyCLI INTERFACE METHODS
##
# The following methods adapt the behavior of the
# `SessionBasedScript` class to the interface expected by pyCLI
# applications. Think twice before overriding them, and read
# the pyCLI docs before :-)
##
def __init__(self, **extra_args):
"""
Perform initialization and set the version, help and usage
strings.
The help text to be printed when the script is invoked with the
``-h``/``--help`` option will be taken from (in order of preference):
* the keyword argument `description`;
* the attribute `self.description`.
If neither is provided, an `AssertionError` is raised.
The text to output when the the script is invoked with the
``-V``/``--version`` options is taken from (in order of
preference):
* the keyword argument `version`;
* the attribute `self.version`.
If none of these is provided, an `AssertionError` is raised.
The `usage` keyword argument (if provided) will be used to
provide the program help text; if not provided, one will be
generated based on the options and positional arguments
defined in the code.
Any additional keyword argument will be used to set a
corresponding instance attribute on this Python object.
"""
# use keyword arguments to set additional instance attrs
for k, v in extra_args.items():
if k not in ['name', 'description']:
setattr(self, k, v)
# init and setup pyCLI classes
if 'version' not in extra_args:
try:
extra_args['version'] = self.version
except AttributeError:
raise AssertionError("Missing required parameter 'version'.")
if 'description' not in extra_args:
if self.__doc__ is not None:
extra_args['description'] = self.__doc__
else:
raise AssertionError(
"Missing required parameter 'description'.")
# allow overriding command-line options in subclasses
def argparser_factory(*args, **kwargs):
kwargs.setdefault('conflict_handler', 'resolve')
kwargs.setdefault('formatter_class',
cli._ext.argparse.RawDescriptionHelpFormatter)
return cli.app.CommandLineApp.argparser_factory(*args, **kwargs)
self.argparser_factory = argparser_factory
# init superclass
extra_args.setdefault(
'name',
os.path.splitext(
os.path.basename(
sys.argv[0]))[0])
extra_args.setdefault('reraise', Exception)
cli.app.CommandLineApp.__init__(self, **extra_args)
# provide some defaults
self.verbose_logging_threshold = 0
@property
def description(self):
"""A string describing the application.
Unless specified when the :class:`Application` was created, this
property will examine the :attr:`main` callable and use its
docstring (:attr:`__doc__` attribute).
"""
if self._description is not None:
return self._description
else:
return getattr(self.main, "__doc__", '')
def setup(self):
"""
Setup standard command-line parsing.
GC3Utils scripts should probably override `setup_args`:meth:
and `setup_options`:meth: to modify command-line parsing.
"""
# setup of base classes
cli.app.CommandLineApp.setup(self)
self.add_param(
"-v",
"--verbose",
action="count",
dest="verbose",
default=0,
help="Print more detailed information about the program's"
" activity. Increase verbosity each time this option is"
" encountered on the command line.")
self.add_param("--config-files",
action="store",
default=str.join(
',', gc3libs.Default.CONFIG_FILE_LOCATIONS),
help="Comma separated list of configuration files",
)
return
def pre_run(self):
"""
Perform parsing of standard command-line options and call into
`parse_args()` to do non-optional argument processing.
Also sets up the ``gc3.gc3utils`` logger; it is controlled by
the ``-v``/``--verbose`` command-line option. Up to
`self.verbose_logging_threshold` occurrences of ``-v`` are
ignored, after which they start to lower the level of messages
sent to standard error output.
"""
# finish setup
self.setup_options()
self.setup_args()
# parse command-line
cli.app.CommandLineApp.pre_run(self)
# setup GC3Libs logging
loglevel = max(1, logging.WARNING -
10 *
max(0, self.params.verbose -
self.verbose_logging_threshold))
gc3libs.configure_logger(loglevel, "gc3utils") # alternate: self.name
# alternate: ('gc3.' + self.name)
self.log = logging.getLogger('gc3.gc3utils')
self.log.setLevel(loglevel)
self.log.propagate = True
self.log.info("Starting %s at %s; invoked as '%s'",
self.name, time.asctime(), str.join(' ', sys.argv))
# Read config file(s) from command line
self.params.config_files = self.params.config_files.split(',')
# interface to the GC3Libs main functionality
self.config = self._make_config(self.params.config_files)
try:
self._core = gc3libs.core.Core(self.config)
except gc3libs.exceptions.NoResources:
# translate internal error `NoResources` to a
# user-readable message.
raise gc3libs.exceptions.FatalError(
"No computational resources defined."
" Please edit the configuration file(s): '%s'."
% (str.join("', '", self.params.config_files)))
# call hook methods from derived classes
self.parse_args()
def run(self):
"""
Execute `cli.app.Application.run`:meth: if any exception is
raised, catch it, output an error message and then exit with
an appropriate error code.
"""
try:
return cli.app.CommandLineApp.run(self)
except gc3libs.exceptions.InvalidUsage as ex:
# Fatal errors do their own printing, we only add a short usage
# message
sys.stderr.write(
"Type '%s --help' to get usage help.\n" % self.name)
return 64 # EX_USAGE in /usr/include/sysexits.h
except KeyboardInterrupt:
sys.stderr.write(
"%s: Exiting upon user request (Ctrl+C)\n" % self.name)
self.cleanup()
return 13
except SystemExit as ex:
# sys.exit() has been called in `post_run()`.
raise
# the following exception handlers put their error message
# into `msg` and the exit code into `rc`; the closing stanza
# tries to log the message and only outputs it to stderr if
# this fails
except lockfile.Error as ex:
# exc_info = sys.exc_info()
msg = ("Error manipulating the lock file (%s: %s)."
" This likely points to a filesystem error"
" or a stale process holding the lock."
" If you cannot get this command to run after"
" a system reboot, please write to gc3pie@googlegroups.com"
" including any output you got by running '%s -vvvv %s'."
" (You need to be subscribed to post to the mailing list;"
" you can also post without being subscribed by using the"
" web interface at"
" http://dir.gmane.org/gmane.comp.python.gc3pie )")
if len(sys.argv) > 0:
msg %= (ex.__class__.__name__, str(ex),
self.name, str.join(' ', sys.argv[1:]))
else:
msg %= (ex.__class__.__name__, str(ex), self.name, '')
# rc = 1
except AssertionError as ex:
# exc_info = sys.exc_info()
msg = ("BUG: %s\n"
"Please send an email to gc3pie@googlegroups.com"
" including any output you got by running '%s -vvvv %s'."
" (You need to be subscribed to post to the mailing list;"
" you can also post without being subscribed by using the"
" web interface at"
" http://dir.gmane.org/gmane.comp.python.gc3pie )"
" Thanks for your cooperation!")
if len(sys.argv) > 0:
msg %= (str(ex), self.name, str.join(' ', sys.argv[1:]))
else:
msg %= (str(ex), self.name, '')
# rc = 1
except cli.app.Abort as ex:
msg = "%s: %s" % (ex.__class__.__name__, str(ex))
# rc = ex.status
except EnvironmentError as ex:
msg = "%s: %s" % (ex.__class__.__name__, str(ex))
# rc = os.EX_IOERR # 74 (see: /usr/include/sysexits.h )
except Exception as ex:
if 'GC3PIE_NO_CATCH_ERRORS' in os.environ:
# propagate generic exceptions for debugging purposes
raise
else:
# generic error exit
msg = "%s: %s" % (ex.__class__.__name__, str(ex))
# rc = 1
# output error message and -maybe- backtrace...
try:
self.log.critical(
msg,
exc_info=(
self.params.verbose > self.verbose_logging_threshold +
2))
except:
# no logging setup, output to stderr
sys.stderr.write("%s: FATAL ERROR: %s\n" % (self.name, msg))
# be careful here as `self.params` might not have been properly
# constructed yet
if ('verbose' in self.params and self.params.verbose >
self.verbose_logging_threshold + 2):
sys.excepthook(* sys.exc_info())
# ...and exit
return 1
##
# INTERNAL METHODS
##
# The following methods are for internal use; they can be
# overridden and customized in derived classes, although there
# should be no need to do so.
##
def _make_config(
self,
config_file_locations=gc3libs.Default.CONFIG_FILE_LOCATIONS,
**extra_args):
"""
Return a `gc3libs.config.Configuration`:class: instance configured
by parsing the configuration file(s) located at
`config_file_locations`. Order of configuration files
matters: files read last overwrite settings from
previously-read ones; list the most specific configuration
files last.
Any additional keyword arguments are passed unchanged to the
`gc3libs.config.Configuration`:class: constructor. In
particular, the `auto_enable_auth` parameter for the
`Configuration` constructor is `True` if not set differently
here as a keyword argument.
"""
# ensure a configuration file exists in the most specific location
for location in reversed(config_file_locations):
if (os.access(os.path.dirname(location),
os.W_OK | os.X_OK) and not
gc3libs.utils.deploy_configuration_file(
location, "gc3pie.conf.example")):
# warn user
self.log.warning(
"No configuration file '%s' was found;"
" a sample one has been copied in that location;"
" please edit it and define resources." % location)
# set defaults
extra_args.setdefault('auto_enable_auth', True)
try:
return gc3libs.config.Configuration(
*config_file_locations, **extra_args)
except:
self.log.error("Failed loading config file(s) from '%s'",
str.join("', '", config_file_locations))
raise
def _select_resources(self, *resource_names):
"""
Restrict resources to those listed in `resource_names`.
Argument `resource_names` is a string listing all names of
allowed resources (comma-separated), or a list of names of the
resources to keep active.
"""
patterns = []
for item in resource_names:
patterns.extend(name for name in item.split(','))
def keep_resource_if_matches(resource):
"""
Return `True` iff `resource`'s `name` attribute matches
one of the glob patterns in `patterns`.
"""
for pattern in patterns:
if fnmatch.fnmatch(resource.name, pattern):
return True
return False
kept = self._core.select_resource(keep_resource_if_matches)
if kept == 0:
raise gc3libs.exceptions.NoResources(
"No resources match the names '%s'"
% str.join(',', resource_names))
class GC3UtilsScript(_Script):
"""
Base class for GC3Utils scripts.
The default command line implemented is the following:
script [options] JOBID [JOBID ...]
By default, only the standard options ``-h``/``--help`` and
``-V``/``--version`` are considered; to add more, override
`setup_options`:meth:
To change default positional argument parsing, override
`setup_args`:meth:
"""
##
# CUSTOMIZATION METHODS
##
# The following are meant to be freely customized in derived scripts.
##
def setup_args(self):
"""
Set up command-line argument parsing.
The default command line parsing considers every argument as a
job ID; actual processing of the IDs is done in
`parse_args`:meth:
"""
self.add_param(
'args',
nargs='*',
metavar='JOBID',
help="Job ID string identifying the jobs to operate upon.")
def parse_args(self):
if hasattr(self.params, 'args') and '-' in self.params.args:
# Get input arguments *also* from standard input
self.params.args.remove('-')
self.params.args.extend(sys.stdin.read().split())
##
# pyCLI INTERFACE METHODS
##
# The following methods adapt the behavior of the
# `SessionBasedScript` class to the interface expected by pyCLI
# applications. Think twice before overriding them, and read
# the pyCLI docs before :-)
##
def __init__(self, **extra_args):
_Script.__init__(self, main=self.main, **extra_args)
def setup(self):
"""
Setup standard command-line parsing.
GC3Utils scripts should probably override `setup_args`:meth:
and `setup_options`:meth: to modify command-line parsing.
"""
# setup of base classes (creates the argparse stuff)
_Script.setup(self)
# local additions
self.add_param("-s",
"--session",
action="store",
required=True,
default=gc3libs.Default.JOBS_DIR,
help="Directory where job information will be stored.")
def pre_run(self):
"""
Perform parsing of standard command-line options and call into
`parse_args()` to do non-optional argument processing.
"""
# base class parses command-line
_Script.pre_run(self)
##
# INTERNAL METHODS
##
# The following methods are for internal use; they can be
# overridden and customized in derived classes, although there
# should be no need to do so.
##
def _get_jobs(self, job_ids, ignore_failures=True):
"""
Iterate over jobs (gc3libs.Application objects) corresponding
to the given Job IDs.
If `ignore_failures` is `True` (default), errors retrieving a
job from the persistence layer are ignored and the jobid is
skipped, therefore the returned list can be shorter than the
list of Job IDs given as argument. If `ignore_failures` is
`False`, then any errors result in the relevant exception being
re-raised.
"""
for jobid in job_ids:
try:
yield self.session.load(jobid)
except Exception as ex:
# Exempted from GC3Pie's `error_ignored()` policy as there
# is explicit control via the `ignore_failures` parameter
if ignore_failures:
gc3libs.log.error(
"Could not retrieve job '%s' (%s: %s). Ignoring.",
jobid, ex.__class__.__name__, ex,
exc_info=(self.params.verbose > 2))
continue
else:
raise
class _SessionBasedCommand(_Script):
"""
Base class for Session Based scripts (interactive or daemons)
"""
##
# CUSTOMIZATION METHODS
##
# The following are meant to be freely customized in derived scripts.
##
def make_directory_path(self, pathspec, jobname):
"""
Return a path to a directory, suitable for storing the output
of a job (named after `jobname`). It is not required that the
returned path points to an existing directory.
This is called by the default `process_args`:meth: using
`self.params.output` (i.e., the argument to the
``-o``/``--output`` option) as `pathspec`, and `jobname` and
`args` exactly as returned by `new_tasks`:meth:
The default implementation substitutes the following strings
within `pathspec`:
* ``SESSION`` is replaced with the name of the current session
(as specified by the ``-s``/``--session`` command-line option)
with a suffix ``.out`` appended;
* ``NAME`` is replaced with `jobname`;
* ``DATE`` is replaced with the current date, in *YYYY-MM-DD* format;
* ``TIME`` is replaced with the current time, in *HH:MM* format.
"""
return (pathspec
.replace('SESSION', self.params.session + '.out')
.replace('NAME', jobname)
.replace('DATE', time.strftime('%Y-%m-%d'))
.replace('TIME', time.strftime('%H:%M')))
def make_task_controller(self):
"""
Return a 'Controller' object to be used for progressing tasks
and getting statistics. In detail, a good 'Controller' object
has to implement `progress` and `stats` methods with the same
interface as `gc3libs.core.Engine`.
By the time this method is called (from `_main`:meth:), the
following instance attributes are already defined:
* `self._core`: a `gc3libs.core.Core` instance;
* `self.session`: the `gc3libs.session.Session` instance
that should be used to save/load jobs
In addition, any other attribute created during initialization
and command-line parsing is of course available.
"""
return gc3libs.core.Engine(
self._core,
self.session,
self.session.store,
max_submitted=self.params.max_running,
max_in_flight=self.params.max_running)
def add(self, task):
"""
Method to add a task to the session (and the controller)
"""
self.controller.add(task)
self.session.add(task)
def before_main_loop(self):
"""
Hook executed before entering the scripts' main loop.
This is the last chance to alter the script state as it will
be seen by the main loop.
Override in subclasses to plug any behavior here; the default
implementation does nothing.
"""
pass
def every_main_loop(self):
"""
Hook executed during each round of the main loop.
This is called from within the main loop.
Override in subclasses to plug any behavior here; the default
implementation does nothing.
FIXME: While on a SessionBasedScript this method is called
*after* processing all the jobs, on a SessionBasedDaemon it is
called *before*.
"""
pass
def after_main_loop(self):
"""
Hook executed after exit from the main loop.
This is called after the main loop has exited (for whatever
reason), but *before* the session is finally saved and other
connections are finalized.
Override in subclasses to plug any behavior here; the default
implementation does nothing.
"""
pass
##
# pyCLI INTERFACE METHODS
##
# The following methods adapt the behavior of the
# `SessionBasedScript` class to the interface expected by pyCLI
# applications. Think twice before overriding them, and read
# the pyCLI docs before :-)
##
# safeguard against programming errors: if the `application` ctor
# parameter has not been given to the constructor, the following
# method raises a fatal error (this function simulates a class ctor)
def __unset_application_cls(*args, **kwargs):
"""Raise an error if users did not set `application` in
`SessionBasedScript` initialization."""
raise gc3libs.exceptions.InvalidArgument(
"PLEASE SET `application` in `SessionBasedScript` CONSTRUCTOR")
def __init__(self, **extra_args):
"""
Perform initialization and set the version, help and usage
strings.
The help text to be printed when the script is invoked with the
``-h``/``--help`` option will be taken from (in order of preference):
* the keyword argument `description`
* the attribute `self.description`
If neither is provided, an `AssertionError` is raised.
The text to output when the the script is invoked with the
``-V``/``--version`` options is taken from (in order of
preference):
* the keyword argument `version`
* the attribute `self.version`
If none of these is provided, an `AssertionError` is raised.
The `usage` keyword argument (if provided) will be used to
provide the program help text; if not provided, one will be
generated based on the options and positional arguments
defined in the code.
Any additional keyword argument will be used to set a
corresponding instance attribute on this Python object.
"""
self.session = None
# by default, print stats of all kind of jobs
self.stats_only_for = None
self.instances_per_file = 1
self.instances_per_job = 1
self.extra = {} # extra extra_args arguments passed to `parse_args`
# use bogus values that should point ppl to the right place
self.input_filename_pattern = 'PLEASE SET `input_filename_pattern`'
'IN `SessionBasedScript` CONSTRUCTOR'
# catch omission of mandatory `application` ctor param (see above)
self.application = _SessionBasedCommand.__unset_application_cls
# init base classes
_Script.__init__(
self,
main=self._main,
**extra_args
)
def process_args(self):
"""
Process command-line positional arguments and set up the
session accordingly. In particular, new jobs should be added
to the session during the execution of this method: additions
are not contemplated elsewhere.
This method is called by the standard `_main`:meth: after
loading or creating a session into `self.session`. New jobs
should be appended to `self.session` and it is also permitted to
remove existing ones.
The default implementation calls `new_tasks`:meth: and adds to
the session all jobs whose name does not clash with the
jobname of an already existing task.
See also: `new_tasks`:meth:
"""
# default creation arguments
self.extra.setdefault('requested_cores', self.params.ncores)
self.extra.setdefault('requested_memory',
self.params.ncores * self.params.memory_per_core)
self.extra.setdefault('requested_walltime', self.params.walltime)
# XXX: assumes `make_directory_path` substitutes ``NAME`` with
# `jobname`; keep in sync!
self.extra.setdefault(
'output_dir',
self.make_directory_path(
self.params.output,
'NAME'))
# build job list
new_jobs = list(self.new_tasks(self.extra.copy()))
self._add_new_tasks(new_jobs)
def _add_new_tasks(self, new_jobs):
# pre-allocate Job IDs
if len(new_jobs) > 0:
# XXX: can't we just make `reserve` part of the `IdFactory`
# contract?
try:
self.session.store.idfactory.reserve(len(new_jobs))
except AttributeError:
# no `idfactory`, ignore
pass
# add new jobs to the session
existing_job_names = self.session.list_names()
warning_on_old_style_given = False
for n, item in enumerate(new_jobs):
if isinstance(item, tuple):
if not warning_on_old_style_given:
self.log.warning(
"Using old-style new tasks list; please update"
" the code!")
warning_on_old_style_given = True
# build Task for (jobname, classname, args, kwargs)
jobname, cls, args, kwargs = item
if jobname in existing_job_names:
continue
kwargs.setdefault('jobname', jobname)
kwargs.setdefault(
'output_dir',
self.make_directory_path(
self.params.output,
jobname))
kwargs.setdefault(
'requested_cores', self.extra['requested_cores'])
kwargs.setdefault(
'requested_memory', self.extra['requested_memory'])
kwargs.setdefault(
'requested_walltime', self.extra['requested_walltime'])
# create a new `Task` object
try:
task = cls(*args, **kwargs)
except Exception as ex:
self.log.error("Could not create job '%s': %s."
% (jobname, str(ex)), exc_info=__debug__)
continue
# XXX: should we raise an exception here?
# raise AssertionError(
# "Could not create job '%s': %s: %s"
# % (jobname, ex.__class__.__name__, str(ex)))