Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ Dates are given for tagged releases only.
first NaN) instead of the smallest valid cost, giving a NaN cost and a wrong wind on the pixels where
only some wind candidates have a valid cost.
- Configuration tests no longer read the user file of the computer (`~/.config/grs/config.yml`).
- Exit status of `grs` and of `exe/launcher.py` (issue #13): a processing error ended with status 0, so that the
processing chains went on to the Level-2B with no Level-2A product. The status is now 0 when the product is
written (or already there with `--no_clobber`), 1 for a processing error, 2 for invalid arguments or a missing /
unreadable input (was -1, i.e. 255), 3 for an image skipped on purpose without product (cloud cover, no water,
was 0). `grs.run.main` returns it (`argv` argument for tests) and closes its log files; the `--no_clobber` check of
the launcher also finds the Zarr products and the no-water marker.

## [3.1.0]

Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,16 @@ the aerosol optical thickness, the flags and the mask of the valid water pixels,
| `--no_clobber` | skip the images already processed |
| `--snap_compliant` | one variable per band, for ESA SNAP |

Exit status of `grs` (and of `exe/launcher.py`), for the processing chains: only 0 gives a product for
the next steps (e.g. Level-2B).

| status | |
|---|---|
| 0 | L2A product written (or, with `--no_clobber`, already there) |
| 1 | processing error (traceback in `log_file.log` and `error.log`) |
| 2 | invalid arguments, missing or unreadable input (Level-1, CAMS, SURFWATER, LUT) |
| 3 | image skipped on purpose, no product: cloud cover above `--max_cloud_cover`, or not enough water (marker file `<name>_no_water.txt`) |

From Python:

```python
Expand Down
66 changes: 44 additions & 22 deletions exe/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

from grs import class_logger
from grs import __version__
from grs.grs_process import Process
from grs.run import s2_cloud_cover
from grs.grs_process import Process, no_water_marker
from grs.grs_exceptions import GRS_IO_Exception
from grs.run import s2_cloud_cover, EXIT_OK, EXIT_ERROR, EXIT_INPUT, EXIT_SKIPPED
from pathlib import Path
import yaml
import sys
Expand All @@ -19,6 +20,25 @@


def main():
'''
Process the image of the configuration files (see `_main`) and close the log files whatever the outcome;
returns the exit status (``grs.run.EXIT_*``).
'''
try:
return _main()
finally:
# Close logger and get stats (if it was set up)
logger = getattr(class_logger.THIS, 'klass', None)
if logger is not None:
logger.close()


def _main():
'''
Process the image of the configuration files; returns the exit status (``grs.run.EXIT_*``): 0 product written
(or already there with noclobber), 1 processing error, 2 missing or unreadable input, 3 image skipped on
purpose (cloud cover, no water): no product.
'''
# read config and prepare environment
if len(sys.argv) > 1:
config_file = sys.argv[1]
Expand Down Expand Up @@ -49,10 +69,10 @@ def main():

if not file.exists():
logging.error("Missing input file. Process stopped")
exit(-1)
return EXIT_INPUT
if not data["cams_folder"]:
logging.error("Missing CAMS folder. Process stopped")
exit(-1)
return EXIT_INPUT

input_filename = file.name

Expand All @@ -75,16 +95,16 @@ def main():

# Verify existence of inputs
if not file.is_dir():
logging.error("Input file doesn't exit. Process stopped")
exit(-1)
logging.error("Input file doesn't exist. Process stopped")
return EXIT_INPUT

if not cams_file.is_file():
logging.error("CAMS file doesn't exit. Process stopped")
exit(-1)
logging.error("CAMS file doesn't exist. Process stopped")
return EXIT_INPUT

if data["surfwater_file"] and not Path(data["surfwater_file"]).is_file():
logging.error("SurfWater file doesn't exit. Process stopped")
exit(-1)
logging.error("SurfWater file doesn't exist. Process stopped")
return EXIT_INPUT

# prepare outfile
suffix = data["suffix"]
Expand All @@ -96,12 +116,15 @@ def main():
outdir = misc.set_ofile(input_filename, odir=output_dir, level_name='L2AGRS', suffix=suffix)
outdir.mkdir(parents=True, exist_ok=True)

outfile = Path(outdir, f"{outdir.name}.nc")

# skip if already processed
if Path(outfile).is_file() & data["noclobber"]:
logging.info(f'File {outfile} already processed; skip!')
exit(-1)
# skip if already processed (Zarr store, the default, or NetCDF file), or already found without water
if data["noclobber"]:
for outfile in (Path(outdir, f"{outdir.name}.zarr"), Path(outdir, f"{outdir.name}.nc")):
if outfile.exists():
logging.info(f'File {outfile} already processed; skip!')
return EXIT_OK
if no_water_marker(outdir).exists():
logging.info(f'File {no_water_marker(outdir)} found (image without water); skip!')
return EXIT_SKIPPED

logging.info(f'call grs_process for the following parameters. '
f'File: {file} , '
Expand All @@ -118,7 +141,7 @@ def main():
cc = s2_cloud_cover(file)
if cc >= max_cc:
logging.info('input file not processed since cloud cover {:.3f} is greater than {:.3f}'.format(cc, max_cc))
return
return EXIT_SKIPPED

try:
process_ = Process()
Expand All @@ -132,19 +155,18 @@ def main():
allpixels=data["allpixels"],
surfwater_file=data["surfwater_file"],
snap_compliant=data["snap_compliant"])
# for an image without water: marker file <outdir>/<name>_no_water.txt instead of the product
process_.write_output()
return EXIT_SKIPPED if getattr(process_, 'no_water', False) else EXIT_OK

except Exception as inst:
logging.error('-------------------------------')
message = 'error for file ' + str(inst) + ' skip'
logging.error(message)
logging.error('-------------------------------')
logging.error('error during grs', exc_info=True)

finally:
# Close logger and get stats
class_logger.get_instance().close()
return EXIT_INPUT if isinstance(inst, GRS_IO_Exception) else EXIT_ERROR


if __name__ == '__main__':
main()
sys.exit(main())
67 changes: 56 additions & 11 deletions grs/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,34 @@
For CNES datalake:
grs /work/datalake/S2-L1C/31TFJ/2023/06/16/S2B_MSIL1C_20230616T103629_N0509_R008_T31TFJ_20230616T111826.SAFE --cams_file /work/datalake/watcal/ECMWF/CAMS/2023/06/16/2023-06-16-cams-global-atmospheric-composition-forecasts.nc --odir /work/datalake/watcal/test --resolution 20 --dem_file /work/datalake/static_aux/MNT/COP-DEM_GLO-30-DGED_S2_tiles/COP-DEM_GLO-30-DGED_31TFJ.tif

Exit status:
0 the L2A product is written (or, with --no_clobber, already exists)
1 processing error (traceback in the log files)
2 invalid arguments, missing or unreadable input file (Level-1, CAMS, SURFWATER, LUT)
3 image skipped on purpose, no product: cloud cover above --max_cloud_cover, or not enough water
(marker file <name>_no_water.txt written or, with --no_clobber, already there)
Only exit status 0 gives a product for the next steps of a processing chain (e.g. Level-2B).

'''

import ctypes
import ctypes.util
import logging
import os

import sys
from pathlib import Path
from xml.etree import ElementTree
from docopt import docopt
from docopt import docopt, DocoptExit

from . import __package__, __version__

# exit status of the grs command (and of exe/launcher.py), see the Exit status section above
EXIT_OK = 0 # product written (or already there with --no_clobber)
EXIT_ERROR = 1 # processing error
EXIT_INPUT = 2 # invalid arguments, missing or unreadable input
EXIT_SKIPPED = 3 # skipped on purpose (cloud cover, no water): no product


def set_ofile(filename: str, odir='', level_name='L2GRS', suffix='') -> Path:
"""Output path: level name of `filename` replaced by `level_name`, extension removed, `suffix` appended."""
Expand Down Expand Up @@ -98,17 +113,35 @@ def limit_malloc_arenas(n=2):
pass


def main():
def main(argv=None):
'''
``grs`` command: process one Level-1 image.

:param argv: command line arguments (default: ``sys.argv[1:]``)
:return: exit status, see the module constants ``EXIT_*`` (the console script passes it to ``sys.exit``)
'''
# before any thread is started
limit_malloc_arenas()
# -h / -v are handled (and exit) here, before the heavy imports below
args = docopt(__doc__, version=__package__ + '_' + __version__)
# -h / -v are handled (and exit with status 0) here, before the heavy imports below
try:
args = docopt(__doc__, argv=argv, version=__package__ + '_' + __version__)
except DocoptExit as exc:
print(exc, file=sys.stderr)
return EXIT_INPUT
print(args)

from . import class_logger
from .grs_process import Process, no_water_marker
from .grs_exceptions import GRS_IO_Exception

file = Path(args['<input_file>'])
if not file.exists():
print(f'input file not found: {file}', file=sys.stderr)
return EXIT_INPUT
for name, path in (('CAMS', args['--cams_file']), ('SURFWATER', args['--surfwater']), ('DEM', args['--dem_file'])):
if path and not Path(path).exists():
print(f'{name} file not found: {path}', file=sys.stderr)
return EXIT_INPUT

lev = args['--levname']
cams_file = args['--cams_file']
Expand All @@ -135,7 +168,8 @@ def main():
cc = s2_cloud_cover(file)
if cc >= max_cc:
logging.info('input file not processed since cloud cover {:.3f} is greater than {:.3f}'.format(cc, max_cc))
return
print(f'cloud cover {cc:.3f} greater than {max_cc:.3f}: image not processed', file=sys.stderr)
return EXIT_SKIPPED

odir = args['--odir']
if odir == './':
Expand All @@ -152,10 +186,12 @@ def main():
# skip if already processed, or already found without water (marker file of Process.write_output);
# checked before the logger is set up, which would overwrite the log file of the previous run
if noclobber:
for done in (outfile, no_water_marker(outdir)):
if done.exists():
print(f'File {done} already processed; skip!')
exit(-1)
if outfile.exists():
print(f'File {outfile} already processed; skip!')
return EXIT_OK
if no_water_marker(outdir).exists():
print(f'File {no_water_marker(outdir)} found (image without water); skip!')
return EXIT_SKIPPED

outdir.mkdir(parents=True, exist_ok=True)
class_logger.ServiceLogger(log_file=str(Path(outdir, 'log_file.log')), error_log="error.log", log_level='INFO',
Expand Down Expand Up @@ -184,10 +220,19 @@ def main():
min_water_area=min_water_area)
# for an image without water: marker file <outdir>/<name>_no_water.txt instead of the product
process_.write_output()
except GRS_IO_Exception:
logging.error("Input error in grs_process", exc_info=True)
return EXIT_INPUT
except Exception:
logging.error("Fatal error in grs_process", exc_info=True)
return
return EXIT_ERROR
finally:
# log the run statistics and close the log files
class_logger.get_instance().close()
if getattr(process_, 'no_water', False):
return EXIT_SKIPPED
return EXIT_OK


if __name__ == "__main__":
main()
sys.exit(main())
Loading
Loading