source: flex_extract.git/Source/Python/submit.py @ b8037ed

dev
Last change on this file since b8037ed was b8037ed, checked in by Anne Tipka <anne.tipka@…>, 18 months ago

if using oper without using eventid, basic job submit must be used

  • Property mode set to 100755
File size: 9.1 KB
Line 
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#*******************************************************************************
4# @Author: Anne Fouilloux (University of Oslo)
5#
6# @Date: October 2014
7#
8# @Change History:
9#
10#    November 2015 - Leopold Haimberger (University of Vienna):
11#        - job submission on ecgate and cca
12#        - job templates suitable for twice daily operational dissemination
13#
14#    February 2018 - Anne Philipp (University of Vienna):
15#        - applied PEP8 style guide
16#        - added documentation
17#        - minor changes in programming style (for consistence)
18#        - changed path names to variables from config file
19#        - added option for writing mars requests to extra file
20#          additionally, as option without submitting the mars jobs
21#        - splitted submit function to use genshi templates for the
22#          job script and avoid code duplication
23#    June 2020 - Anne Philipp
24#        - changed finale job_file to filename from config file
25#          instead of generating from the template filename
26#
27# @License:
28#    (C) Copyright 2014-2020.
29#    Anne Philipp, Leopold Haimberger
30#
31#    SPDX-License-Identifier: CC-BY-4.0
32#
33#    This work is licensed under the Creative Commons Attribution 4.0
34#    International License. To view a copy of this license, visit
35#    http://creativecommons.org/licenses/by/4.0/ or send a letter to
36#    Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
37#*******************************************************************************
38'''This script allows the user to extract meteorological fields from the ECMWF.
39
40It prepares the settings for retrieving the data from ECMWF servers and
41process the resulting files to prepare them for the use with FLEXPART or
42FLEXTRA.
43
44If it is supposed to work locally then it works through the necessary
45functions get_mars_data and prepare_flexpart. Otherwise it prepares
46a job script (korn shell) which will do the necessary work on the
47ECMWF server. This script will de submitted via the ecaccess command
48ecaccess-job-submit.
49
50This file can also be imported as a module which then contains the following
51functions:
52
53    * main - the main function of the script
54    * submit - calls mk_jobscript depending on operation mode and submits its
55    * mk_jobscript - creates the job script from a template
56
57Type: submit.py --help
58to get information about command line parameters.
59Read the documentation for usage instructions.
60'''
61
62# ------------------------------------------------------------------------------
63# MODULES
64# ------------------------------------------------------------------------------
65from __future__ import print_function
66
67import os
68import sys
69from datetime import datetime, timedelta
70
71# software specific classes and modules from flex_extract
72import _config
73from Mods.tools import (setup_controldata, normal_exit,
74                        submit_job_to_ecserver,
75                        submit_eventjob_to_ecserver)
76from Mods.get_mars_data import get_mars_data
77from Mods.prepare_flexpart import prepare_flexpart
78
79# ------------------------------------------------------------------------------
80# METHODS
81# ------------------------------------------------------------------------------
82
83def main():
84    '''Get the arguments from script call and from CONTROL file.
85    Decides from the argument "queue" if the local version
86    is done "queue=None" or the gateway version with "queue=ecgate"
87    or "queue=cca".
88
89    Parameters
90    ----------
91
92
93    Return
94    ------
95
96    '''
97
98    c, ppid, queue, job_template = setup_controldata()
99
100    # on local side
101    # starting from an ECMWF server this would also be the local side
102    called_from_dir = os.getcwd()
103    if queue is None:
104        if c.inputdir[0] != '/':
105            c.inputdir = os.path.join(called_from_dir, c.inputdir)
106        if c.outputdir[0] != '/':
107            c.outputdir = os.path.join(called_from_dir, c.outputdir)
108        get_mars_data(c)
109        if c.request == 0 or c.request == 2:
110            prepare_flexpart(ppid, c)
111            exit_message = 'FLEX_EXTRACT IS DONE!'
112        else:
113            exit_message = 'PRINTING MARS_REQUESTS DONE!'
114    # send files to ECMWF server
115    else:
116        submit(job_template, c, queue)
117        exit_message = 'FLEX_EXTRACT JOB SCRIPT IS SUBMITTED!'
118
119    normal_exit(exit_message)
120
121    return
122
123def submit(jtemplate, c, queue):
124    '''Prepares the job script and submits it to the specified queue.
125
126    Parameters
127    ----------
128    jtemplate : str
129        Job template file from sub-directory "_templates" for
130        submission to ECMWF. It contains all necessary
131        module and variable settings for the ECMWF environment as well as
132        the job call and mail report instructions.
133        Default is _config.TEMPFILE_JOB.
134
135    c : ControlFile
136        Contains all the parameters of CONTROL file and
137        command line.
138
139    queue : str
140        Name of queue for submission to ECMWF (e.g. ecgate or cca )
141
142    Return
143    ------
144
145    '''
146
147    if not c.oper:
148    # --------- create on demand job script ------------------------------------
149        if c.purefc:
150            print('---- Pure forecast mode! ----')
151        else:
152            print('---- On-demand mode! ----')
153
154        job_file = os.path.join(_config.PATH_JOBSCRIPTS,
155                                _config.FILE_JOB_OD)
156
157        # divide time periode into specified number of job chunks
158        # to have multiple job scripts
159        if c.job_chunk:
160            start = datetime.strptime(c.start_date, '%Y%m%d')
161            end = datetime.strptime(c.end_date, '%Y%m%d')
162            chunk = timedelta(days=c.job_chunk)
163            oneday = timedelta(days=1)
164
165            while start <= end:
166                if (start + chunk) <= end:
167                    c.end_date = (start + chunk - oneday).strftime("%Y%m%d")
168                else:
169                    c.end_date = end.strftime("%Y%m%d")
170
171                clist = c.to_list()
172                mk_jobscript(jtemplate, job_file, clist)
173
174                job_id = submit_job_to_ecserver(queue, job_file)
175                print('The job id is: ' + str(job_id.strip()))
176
177                start = start + chunk
178                c.start_date = start.strftime("%Y%m%d")
179        # submit a single job script
180        else:
181            clist = c.to_list()
182
183            mk_jobscript(jtemplate, job_file, clist)
184
185            job_id = submit_job_to_ecserver(queue, job_file)
186            print('The job id is: ' + str(job_id.strip()))
187
188    else:
189    # --------- create operational job script ----------------------------------
190        print('---- Operational mode! ----')
191
192        job_file = os.path.join(_config.PATH_JOBSCRIPTS,
193                                _config.FILE_JOB_OP)
194
195        c.start_date = '${MSJ_YEAR}${MSJ_MONTH}${MSJ_DAY}'
196        c.end_date = '${MSJ_YEAR}${MSJ_MONTH}${MSJ_DAY}'
197        c.basetime = '${MSJ_BASETIME}'
198        if c.maxstep > 24:
199            c.time = '${MSJ_BASETIME} {MSJ_BASETIME}'
200
201        clist = c.to_list()
202
203        mk_jobscript(jtemplate, job_file, clist)
204
205        if not c.eventid:
206            job_id = submit_job_to_ecserver(queue, job_file)
207        else:
208            job_id = submit_eventjob_to_ecserver(queue, job_file, c.eventid,
209                                                 c.eventjobname, c.ecuid)
210
211        print('The job id is: ' + str(job_id.strip()))
212
213    print('You should get an email per job with subject flex.hostname.pid')
214
215    return
216
217def mk_jobscript(jtemplate, job_file, clist):
218    '''Creates the job script from template.
219
220    Parameters
221    ----------
222    jtemplate : str
223        Job template file from sub-directory "Templates" for
224        submission to ECMWF. It contains all necessary
225        module and variable settings for the ECMWF environment as well as
226        the job call and mail report instructions.
227        Default is _config.TEMPFILE_JOB.
228
229    job_file : str
230        Path to the job script file.
231
232    clist : list of str
233        Contains all necessary parameters for ECMWF CONTROL file.
234
235    Return
236    ------
237
238    '''
239    from genshi.template.text import NewTextTemplate
240    from genshi.template import  TemplateLoader
241    from genshi.template.eval import UndefinedError
242
243    # load template and insert control content as list
244    try:
245        loader = TemplateLoader(_config.PATH_TEMPLATES, auto_reload=False)
246        control_template = loader.load(jtemplate,
247                                       cls=NewTextTemplate)
248
249        stream = control_template.generate(control_content=clist)
250    except UndefinedError as e:
251        print('... ERROR ' + str(e))
252
253        sys.exit('\n... error occured while trying to generate jobscript')
254    except OSError as e:
255        print('... ERROR CODE: ' + str(e.errno))
256        print('... ERROR MESSAGE:\n \t ' + str(e.strerror))
257
258        sys.exit('\n... error occured while trying to generate jobscript')
259
260    # create jobscript file
261    try:
262        with open(job_file, 'w') as f:
263            f.write(stream.render('text'))
264    except OSError as e:
265        print('... ERROR CODE: ' + str(e.errno))
266        print('... ERROR MESSAGE:\n \t ' + str(e.strerror))
267
268        sys.exit('\n... error occured while trying to write ' + job_file)
269
270    return
271
272
273if __name__ == "__main__":
274    main()
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG