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

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

accidentally wrote 'ls' into first line of file. removed

  • Property mode set to 100755
File size: 9.0 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
199        clist = c.to_list()
200
201        mk_jobscript(jtemplate, job_file, clist)
202
203        if not c.eventid:
204            job_id = submit_job_to_ecserver(queue, job_file)
205        else:
206            job_id = submit_eventjob_to_ecserver(queue, job_file, c.eventid,
207                                                 c.eventjobname, c.ecuid)
208
209        print('The job id is: ' + str(job_id.strip()))
210
211    print('You should get an email per job with subject flex.hostname.pid')
212
213    return
214
215def mk_jobscript(jtemplate, job_file, clist):
216    '''Creates the job script from template.
217
218    Parameters
219    ----------
220    jtemplate : str
221        Job template file from sub-directory "Templates" for
222        submission to ECMWF. It contains all necessary
223        module and variable settings for the ECMWF environment as well as
224        the job call and mail report instructions.
225        Default is _config.TEMPFILE_JOB.
226
227    job_file : str
228        Path to the job script file.
229
230    clist : list of str
231        Contains all necessary parameters for ECMWF CONTROL file.
232
233    Return
234    ------
235
236    '''
237    from genshi.template.text import NewTextTemplate
238    from genshi.template import  TemplateLoader
239    from genshi.template.eval import UndefinedError
240
241    # load template and insert control content as list
242    try:
243        loader = TemplateLoader(_config.PATH_TEMPLATES, auto_reload=False)
244        control_template = loader.load(jtemplate,
245                                       cls=NewTextTemplate)
246
247        stream = control_template.generate(control_content=clist)
248    except UndefinedError as e:
249        print('... ERROR ' + str(e))
250
251        sys.exit('\n... error occured while trying to generate jobscript')
252    except OSError as e:
253        print('... ERROR CODE: ' + str(e.errno))
254        print('... ERROR MESSAGE:\n \t ' + str(e.strerror))
255
256        sys.exit('\n... error occured while trying to generate jobscript')
257
258    # create jobscript file
259    try:
260        with open(job_file, 'w') as f:
261            f.write(stream.render('text'))
262    except OSError as e:
263        print('... ERROR CODE: ' + str(e.errno))
264        print('... ERROR MESSAGE:\n \t ' + str(e.strerror))
265
266        sys.exit('\n... error occured while trying to write ' + job_file)
267
268    return
269
270
271if __name__ == "__main__":
272    main()
Note: See TracBrowser for help on using the repository browser.
hosted by ZAMG