diff --git a/CHANGELOG.md b/CHANGELOG.md index 06e47e5..1ae2008 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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] diff --git a/README.md b/README.md index 29af954..68f9a65 100644 --- a/README.md +++ b/README.md @@ -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 `_no_water.txt`) | + From Python: ```python diff --git a/exe/launcher.py b/exe/launcher.py index f34e47c..14156c7 100644 --- a/exe/launcher.py +++ b/exe/launcher.py @@ -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 @@ -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] @@ -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 @@ -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"] @@ -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} , ' @@ -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() @@ -132,7 +155,9 @@ def main(): allpixels=data["allpixels"], surfwater_file=data["surfwater_file"], snap_compliant=data["snap_compliant"]) + # for an image without water: marker file /_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('-------------------------------') @@ -140,11 +165,8 @@ def main(): 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()) diff --git a/grs/run.py b/grs/run.py index da1a1b2..63c6787 100644 --- a/grs/run.py +++ b/grs/run.py @@ -45,6 +45,14 @@ 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 _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 @@ -52,12 +60,19 @@ 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.""" @@ -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['']) + 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'] @@ -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 == './': @@ -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', @@ -184,10 +220,19 @@ def main(): min_water_area=min_water_area) # for an image without water: marker file /_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()) diff --git a/grs/tests/unit/test_exit_codes.py b/grs/tests/unit/test_exit_codes.py new file mode 100644 index 0000000..93aa1c4 --- /dev/null +++ b/grs/tests/unit/test_exit_codes.py @@ -0,0 +1,153 @@ +"""Exit status of the grs command (grs.run.main) and of the CNES launcher (exe/launcher.py), issue #13. + +The processing is replaced by a fake Process: these tests only check how each outcome is turned into an exit +status (0 product, 1 processing error, 2 input error, 3 skipped on purpose). +""" + +import sys + +import pytest +import yaml + +import grs.grs_process +from grs import run +from grs.grs_exceptions import GRS_IO_Exception +from grs.run import EXIT_OK, EXIT_ERROR, EXIT_INPUT, EXIT_SKIPPED + +SAFE_NAME = 'S2C_MSIL1C_20260707T112111_N0512_R037_T28PEC_20260707T145811.SAFE' +MTD = ('{cc}' + '') + + +class FakeProcess: + """Process whose execute ends as set by `outcome`.""" + outcome = 'ok' + + def __init__(self): + self.no_water = False + + def execute(self, l1c_prod, **kwargs): + if self.outcome == 'error': + # the error of issue #13 (GRS 2.1.9, image T28PEC of 2026-07-07) + raise ValueError('arange: cannot compute length') + if self.outcome == 'io': + raise GRS_IO_Exception(l1c_prod, OSError('cannot read')) + if self.outcome == 'no_water': + self.no_water = True + + def write_output(self): + pass + + +@pytest.fixture +def fake_process(monkeypatch): + monkeypatch.setattr(grs.grs_process, 'Process', FakeProcess) + yield FakeProcess + FakeProcess.outcome = 'ok' + + +@pytest.fixture +def safe(tmp_path): + """Level-1 product folder with a cloud cover of 10 %.""" + path = tmp_path / SAFE_NAME + path.mkdir() + (path / 'MTD_MSIL1C.xml').write_text(MTD.format(cc=10.0)) + cams = tmp_path / 'cams.nc' + cams.write_text('') + return path, cams + + +# ---------------------------------------------------------------------------------------------------- grs command + +def grs_main(safe, *options): + path, cams = safe + return run.main([str(path), '--cams_file', str(cams), '--odir', str(path.parent / 'out'), *options]) + + +@pytest.mark.parametrize('outcome, status', [('ok', EXIT_OK), ('error', EXIT_ERROR), ('io', EXIT_INPUT), + ('no_water', EXIT_SKIPPED)]) +def test_grs_processing_outcome(fake_process, safe, outcome, status): + fake_process.outcome = outcome + assert grs_main(safe) == status + + +def test_grs_cloud_cover_skipped(fake_process, safe): + assert grs_main(safe, '--max_cloud_cover', '0.05') == EXIT_SKIPPED + + +def test_grs_missing_input(fake_process, safe, tmp_path): + _, cams = safe + assert run.main([str(tmp_path / 'missing.SAFE'), '--cams_file', str(cams)]) == EXIT_INPUT + + +def test_grs_missing_cams(fake_process, safe, tmp_path): + path, _ = safe + assert run.main([str(path), '--cams_file', str(tmp_path / 'missing.nc')]) == EXIT_INPUT + + +def test_grs_invalid_arguments(fake_process): + assert run.main(['image.SAFE', '--unknown_option']) == EXIT_INPUT + + +def test_grs_no_clobber(fake_process, safe): + path, _ = safe + outdir = run.set_ofile(path.name, odir=path.parent / 'out', level_name='L2AGRS', suffix=f'_V{grs.__version__}') + outdir.mkdir(parents=True) + # no-water marker of a previous run: skipped, no product + marker = grs.grs_process.no_water_marker(outdir) + marker.write_text('') + assert grs_main(safe, '--no_clobber') == EXIT_SKIPPED + # product of a previous run: available for the next steps + (outdir / (outdir.name + '.zarr')).mkdir() + assert grs_main(safe, '--no_clobber') == EXIT_OK + + +def test_grs_version(capsys): + with pytest.raises(SystemExit) as exc: + run.main(['--version']) + assert exc.value.code in (None, 0) + + +# ---------------------------------------------------------------------------------------------------- CNES launcher + +@pytest.fixture +def launcher(monkeypatch, tmp_path, safe): + """exe.launcher.main with configuration files in tmp_path; returns a function (settings) -> exit status.""" + from exe import launcher as launcher_module + monkeypatch.setattr(launcher_module, 'Process', FakeProcess) + path, cams = safe + + def call(**settings): + hymotep = dict(input_file=str(path), cams_folder=str(cams), output_dir=str(tmp_path / 'out'), + surfwater_file=None, dem_file=None, suffix=None, noclobber=False, max_cloud_cover=1., + resolution=60, scale_aot=1., opac_model=None, allpixels=False, snap_compliant=False) + hymotep.update(settings) + (tmp_path / 'hymotep.yml').write_text(yaml.safe_dump(hymotep)) + (tmp_path / 'global.yml').write_text(yaml.safe_dump(dict(logfile=str(tmp_path / 'log' / 'grs.log'), + level='INFO', + hymotep_config=str(tmp_path / 'hymotep.yml')))) + monkeypatch.setattr(sys, 'argv', ['launcher.py', str(tmp_path / 'global.yml')]) + return launcher_module.main() + + yield call + FakeProcess.outcome = 'ok' + + +@pytest.mark.parametrize('outcome, status', [('ok', EXIT_OK), ('error', EXIT_ERROR), ('io', EXIT_INPUT), + ('no_water', EXIT_SKIPPED)]) +def test_launcher_processing_outcome(launcher, outcome, status): + FakeProcess.outcome = outcome + assert launcher() == status + + +def test_launcher_missing_input(launcher, tmp_path): + assert launcher(input_file=str(tmp_path / 'missing.SAFE')) == EXIT_INPUT + + +def test_launcher_missing_cams(launcher, tmp_path): + assert launcher(cams_folder=str(tmp_path / 'missing.nc')) == EXIT_INPUT + + +def test_launcher_cloud_cover_skipped(launcher): + assert launcher(max_cloud_cover=0.05) == EXIT_SKIPPED