-
Notifications
You must be signed in to change notification settings - Fork 23
/
__init__.py
executable file
·2147 lines (1792 loc) · 82.4 KB
/
__init__.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
#
# Copyright (C) 2009-2016 S3IT, Zentrale Informatik, University of Zurich. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2 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 Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
"""
GC3Libs is a python package for controlling the life-cycle of a Grid
or batch computational job.
GC3Libs provides services for submitting computational jobs to Grids
and batch systems, controlling their execution, persisting job
information, and retrieving the final output.
GC3Libs takes an application-oriented approach to batch computing. A
generic :class:`Application` class provides the basic operations for
controlling remote computations, but different :class:`Application`
subclasses can expose adapted interfaces, focusing on the most
relevant aspects of the application being represented.
"""
__docformat__ = 'reStructuredText'
__version__ = 'development version (SVN $Revision$)'
import inspect
import os
import os.path
import string
import sys
import time
import types
import subprocess
import shlex
import uuid
import logging
import logging.config
log = logging.getLogger("gc3.gc3libs")
log.propagate = True
from gc3libs.quantity import MB, hours, minutes, seconds, MiB
from gc3libs.compat._collections import OrderedDict
# this needs to be defined before we import other GC3Libs modules, as
# they may depend on it
class Default(object):
"""
A namespace for all constants and default values used in the
GC3Libs package.
"""
RCDIR = os.path.join(os.path.expandvars('$HOME'), ".gc3")
CONFIG_FILE_LOCATIONS = [
# system-wide config file
"/etc/gc3/gc3pie.conf",
# virtualenv config file
os.path.expandvars("$VIRTUAL_ENV/etc/gc3/gc3pie.conf"),
# user-private config file: first look into `$GC3PIE_CONF`, and
# fall-back to `~/.gc3/gc3pie.conf`
os.environ.get('GC3PIE_CONF', os.path.join(RCDIR, "gc3pie.conf"))
]
JOBS_DIR = os.path.join(RCDIR, "jobs")
# the ARC backends have been removed, but keep their names around
# so we can issue a warning if a user still has these resources in
# the configuration file
ARC0_LRMS = 'arc0'
ARC1_LRMS = 'arc1'
SGE_LRMS = 'sge'
PBS_LRMS = 'pbs'
LSF_LRMS = 'lsf'
SHELLCMD_LRMS = 'shellcmd'
SLURM_LRMS = 'slurm'
SUBPROCESS_LRMS = 'subprocess'
EC2_LRMS = 'ec2'
OPENSTACK_LRMS = 'openstack'
# Transport information
SSH_CONFIG_FILE = '~/.ssh/config'
SSH_PORT = 22
SSH_CONNECT_TIMEOUT = 30
# Proxy
# : Proxy validity threshold in seconds. If proxy is expiring
# before the thresold, it will be marked as to be renewed.
PROXY_VALIDITY_THRESHOLD = 600
PEEK_FILE_SIZE = 120 # expressed in bytes
# Openstack default VM Operating System overhead
VM_OS_OVERHEAD = 512 * MiB
# time to cache lshosts/bjobs information for
LSF_CACHE_TIME = 30
import gc3libs.exceptions
from gc3libs.persistence import Persistable
from gc3libs.url import UrlKeyDict, UrlValueDict
from gc3libs.utils import (defproperty, deploy_configuration_file, Enum,
History, Struct, safe_repr, sh_quote_unsafe)
# when used in the `output` attribute of an application,
# it stands for "fetch the whole contents of the remote
# directory"
ANY_OUTPUT = '*'
# utility functions
#
def configure_logger(
level=logging.ERROR,
name=None,
format=(os.path.basename(sys.argv[0])
+ ': [%(asctime)s] %(levelname)-8s: %(message)s'),
datefmt='%Y-%m-%d %H:%M:%S',
colorize='auto'):
"""
Configure the ``gc3.gc3libs`` logger.
Arguments `level`, `format` and `datefmt` set the corresponding
arguments in the `logging.basicConfig()` call.
Argument `colorize` controls the use of the `coloredlogs`_ module to
color-code log output lines. The default value ``auto`` enables log
colorization iff the `sys.stderr` stream is connected to a terminal;
a ``True`` value will enable it regardless of the log output stream
terminal status, and any ``False`` value will disable log
colorization altogether. Note that log colorization can anyway be
disabled if `coloredlogs`_ thinks that the terminal is not capable
of colored output; see `coloredlogs.terminal_supports_colors`__.
If the `coloredlogs`_ module cannot be imported, a warning is logged
and log colorization is disabled.
.. _coloredlogs: https://coloredlogs.readthedocs.org/en/latest/#
.. __: http://humanfriendly.readthedocs.org/en/latest/index.html#humanfriendly.terminal.terminal_supports_colors
If a user configuration file exists in file NAME.log.conf in the
``Default.RCDIR`` directory (usually ``~/.gc3``), it is read and
used for more advanced configuration; if it does not exist, then a
sample one is created.
"""
if name is None:
name = os.path.basename(sys.argv[0])
log_conf = os.path.join(Default.RCDIR, name + '.log.conf')
logging.basicConfig(level=level, format=format, datefmt=datefmt)
deploy_configuration_file(log_conf, "logging.conf.example")
logging.config.fileConfig(log_conf, {
'RCDIR': Default.RCDIR,
'HOMEDIR': os.path.expandvars('$HOME'),
})
log = logging.getLogger("gc3.gc3libs")
log.setLevel(level)
log.propagate = 1
if colorize == 'auto':
# set if STDERR is connected to a terminal
colorize = sys.stderr.isatty()
if colorize:
try:
import coloredlogs
coloredlogs.install(
logger=log, reconfigure=True, stream=sys.stderr,
level=level, fmt=format, datefmt=datefmt, programname=name)
except ImportError as err:
log.warning("Could not import `coloredlogs` module: %s", err)
UNIGNORE_ERRORS = set(os.environ.get('GC3PIE_NO_CATCH_ERRORS', '').split(','))
if 'ALL' in UNIGNORE_ERRORS:
UNIGNORE_ALL_ERRORS = True
else:
UNIGNORE_ALL_ERRORS = False
def error_ignored(*ctx):
"""
Return ``True`` if no object in list `ctx` matches the contents of the
``GC3PIE_NO_CATCH_ERRORS`` environment variable.
Note that the list of un-ignored errors is determined when the `gc3libs`
module is initially loaded and is thus insensitive to changes in the
environment that happen afterwards.
The calling interface is so designed, that a list of keywords
describing -or related- to the error are passed; if any of them
has been mentioned in the environment variable
``GC3PIE_NO_CATCH_ERRORS`` then this function returns ``False`` --
i.e., the error is never ignored by GC3Pie and always propagated
to the top-level handler.
"""
if UNIGNORE_ALL_ERRORS:
return False
else:
return (0 == len(UNIGNORE_ERRORS.intersection(set(str(word).lower()
for word in ctx))))
# Task and Application classes
#
class Task(Persistable, Struct):
"""
Mix-in class implementing a facade for job control.
A `Task` can be described as an "active" job, in the sense that
all job control is done through methods on the `Task` instance
itself; contrast this with operating on `Application` objects
through a `Core` or `Engine` instance.
The following pseudo-code is an example of the usage of the `Task`
interface for controlling a job. Assume that `GamessApplication` is
inheriting from `Task` (it actually is)::
t = GamessApplication(input_file)
t.submit()
# ... do other stuff
t.update_state()
# ... take decisions based on t.execution.state
t.wait() # blocks until task is terminated
Each `Task` object has an `execution` attribute: it is an instance
of class :class:`Run`, initialized with a new instance of `Run`,
and at any given time it reflects the current status of the
associated remote job. In particular, `execution.state` can be
checked for the current task status.
After successful initialization, a `Task` instance will have the
following attributes:
`changed`
evaluates to `True` if the `Task` has been changed since last
time it has been saved to persistent storage (see
:mod:`gclibs.persistence`)
`execution`
a `Run` instance; its state attribute is initially set to ``NEW``.
"""
# assume that a generic `Task` produces no output -- this should
# be changed in subclasses!
would_output = False
def __init__(self, **extra_args):
"""
Initialize a `Task` instance.
The following attributes are defined on a valid `Task` instance:
* `execution`: a `gc3libs.Run`:class: instance
:param grid: A :class:`gc3libs.Engine` or
:class:`gc3libs.Core` instance, or anything
implementing the same interface.
"""
Persistable.__init__(self, **extra_args)
Struct.__init__(self, **extra_args)
self.execution = Run(attach=self)
# `_controller` and `_attached` are set by `attach()`/`detach()`
self._attached = False
self._controller = None
self.changed = True
# manipulate the "controller" interface used to control the associated job
def attach(self, controller):
"""
Use the given Grid interface for operations on the job
associated with this task.
"""
if self._controller != controller:
if self._attached:
self.detach()
# gc3libs.log.debug("Attaching %s to %s" % (self, controller))
controller.add(self)
self._attached = True
self._controller = controller
# create a class-shared fake "controller" object, that just throws a
# DetachedFromController exception when any of its methods is used. We
# use this as a safeguard for detached `Task` objects, in order to
# get sensible error reporting.
class __NoController(object):
# XXX: this returns a function object for whatever `name`;
# should be fine since a "controller" interface should just contain
# methods, but one never knows...
def __getattr__(self, name):
def throw_error(*args, **kwargs):
raise gc3libs.exceptions.DetachedFromControllerError(
"Task object is not attached to a controller.")
return throw_error
__no_controller = __NoController()
def detach(self):
"""
Remove any reference to the current grid interface. After
this, calling any method other than :meth:`attach` results in
an exception :class:`TaskDetachedFromGridError` being thrown.
"""
if self._attached:
self._attached = False
try:
self._controller.remove(self)
except:
pass
self._controller = Task.__no_controller
# interface with pickle/gc3libs.persistence: do not save the
# attached grid/engine/core as well: it definitely needs to be
# saved separately.
def __getstate__(self):
state = self.__dict__.copy()
state['_controller'] = None
state['_attached'] = None
state['changed'] = False
return state
def __setstate__(self, state):
self.__dict__ = state
self.detach()
# grid-level actions on this Task object are re-routed to the
# grid/engine/core instance
def submit(self, resubmit=False, targets=None, **extra_args):
"""
Start the computational job associated with this `Task` instance.
"""
assert self._attached, ("Task.submit() called on detached task %s." %
self)
assert hasattr(self._controller, 'submit'), \
("Invalid `_controller` object '%s' in Task %s" %
(self._controller, self))
self._controller.submit(self, resubmit, targets, **extra_args)
def update_state(self, **extra_args):
"""
In-place update of the execution state of the computational
job associated with this `Task`. After successful completion,
`.execution.state` will contain the new state.
After the job has reached the `TERMINATING` state, the following
attributes are also set:
`execution.duration`
Time lapse from start to end of the job at the remote
execution site, as a `gc3libs.quantity.Duration`:class: value.
(This is also often referred to as the 'wall-clock time' or
`walltime`:term: of the job.)
`execution.max_used_memory`
Maximum amount of RAM used during job execution, represented
as a `gc3libs.quantity.Memory`:class: value.
`execution.used_cpu_time`
Total time (as a `gc3libs.quantity.Duration`:class: value) that the
processors has been actively executing the job's code.
The execution backend may set additional attributes; the exact
name and format of these additional attributes is
backend-specific. However, you can easily identify the
backend-specific attributes because their name is prefixed
with the (lowercased) backend name; for instance, the
`PbsLrms`:class: backend sets attributes `pbs_queue`,
`pbs_end_time`, etc.
"""
assert self._attached, (
"Task.update_state() called on detached task %s." % self)
assert hasattr(self._controller, 'update_job_state'), \
("Invalid `_controller` object '%s' in Task %s" %
(self._controller, self))
self._controller.update_job_state(self, **extra_args)
def kill(self, **extra_args):
"""
Terminate the computational job associated with this task.
See :meth:`gc3libs.Core.kill` for a full explanation.
"""
assert self._attached, ("Task.kill() called on detached task %s." %
self)
assert hasattr(self._controller, 'kill'), \
("Invalid `_controller` object '%s' in Task %s" %
(self._controller, self))
self._controller.kill(self, **extra_args)
def fetch_output(self, output_dir=None,
overwrite=False, changed_only=True, **extra_args):
"""
Retrieve the outputs of the computational job associated with
this task into directory `output_dir`, or, if that is `None`,
into the directory whose path is stored in instance attribute
`.output_dir`.
If the execution state is `TERMINATING`, transition the state to
`TERMINATED` (which runs the appropriate hook).
See :meth:`gc3libs.Core.fetch_output` for a full explanation.
:return: Path to the directory where the job output has been
collected.
"""
if self.execution.state == Run.State.TERMINATED:
return self.output_dir
if self.execution.state == Run.State.TERMINATING:
# advance state to TERMINATED
self.output_dir = self._get_download_dir(output_dir)
if self.output_dir:
self.execution.info = (
"Final output downloaded to '%s'" % self.output_dir)
self.execution.state = Run.State.TERMINATED
self.changed = True
return self.output_dir
else:
download_dir = self._get_download_dir(output_dir)
self.execution.info = (
"Output snapshot downloaded to '%s'" % download_dir)
return download_dir
def _get_download_dir(self, download_dir):
"""
Return a directory path where to download this Task's output files,
or ``None`` if this Task is not expected to produce any output.
For output-producing tasks, if the given `download_dir` is not
None, return that. Otherwise, return the directory saved on
this object in attribute `output_dir`. If all else fails,
raise an `InvalidArgument` exception.
"""
# XXX: the try/except block below is there for compatibility
# with saved jobs -- should be removed after release 2.3
try:
if not self.would_output:
return None
except AttributeError:
pass
# determine download dir
if download_dir is not None:
return download_dir
else:
try:
return self.output_dir
except AttributeError:
raise gc3libs.exceptions.InvalidArgument(
"`Task._get_download_dir()` called with no explicit"
" download directory, but object '%s' (%s) has no `output_dir`"
" attribute set either."
% (self, type(self)))
def peek(self, what='stdout', offset=0, size=None, **extra_args):
"""
Download `size` bytes (at offset `offset` from the start) from
the associated job standard output or error stream, and write them
into a local file. Return a file-like object from which the
downloaded contents can be read.
See :meth:`gc3libs.Core.peek` for a full explanation.
"""
assert self._attached, ("Task.peek() called on detached task %s." %
self)
assert hasattr(self._controller, 'peek'), \
("Invalid `_controller` object '%s' in Task %s" %
(self._controller, self))
return self._controller.peek(self, what, offset, size, **extra_args)
def free(self, **extra_args):
"""
Release any remote resources associated with this task.
See :meth:`gc3libs.Core.free` for a full explanation.
"""
return
# convenience methods, do not really add any functionality over
# what's above
def progress(self):
"""
Advance the associated job through all states of a regular
lifecycle. In detail:
1. If `execution.state` is `NEW`, the associated job is started.
2. The state is updated until it reaches `TERMINATED`
3. Output is collected and the final returncode is returned.
An exception `TaskError` is raised if the job hits state
`STOPPED` or `UNKNOWN` during an update in phase 2.
When the job reaches `TERMINATING` state, the output is
retrieved; if this operation is successfull, state is advanced
to `TERMINATED`.
Once the job reaches `TERMINATED` state, the return code
(stored also in `.returncode`) is returned; if the job is not
yet in `TERMINATED` state, calling `progress` returns `None`.
:raises: exception :class:`UnexpectedStateError` if the
associated job goes into state `STOPPED` or `UNKNOWN`
:return: final returncode, or `None` if the execution
state is not `TERMINATED`.
"""
# first update state, we'll submit NEW jobs last, so that the
# state is not updated immediately after submission as ARC
# does not cope well with this...
if self.execution.state in [Run.State.SUBMITTED,
Run.State.RUNNING,
Run.State.STOPPED,
Run.State.UNKNOWN]:
self.update_state()
# now "do the right thing" based on actual state
if self.execution.state in [Run.State.STOPPED,
Run.State.UNKNOWN]:
raise gc3libs.exceptions.UnexpectedStateError(
"Task '%s' entered `%s` state." % (self, self.execution.state))
elif self.execution.state == Run.State.NEW:
self.submit()
elif self.execution.state == Run.State.TERMINATING:
self.fetch_output()
return self.execution.returncode
def redo(self, *args, **kwargs):
"""
Reset the state of this Task instance to ``NEW``.
This is only allowed for tasks which are already in a terminal
state, or one of ``STOPPED``, ``UNKNOWN``, or ``NEW`;
otherwise an `AssertionError` is raised.
The task should then be resubmitted to actually resume
execution.
See also `SequentialTaskCollection.redo`:meth:.
:raises AssertionError: if this Task's state is not terminal.
"""
assert self.execution.state in [
Run.State.NEW, # allow re-doing partially run TaskCollections
Run.State.STOPPED,
Run.State.TERMINATED,
Run.State.TERMINATING,
Run.State.UNKNOWN,
], ("Can only re-do a Task which is in a terminal state;"
" task {0} is in state {1} instead."
.format(self, self.execution.state))
self.execution.state = Run.State.NEW
def wait(self, interval=60):
"""
Block until the associated job has reached `TERMINATED` state,
then return the job's return code. Note that this does not
automatically fetch the output.
:param integer interval: Poll job state every this number of seconds
"""
# FIXME: I'm not sure how to deal with this... Ideally, this
# call should suspend the current thread and wait for
# notifications from the Engine, but:
# - there's no way to tell if we are running threaded,
# - `self._controller` could be a `Core` instance, thus not capable
# of running independently.
# For now this is a poll+sleep loop, but we certainly need to revise
# it.
while True:
self.update_state()
if self.execution.state == Run.State.TERMINATED:
return self.returncode
time.sleep(interval)
# State transition handlers.
#
def new(self):
"""
Called when the job state is (re)set to `NEW`.
Note this will not be called when the application object is
created, rather if the state is reset to `NEW` after it has
already been submitted.
The default implementation does nothing, override in derived
classes to implement additional behavior.
"""
pass
def submitted(self):
"""
Called when the job state transitions to `SUBMITTED`, i.e.,
the job has been successfully sent to a (possibly) remote
execution resource and is now waiting to be scheduled.
The default implementation does nothing, override in derived
classes to implement additional behavior.
"""
pass
def running(self):
"""
Called when the job state transitions to `RUNNING`, i.e., the
job has been successfully started on a (possibly) remote
resource.
The default implementation does nothing, override in derived
classes to implement additional behavior.
"""
pass
def stopped(self):
"""
Called when the job state transitions to `STOPPED`, i.e., the
job has been remotely suspended for an unknown reason and
cannot automatically resume execution.
The default implementation does nothing, override in derived
classes to implement additional behavior.
"""
pass
def terminating(self):
"""
Called when the job state transitions to `TERMINATING`, i.e.,
the remote job has finished execution (with whatever exit
status, see `returncode`) but output has not yet been
retrieved.
The default implementation does nothing, override in derived
classes to implement additional behavior.
"""
pass
def terminated(self):
"""
Called when the job state transitions to `TERMINATED`, i.e.,
the job has finished execution (with whatever exit status, see
`returncode`) and the final output has been retrieved.
The location where the final output has been stored is
available in attribute `self.output_dir`.
The default implementation does nothing, override in derived
classes to implement additional behavior.
"""
pass
def unknown(self):
"""
Called when the job state transitions to `UNKNOWN`, i.e.,
the job has not been updated for a certain period of time
thus it is placed in UNKNOWN state.
Two possible ways of changing from this state:
1) next update cycle, job status is updated from the remote
server
2) derive this method for Application specific logic to deal
with this case
The default implementation does nothing, override in derived
classes to implement additional behavior.
"""
pass
class Application(Task):
"""
Support for running a generic application with the GC3Libs.
The following parameters are *required* to create an `Application`
instance:
`arguments`
List or sequence of program arguments. The program to execute is
the first one.; any object in the list will be converted to
string via Python's `str()`.
`inputs`
Files that will be copied to the remote execution node before
execution starts.
There are two possible ways of specifying the `inputs` parameter:
* It can be a Python dictionary: keys are local file paths or
URLs, values are remote file names.
* It can be a Python list: each item in the list should be a pair
`(source, remote_file_name)`: the `source` can be a local file
or a URL; `remote_file_name` is the path (relative to the
execution directory) where `source` will be downloaded. If
`remote_file_name` is an absolute path, an
:class:`InvalidArgument` error is raised.
A single string `file_name` is allowed instead of the pair
and results in the local file `file_name` being copied to
`file_name` on the remote host.
`outputs`
Files and directories that will be copied from the remote
execution node back to the local computer (or a
network-accessible server) after execution has completed.
Directories are copied recursively.
There are three possible ways of specifying the `outputs` parameter:
* It can be a Python dictionary: keys are remote file or directory
paths (relative to the execution directory), values are
corresponding local names.
* It can be a Python list: each item in the list should be a pair
`(remote_file_name, destination)`: the `destination` can be a
local file or a URL; `remote_file_name` is the path (relative to
the execution directory) that will be uploaded to `destination`.
If `remote_file_name` is an absolute path, an
:class:`InvalidArgument` error is raised.
A single string `file_name` is allowed instead of the pair
and results in the remote file `file_name` being copied to
`file_name` on the local host.
* The constant `gc3libs.ANY_OUTPUT` which instructs GC3Libs to
copy every file in the remote execution directory back to the
local output path (as specified by the `output_dir` attribute).
Note that no errors will be raised if an output file is not present.
Override the `terminated`:meth: method to raise errors for reacting
on this kind of failures.
`output_dir`
Path to the base directory where output files will be downloaded.
Output file names are interpreted relative to this base directory.
`requested_cores`,`requested_memory`,`requested_walltime`
Specify resource requirements for the application:
* the number of independent execution units (CPU cores; all are
required to be in the same execution node);
* amount of memory (as a `gc3libs.quantity.Memory`:class: object)
for the task as a whole, i.e., independent of number of CPUs
allocated;
* amount of wall-clock time to allocate for the computational job
(as a `gc3libs.quantity.Duration`:class: object).
The following optional parameters may be additionally
specified as keyword arguments and will be given special
treatment by the `Application` class logic:
`requested_architecture`
specify that this application can only be executed on a certain
processor architecture; see `Run.Arch`:class: for a list of
possible values. The default value `None` means that any
architecture is valid, i.e., there are no requirements on the
processor architecture.
`environment`
a dictionary defining environment variables and the values to
give them in the task execution setting. Keys of the dictionary
are environmental variables names, and dictionary values define
the corresponding variable content. Both keys and values must
be strings or convertible to string.
For example, to run the application in an environment where the
variable ``LC_ALL`` has the value ``C`` and the variable ``HZ``
has the value ``100``, one would use::
Application(...,
environment={'LC_ALL':'C', 'HZ':100},
...)
`output_base_url`
if not `None`, this is prefixed to all output files (except
stdout and stderr, which are always retrieved), so, for
instance, having `output_base_url="gsiftp://example.org/data"`
will upload output files into that remote directory.
`stdin`
file name of a file whose contents will be fed as
standard input stream to the remote-executing process.
`stdout`
name of a file where the standard output stream of
the remote executing process will be redirected to; will be
automatically added to `outputs`.
`stderr`
name of a file where the standard error stream of
the remote executing process will be redirected to; will be
automatically added to `outputs`.
`join`
if this evaluates to `True`, then standard error is
redirected to the file specified by `stdout` and `stderr` is
ignored. (`join` has no effect if `stdout` is not given.)
`tags`
list of tag names (string) that must be present on a
resource in order to be eligible for submission.
Any other keyword arguments will be set as instance attributes,
but otherwise ignored by the `Application` constructor.
After successful construction, an `Application` object is
guaranteed to have the following instance attributes:
`arguments`
list of strings specifying command-line arguments for executable
invocation. The first element must be the executable.
`inputs`
dictionary mapping source URL (a `gc3libs.url.Url`:class:
object) to a remote file name (a string); remote file names are
relative paths (root directory is the remote job folder)
`outputs`
dictionary mapping remote file name (a string) to a destination
(a `gc3libs.url.Url`:class:); remote file names are relative
paths (root directory is the remote job folder)
`output_dir`
Path to the base directory where output files will be
downloaded. Output file names (those which are not URLs) are
interpreted relative to this base directory.
`execution`
a `Run` instance; its state attribute is initially set to ``NEW``
(Actually inherited from the `Task`:class:)
`environment`
dictionary mapping environment variable names to the requested
value (string); possibly empty
`stdin`
``None`` or a string specifying a (local) file name. If `stdin`
is not None, then it matches a key name in `inputs`
`stdout`
``None`` or a string specifying a (remote) file name. If `stdout`
is not None, then it matches a key name in `outputs`
`stderr`
``None`` or a string specifying a (remote) file name. If `stdout`
is not None, then it matches a key name in `outputs`
`join`
boolean value, indicating whether `stdout` and `stderr` are
collected into the same file
`tags`
list of strings specifying the tags to request in each resource
for submission; possibly empty.
"""
application_name = 'generic'
"""
A name for applications of this class.
This string is used as a prefix for configuration items related to
this application in configured resources. For example, if the
`application_name` is ``foo``, then the application interface code
in GC3Pie might search for ``foo_cmd``, ``foo_extra_args``, etc.
See `qsub_sge`:meth: for an actual example.
"""
def __init__(self, arguments, inputs, outputs, output_dir, **extra_args):
# required parameters
if isinstance(arguments, types.StringTypes):
arguments = shlex.split(arguments)
if 'executable' in extra_args:
gc3libs.log.warning(
"The `executable` argument is not supported anymore in"
" GC3Pie 2.0. Please adapt your code and use `arguments`"
" only.")
arguments = [extra_args['executable']] + list(arguments)
self.arguments = [str(x) for x in arguments]
self.inputs = Application._io_spec_to_dict(UrlKeyDict, inputs, True)
self.outputs = Application._io_spec_to_dict(
UrlValueDict, outputs, False)
# check that remote entries are all distinct
# (can happen that two local paths are mapped to the same remote one)
if len(self.inputs.values()) != len(set(self.inputs.values())):
# try to build an exact error message
inv = {}
for l, r in self.inputs.iteritems():
if r in inv:
raise gc3libs.exceptions.DuplicateEntryError(
"Local inputs '%s' and '%s'"
" map to the same remote path '%s'" %
(l, inv[r], r))
else:
inv[r] = l
# ensure remote paths are not absolute
for r_path in self.inputs.itervalues():
if os.path.isabs(r_path):
raise gc3libs.exceptions.InvalidArgument(
"Remote paths not allowed to be absolute: %s" % r_path)
# check that local entries are all distinct
# (can happen that two remote paths are mapped to the same local one)
if len(self.outputs.values()) != len(set(self.outputs.values())):
# try to build an exact error message
inv = {}
for r, l in self.outputs.iteritems():
if l in inv:
raise gc3libs.exceptions.DuplicateEntryError(
"Remote outputs '%s' and '%s'"
" map to the same local path '%s'" %
(r, inv[l], l))
else:
inv[l] = r
# ensure remote paths are not absolute
for r_path in self.outputs.iterkeys():
if os.path.isabs(r_path):
raise gc3libs.exceptions.InvalidArgument(
"Remote paths not allowed to be absolute")
self.output_dir = output_dir
# optional params
self.output_base_url = extra_args.pop('output_base_url', None)
self.requested_cores = int(extra_args.pop('requested_cores', 1))
self.requested_memory = extra_args.pop('requested_memory', None)
assert (self.requested_memory is None
or isinstance(self.requested_memory,
gc3libs.quantity.Memory)), \
("Expected `Memory` instance for `requested_memory,"
" got %r %s instead."
% (self.requested_memory, type(self.requested_memory)))
self.requested_walltime = extra_args.pop('requested_walltime', None)
assert (self.requested_walltime is None
or isinstance(self.requested_walltime,
gc3libs.quantity.Duration)), \
("Expected `Duration` instance for `requested_walltime,"
" got %r %s instead."
% (self.requested_walltime, type(self.requested_walltime)))
self.requested_architecture = extra_args.pop(
'requested_architecture', None)
if self.requested_architecture is not None \
and self.requested_architecture not in [
Run.Arch.X86_32,
Run.Arch.X86_64]:
raise gc3libs.exceptions.InvalidArgument(
"Architecture must be either '%s' or '%s'"
% (Run.Arch.X86_32, Run.Arch.X86_64))
self.environment = dict(
(str(k), str(v)) for k, v in extra_args.pop(
'environment', dict()).items())
self.join = extra_args.pop('join', False)
self.stdin = extra_args.pop('stdin', None)
if self.stdin and (self.stdin not in self.inputs):
self.inputs[self.stdin] = os.path.basename(self.stdin)
self.stdout = extra_args.pop('stdout', None)
if self.stdout is not None and os.path.isabs(self.stdout):
raise gc3libs.exceptions.InvalidArgument(
"Absolute path '%s' passed as `Application.stdout`"
% self.stdout)
if ((self.stdout is not None)
and (gc3libs.ANY_OUTPUT not in self.outputs)
and (self.stdout not in self.outputs)):
self.outputs[self.stdout] = self.stdout
self.stderr = extra_args.pop('stderr', None)
join_stdout_and_stderr = (self.join
or self.stderr == self.stdout
or self.stderr == subprocess.STDOUT)
if join_stdout_and_stderr:
self.join = True