forked from ARPA-SIMC/arkimaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arkimaps
executable file
·567 lines (450 loc) · 16.8 KB
/
arkimaps
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
#!/usr/bin/python3
# from __future__ import annotations
import argparse
import contextlib
import datetime
import json
import logging
import os
import subprocess
import sys
import time
from collections import defaultdict
from typing import Generator, List, Optional, Type
from arkimapslib import outputbundle
from arkimapslib.cmdline import Command, Fail, Success
# if TYPE_CHECKING:
from arkimapslib.flavours import Flavour
from arkimapslib.lint import Lint
from arkimapslib.orders import Order
from arkimapslib.render import Renderer
VERSION = "1.18"
SYSTEM_RECIPE_DIR = "/usr/share/arkimaps/recipes"
log = logging.getLogger("arkimaps")
class LogCollector(logging.Handler):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.entries = outputbundle.Log()
def emit(self, record: logging.LogRecord):
self.entries.append(
ts=time.clock_gettime(time.CLOCK_REALTIME), level=record.levelno, msg=self.format(record), name=record.name
)
#
# Mixins used to compose the various command line actions
#
class RecipesMixin(Command):
"""
Command line options and code to load recipes into a kitchen
"""
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
default_recipes_dir = SYSTEM_RECIPE_DIR
if os.path.isdir("recipes"):
default_recipes_dir = os.path.abspath("recipes")
parser.add_argument(
"--recipes",
metavar="dir",
action="store",
default=default_recipes_dir,
help="directory with the YAML recipes (default: ./recipes (if existing)" " or " + SYSTEM_RECIPE_DIR,
)
return parser
def load_recipes(self, lint: Optional[Lint] = None):
"""
Load recipes into the already created kitchen
"""
self.kitchen.load_recipes([self.args.recipes], lint=lint)
class FlavoursMixin(Command):
"""
Command that takes one or more flavours as option
"""
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
parser.add_argument(
"--flavours",
action="store",
default="default",
help='comma-separated list of flavours to render. Default: "%(default)s"',
)
return parser
def parse_flavours(self) -> List[Flavour]:
"""
Parse --flavours argument into a list of flavours
"""
flavours = []
for flavour_name in self.args.flavours.split(","):
flavour = self.kitchen.flavours.get(flavour_name)
if flavour is None:
raise Fail(f'Flavour "{flavour_name}" not found')
flavours.append(flavour)
return flavours
class RenderMixin(FlavoursMixin):
"""
Command line options to control rendering of recipes
"""
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
default_styles = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "styles"))
if not os.path.isdir(default_styles):
default_styles = "/usr/share/magics/styles/ecmwf"
parser.add_argument(
"--styles",
metavar="dir",
action="store",
default=default_styles,
help="styles directory. Default: ./styles (if existing) or /usr/share/magics/styles/ecmwf",
)
parser.add_argument(
"--output",
"-o",
metavar="file.tar|zip",
action="store",
help="write rendered output to the given file. Default: write to stdout",
)
return parser
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
# Collect log entries that we can then add to the output data
# TODO: save intermediate log in workdir
self.log_collector = LogCollector()
self.log_collector.setLevel(logging.DEBUG)
root_logger = logging.getLogger()
root_logger.addHandler(self.log_collector)
def get_styles_directory(self):
"""
Return the directory where Magics styles are stored
"""
return self.args.styles
@contextlib.contextmanager
def open_output(self) -> Generator[outputbundle.Writer, None, None]:
if self.args.output:
writer_cls: Type[outputbundle.Writer]
if self.args.output.endswith(".zip"):
writer_cls = outputbundle.ZipWriter
else:
writer_cls = outputbundle.TarWriter
with open(self.args.output, "wb") as out:
with writer_cls(out=out) as bundle:
yield bundle
else:
with outputbundle.TarWriter(out=sys.stdout.buffer) as bundle:
yield bundle
def render_tarball(self) -> None:
"""
Render all recipes for which inputs are available, into a tarball
"""
flavours = self.parse_flavours()
orders: List[Order] = []
for flavour in flavours:
# List of products that should be rendered
orders += self.kitchen.make_orders(flavour=flavour)
# Prepare input summary after we're done with input processing
input_summary = outputbundle.InputSummary()
self.kitchen.pantry.summarize_inputs(orders, input_summary)
renderer = Renderer(
config=self.kitchen.config, workdir=self.kitchen.workdir, styles_dir=self.get_styles_directory()
)
rendered: List[Order] = []
with self.open_output() as bundle:
# Add input summary
bundle.add_input_summary(input_summary)
# Perform rendering
rendered = renderer.render(orders, bundle)
bundle.add_log(self.log_collector.entries)
# Add products summary
products_info = outputbundle.Products()
for order in rendered:
products_info.add_order(order)
bundle.add_products(products_info)
# Let the Pantry store processing artifacts if it has any
self.kitchen.pantry.store_processing_artifacts(bundle)
def print_render_plan(self):
"""
Print a list of operations that would be done during rendering
"""
flavours = self.parse_flavours()
for flavour in flavours:
# List of products that should be rendered
orders = self.kitchen.make_orders(flavour=flavour)
by_name = defaultdict(list)
for order in orders:
by_name[order.recipe.name].append(order)
for name, orders in by_name.items():
print(f"{flavour}: {name}:")
for order in orders:
print(f" {order}")
class WorkingKitchenMixin(Command):
"""
Mixin for commands that need a kitchen that can be used to generate
products
"""
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
parser.add_argument(
"--filter",
metavar="{arkimet|eccodes}",
default="arkimet",
help="backend to use to organise data into recipe inputs. Default: %(default)s",
)
parser.add_argument(
"--grib",
action="store_true",
help="read input as GRIB data instead of arkimet output. Implies --filter=eccodes",
)
return parser
def make_kitchen(self, workdir):
if self.args.grib or self.args.filter == "eccodes":
from arkimapslib.kitchen import EccodesKitchen
return EccodesKitchen(workdir, grib_input=self.args.grib)
elif self.args.filter == "arkimet":
from arkimapslib.kitchen import ArkimetKitchen
return ArkimetKitchen(workdir)
else:
raise Fail(f"Unsupported value `{self.args.filter}` for --filter")
#
# Command line actions
#
class PrintArkiQuery(RecipesMixin, Command):
"""
print an arkimet query to query data that can be used by the recipes found
"""
NAME = "print-arki-query"
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
from arkimapslib.kitchen import ArkimetEmptyKitchen
self.kitchen = ArkimetEmptyKitchen()
self.load_recipes()
def run(self):
merged = self.kitchen.get_merged_arki_query()
print(merged)
class DocumentRecipes(RecipesMixin, Command):
"""
generate recipes documentation
"""
NAME = "document-recipes"
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
parser.add_argument(
"--destdir",
metavar="dir",
action="store",
help="directory where documentation is written. It" " defaults to the recipes directory",
)
return parser
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
from arkimapslib.kitchen import EccodesEmptyKitchen
self.kitchen = EccodesEmptyKitchen()
self.load_recipes()
def run(self):
dest = self.args.destdir
if dest is None:
dest = self.args.recipes
if not os.path.isdir(dest):
os.makedirs(dest)
self.kitchen.document_recipes(dest)
class DumpRecipes(RecipesMixin, FlavoursMixin, Command):
"""
dump content parsed from recipes directory
"""
NAME = "dump-recipes"
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
parser.add_argument("--inputs", action="store_true", help="dump inputs instead of recipes")
return parser
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
from arkimapslib.kitchen import EccodesEmptyKitchen
self.kitchen = EccodesEmptyKitchen()
self.load_recipes()
def dump_recipes(self):
res_inputs = {}
for name, inputs in self.kitchen.pantry.inputs.items():
res_inputs[name] = []
for idx, inp in enumerate(inputs, start=1):
res_inputs[name].append(inp.to_dict())
res = {}
res["inputs"] = res_inputs
json.dump(res, sys.stdout, indent=1)
print()
# TODO: self.recipes = Recipes()
# TODO: self.flavours: Dict[str, Flavour] = {}
def dump_inputs(self):
flavours = self.parse_flavours()
all_inputs = self.kitchen.list_inputs(flavours)
for name in sorted(all_inputs):
print(name)
def run(self):
if self.args.inputs:
self.dump_inputs()
else:
self.dump_recipes()
class LintCmd(RecipesMixin, Command):
"""
Validate contents of recipes
"""
NAME = "lint"
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
from arkimapslib.kitchen import EccodesEmptyKitchen
self.kitchen = EccodesEmptyKitchen()
def run(self):
lint = Lint()
self.load_recipes(lint=lint)
class Dispatch(RecipesMixin, WorkingKitchenMixin, FlavoursMixin, Command):
"""
do not render: dispatch into a working directory
"""
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
parser.add_argument("workdir", metavar="dir", action="store", help="working directory")
return parser
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.kitchen = self.make_kitchen(self.args.workdir)
self.load_recipes()
def run(self):
"""
Acquire input data
"""
self.kitchen.fill_pantry(flavours=self.parse_flavours())
class Render(RecipesMixin, RenderMixin, WorkingKitchenMixin, Command):
"""
render data that was already dispatched
"""
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
parser.add_argument("workdir", metavar="dir", action="store", help="working directory")
parser.add_argument(
"--simulate",
action="store_true",
help="print what products would be generated" " (note that this will still generate derived inputs)",
)
return parser
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.kitchen = self.make_kitchen(self.args.workdir)
self.load_recipes()
self.kitchen.pantry.rescan()
def run(self):
"""
Render all recipes for which inputs are available
"""
if self.args.simulate:
self.print_render_plan()
else:
self.render_tarball()
class Preview(RecipesMixin, RenderMixin, WorkingKitchenMixin, Command):
"""
generate the given product only, and display it with xdg-open
"""
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
parser.add_argument(
"-d", "--date", metavar="datetime", action="store", help="render product at this reference time"
)
parser.add_argument("workdir", metavar="dir", action="store", help="working directory")
parser.add_argument("name", metavar="prod[+step]", action="store", help="name of the product to preview")
return parser
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.kitchen = self.make_kitchen(self.args.workdir)
self.load_recipes()
self.kitchen.pantry.rescan()
def run(self):
"""
Generate the given product only, and preview it with xdg-open
"""
if "+" in self.args.name:
name, step = self.args.name.split("+")
step = int(step, 10)
else:
name = self.args.name
step = None
if self.args.date is not None:
res = subprocess.run(["date", "--date=" + self.args.date, "+%s"], text=True, capture_output=True)
reftime = datetime.datetime.fromtimestamp(int(res.stdout))
else:
reftime = None
flavours = self.parse_flavours()
if len(flavours) != 1:
raise Fail("Only 1 flavour is supported for preview")
flavour = flavours[0]
# Make an order
order = self.kitchen.make_order(self.kitchen.recipes.get(name), flavour=flavour, step=step, reftime=reftime)
# Prepare it
renderer = Renderer(
config=self.kitchen.config, workdir=self.kitchen.workdir, styles_dir=self.get_styles_directory()
)
order = renderer.render_one(order)
log.info("Rendered %s to %s", order.recipe.name, order.output.relpath)
# Display it
output_pathname = os.path.join(self.kitchen.workdir, order.output.relpath)
subprocess.run(["xdg-open", output_pathname], check=True)
input("Press enter when done> ")
os.unlink(output_pathname)
class Process(RecipesMixin, RenderMixin, WorkingKitchenMixin, Command):
"""
draw maps based on GRIB data
"""
@classmethod
def make_subparser(cls, subparsers):
parser = super().make_subparser(subparsers)
parser.add_argument(
"--workdir", metavar="dir", action="store", help="working directory. Default: a temporary one"
)
return parser
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
# Set up working directory
self.kitchen = self.make_kitchen(self.args.workdir)
self.load_recipes()
def run(self):
# Acquire input data
self.kitchen.fill_pantry(flavours=self.parse_flavours())
self.render_tarball()
def main():
parser = argparse.ArgumentParser(description="Render maps from model output.")
parser.add_argument("-v", "--verbose", action="store_true", help="verbose output")
parser.add_argument("--debug", action="store_true", help="verbose output")
parser.add_argument("--version", action="version", version="%(prog)s " + VERSION)
# From Python 3.7+, use required=True
subparsers = parser.add_subparsers(help="sub-command help", dest="command")
Process.make_subparser(subparsers)
PrintArkiQuery.make_subparser(subparsers)
DocumentRecipes.make_subparser(subparsers)
Dispatch.make_subparser(subparsers)
Render.make_subparser(subparsers)
Preview.make_subparser(subparsers)
DumpRecipes.make_subparser(subparsers)
LintCmd.make_subparser(subparsers)
args = parser.parse_args()
if args.command is None:
parser.print_help()
return
else:
handler = args.command(args)
if getattr(handler, "kitchen", None) is not None:
with handler.kitchen:
res = handler.run()
else:
res = handler.run()
if res is not None:
sys.exit(res)
if __name__ == "__main__":
try:
main()
except Fail as e:
print(e, file=sys.stderr)
sys.exit(1)
except Success:
pass