-
Notifications
You must be signed in to change notification settings - Fork 12
/
generate_schedule_xmlpage.py
179 lines (136 loc) · 6.36 KB
/
generate_schedule_xmlpage.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2016, 2018, 2019 Adam.Dybbroe
# Author(s):
# Adam.Dybbroe <[email protected]>
# 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/>.
"""From a schedule request xml file generate png's with swath coverage outline and an xml page for visualisation.
It uses posttroll to listen for incoming schedule request xml files and then triggers the png and xml output generation.
"""
import logging
import os.path
import sys
from datetime import datetime
import defusedxml.ElementTree as ET
import posttroll.subscriber
from posttroll.publisher import Publish
from six.moves.configparser import RawConfigParser
from six.moves.urllib.parse import urlparse
from trollsched import INSTRUMENT, SATELLITE_NAMES
from trollsched.drawing import save_fig
from trollsched.satpass import Pass
LOG = logging.getLogger(__name__)
CFG_DIR = os.environ.get("PYTROLL_SCHEDULE_CONFIG_DIR", "./")
CONF = RawConfigParser()
CFG_FILE = os.path.join(CFG_DIR, "pytroll_schedule_config.cfg")
LOG.debug("Config file = " + str(CFG_FILE))
if not os.path.exists(CFG_FILE):
raise IOError("Config file %s does not exist!" % CFG_FILE)
CONF.read(CFG_FILE)
OPTIONS = {}
for option, value in CONF.items("DEFAULT"):
OPTIONS[option] = value
#: Default time format
_DEFAULT_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
#: Default log format
_DEFAULT_LOG_FORMAT = "[%(levelname)s: %(asctime)s : %(name)s] %(message)s"
def process_xmlrequest(filename, plotdir, output_file, excluded_satellites):
"""Process the xml request."""
tree = ET.parse(filename)
root = tree.getroot()
for child in root:
if child.tag == "pass":
LOG.debug("Pass: %s", str(child.attrib))
platform_name = SATELLITE_NAMES.get(child.attrib["satellite"], child.attrib["satellite"])
instrument = INSTRUMENT.get(platform_name)
if not instrument:
LOG.error("Instrument unknown! Platform = %s", platform_name)
continue
if platform_name in excluded_satellites:
LOG.debug("Platform name excluded: %s", platform_name)
continue
try:
overpass = Pass(platform_name,
datetime.strptime(child.attrib["start-time"],
"%Y-%m-%d-%H:%M:%S"),
datetime.strptime(child.attrib["end-time"],
"%Y-%m-%d-%H:%M:%S"),
instrument=instrument)
except KeyError as err:
LOG.warning("Failed on satellite %s: %s", platform_name, str(err))
continue
save_fig(overpass, directory=plotdir)
child.set("img", overpass.fig)
child.set("rec", "True")
LOG.debug("Plot saved - plotdir = %s, platform_name = %s", plotdir, platform_name)
tree.write(output_file, encoding="utf-8", xml_declaration=True)
with open(output_file) as fpt:
lines = fpt.readlines()
lines.insert(
1, "<?xml-stylesheet type='text/xsl' href='reqreader.xsl'?>")
with open(output_file, "w") as fpt:
fpt.writelines(lines)
def start_plotting(jobreg, message, **kwargs):
"""Make a web-publishable version of the xml schedule.
Read the xmlschedule request file and make the png images of swath outlines
and generate the output xml file for web publication.
"""
excluded_satellites = kwargs.get("excluded_satellites", [])
LOG.info("")
LOG.info("job-registry dict: " + str(jobreg))
LOG.info("\tMessage:")
LOG.info(message)
urlobj = urlparse(message.data["uri"])
# path, fname = os.path.split(urlobj.path)
process_xmlrequest(urlobj.path,
OPTIONS["path_plots"], OPTIONS["xmlfilepath"],
excluded_satellites)
return jobreg
def schedule_page_generator(excluded_satellite_list=None):
"""Listens and triggers processing."""
LOG.info(
"*** Start the generation of the schedule xml page with swath outline plots")
with posttroll.subscriber.Subscribe("", [OPTIONS["posttroll_topic"], ],
True) as subscr:
with Publish("schedule_page_generator", 0) as publisher:
job_registry = {}
for msg in subscr.recv():
job_registry = start_plotting(
job_registry, msg, publisher=publisher, excluded_satellites=excluded_satellite_list)
# Cleanup in registry (keep only the last 5):
keys = job_registry.keys()
if len(keys) > 5:
keys.sort()
job_registry.pop(keys[0])
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-x", "--excluded_satellites", nargs="*",
help="List of platform names to exclude",
default=[])
opts = parser.parse_args()
no_sats = opts.excluded_satellites
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(fmt=_DEFAULT_LOG_FORMAT,
datefmt=_DEFAULT_TIME_FORMAT)
handler.setFormatter(formatter)
logging.getLogger("").addHandler(handler)
logging.getLogger("").setLevel(logging.DEBUG)
logging.getLogger("posttroll").setLevel(logging.INFO)
LOG = logging.getLogger("schedule_page_generator")
LOG.info("Exclude the following satellite platforms: %s", str(no_sats))
schedule_page_generator(no_sats)
# uri = "/data/temp/AdamD/xxx/2018-10-22-00-42-28-acquisition-schedule-confirmation-nrk.xml"
# urlobj = urlparse(uri)
# process_xmlrequest(urlobj.path,
# OPTIONS['path_plots'], OPTIONS['xmlfilepath'], no_sats)