diff --git a/docker/extract_indexes.sh b/docker/extract_indexes.sh index a5ee45c..2ccfd50 100644 --- a/docker/extract_indexes.sh +++ b/docker/extract_indexes.sh @@ -1,109 +1,121 @@ #!/bin/bash # Copyright (C) 2021-2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information WORKDIR=${1-/work} FILE_IN=$WORKDIR/nexus-maven-repository-index.gz localtime=$(date +"%Y-%m-%d %H:%M:%S") echo "Docker Script started on $localtime." echo "# Checks.." echo "* Content of /opt:" ls -l /opt echo "* Content of $WORKDIR:" ls -l $WORKDIR echo "* Will read files from [$FILE_IN]." if [ ! -r "$FILE_IN" ]; then + exit_code=4 echo "Cannot find file [$FILE_IN]." - echo "Need an index file to work on. Exiting 4." - exit 4 + echo "Need an index file to work on. Exiting ${exit_code}." + exit $exit_code else echo "* Found file [$FILE_IN]." fi indexer=$(find /opt/ -name "indexer-cli-*.jar") if [ "$indexer" = "" ]; then - echo "Cannot find indexer. Exiting 6." - exit 6 + exit_code=6 + echo "Cannot find indexer. Exiting ${exit_code}." + exit exit_code else echo "* Found indexer [$indexer]." fi clue=$(find /opt/ -name "clue-*.jar") if [ "$clue" = "" ]; then - echo "Cannot find clue. Exiting 8." - exit 8 + exit_code=8 + echo "Cannot find clue. Exiting ${exit_code}." + exit $exit_code else echo "* Found clue [$clue]." fi echo "* Java version:." java -version echo "#############################" if [ -d $WORKDIR/indexes ]; then echo "Found $WORKDIR/indexes, skipping index generation." du -sh $WORKDIR/indexes/ else echo "Unpacking [$FILE_IN] to $WORKDIR/indexes" java --illegal-access=permit -jar $indexer \ --unpack $FILE_IN \ --destination $WORKDIR/indexes/ \ --type full 2>&1 | grep -v WARNING fi localtime=$(date +"%Y-%m-%d %H:%M:%S") echo "Unpacking finished on $localtime." echo "#############################" -if [ -d $WORKDIR/export ]; then - echo "Found $WORKDIR/export, skipping index export." - ls -lh $WORKDIR/export/ +EXPORT_DIR=$WORKDIR/export/ +TEMP_FLD=$(find $EXPORT_DIR -name "*.fld") +TEMP_FLD_LOCK=$(find $EXPORT_DIR -name "*.lock") + +if [[ -f $TMP_FLD && -f $TEMP_FLD_LOCK ]]; then + exit_code=1 + echo "Found exported file $TEMP_FLD. Another process is updating it. Stopping." + exit $exit_code +elif [[ -f $TMP_FLD && ! -f $TEMP_FLD_LOCK ]]; then + echo "Found final exported file $TEMP_FLD, skipping index export." + ls -lh $EXPORT_DIR else echo "Exporting indexes $WORKDIR/indexes to $WORKDIR/export" java --illegal-access=permit -jar $clue \ $WORKDIR/indexes/ \ - export $WORKDIR/export/ text 2>&1 | grep -v WARNING + export $EXPORT_DIR text 2>&1 | grep -v WARNING fi localtime=$(date +"%Y-%m-%d %H:%M:%S") echo "Exporting finished on $localtime." echo "#############################" echo "Cleaning useless files." echo "Size before cleaning:" du -sh $WORKDIR/* # We might want or not to delete the indexes # Remember that when they're not present, everything # gets recomputed every run.. -#echo "* Removing indexes." -#rm -rf $WORKDIR/indexes/ +# echo "* Removing indexes." +# rm -rf $WORKDIR/indexes/ # If files others than the .fld one are required, please comment # the following lines. echo "* Removing useless exports." echo " Keeping only fld text extract." -rm -f $WORKDIR/export/*.inf -rm -f $WORKDIR/export/*.len -rm -f $WORKDIR/export/*.pst -rm -f $WORKDIR/export/*.si -rm -f $WORKDIR/export/segments* +rm -f $EXPORT_DIR/*.inf +rm -f $EXPORT_DIR/*.len +rm -f $EXPORT_DIR/*.pst +rm -f $EXPORT_DIR/*.si +rm -f $EXPORT_DIR/segments* +rm -f $EXPORT_DIR/*.lock echo " Size after cleaning:" du -sh $WORKDIR/* echo "* Make files modifiable by the end-user." -chmod -R 777 $WORKDIR/export/ +chmod -R 777 $EXPORT_DIR chmod -R 777 $WORKDIR/indexes/ localtime=$(date +"%Y-%m-%d %H:%M:%S") echo "Docker Script execution finished on $localtime." diff --git a/docker/run_full_export.py b/docker/run_full_export.py index c40fd24..751d5e8 100644 --- a/docker/run_full_export.py +++ b/docker/run_full_export.py @@ -1,170 +1,175 @@ # Copyright (C) 2021-2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import logging import click import sys import datetime import glob import re -from subprocess import check_call +from subprocess import check_call, CalledProcessError from os import chdir, makedirs from os.path import getsize, isabs, isdir, isfile, join, basename from pathlib import Path from shutil import copy2 from urllib.parse import urljoin import requests logger = logging.getLogger(__name__) MAVEN_INDEX_NAME = "nexus-maven-repository-index" MAVEN_INDEX_ARCHIVE = f"{MAVEN_INDEX_NAME}.gz" def _download_indexes(base_url: str, work_dir: str) -> None: """Download all required indexes from the .index/ directory of the specified instance. """ if base_url.startswith('test://'): logger.info("(Testing) Fake downloading required indexes") return None logger.info("Downloading required indexes") index_url = urljoin(base_url, ".index/") properties_name = f"{MAVEN_INDEX_NAME}.properties" properties_file = join(work_dir, properties_name) properties_url = urljoin(index_url, properties_name) # Retrieve properties file. logger.info(" - Downloading %s.", properties_file) content = requests.get(properties_url).content.decode() open(properties_file, "w").write(content) diff_re = re.compile("^nexus.index.incremental-[0-9]+=([0-9]+)") for line in content.split("\n"): diff_group = diff_re.match(line) if diff_group is not None: ind_name = f"{MAVEN_INDEX_NAME}.{diff_group.group(1)}.gz" ind_path = join(work_dir, ind_name) ind_url = urljoin(index_url, ind_name) if isfile(ind_path): logger.info( " - File %s exists, skipping download.", basename(ind_path) ) else: logger.info( " - File %s doesn't exist. Downloading file from %s.", basename(ind_path), ind_url, ) # Retrieve incremental gz file contentb = requests.get(ind_url).content open(ind_path, "wb").write(contentb) # Retrieve main index file. ind_path = join(work_dir, MAVEN_INDEX_ARCHIVE) ind_url = urljoin(index_url, MAVEN_INDEX_ARCHIVE) if isfile(ind_path): logger.info(" - File %s exists, skipping download.", basename(ind_path)) else: logger.info( " - File %s doesn't exist. Downloading file from %s", basename(ind_path), ind_url, ) contentb = requests.get(ind_url).content open(ind_path, "wb").write(contentb) @click.command() @click.option( "--base-url", required=True, help=( "Base url of the maven repository instance. \n" "Example: https://repo.maven.apache.org/maven2/" ), ) @click.option( "--work-dir", help="Absolute path to the temp directory.", default="/tmp/maven-index-exporter/", ) @click.option( "--publish-dir", help="Absolute path to the final directory.", default="/tmp/maven-index-exporter/publish/", ) def main(base_url, work_dir, publish_dir): now = datetime.datetime.now() logger.info("Script: run_full_export") logger.info("Timestamp: %s", now.strftime("%Y-%m-%d %H:%M:%S")) logger.info("* URL: %s", base_url) logger.info("* Working directory: %s", work_dir) logger.info("* Publish directory: %s", publish_dir) # Check work_dir and create it if needed. if isdir(work_dir): logger.info("Work_Dir %s exists. Reusing it.", work_dir) else: try: logger.info("Cannot find work_dir %s. Creating it.", work_dir) Path(work_dir).mkdir(parents=True, exist_ok=True) except OSError as error: logger.info("Could not create work_dir %s: %s.", work_dir, error) assert isdir(work_dir) assert isabs(work_dir) # Grab all the indexes # Only fetch the new ones, existing files won't be re-downloaded. _download_indexes(base_url, work_dir) - # Extract indexes into a .fld file - check_call(["/opt/extract_indexes.sh", work_dir]) + try: + # Extract indexes into a .fld file to publish + # this can raise if something is badly wired or something goes wrong + check_call(["/opt/extract_indexes.sh", work_dir]) + except CalledProcessError as e: + logger.error(e) + sys.exit(4) logger.info("Export directory has the following files:") export_dir = join(work_dir, "export") makedirs(export_dir, exist_ok=True) chdir(export_dir) fld_file = None regexp_fld = re.compile(r".*\.fld$") for file_ in glob.glob("*.*"): logger.info(" - %s size %s", file_, getsize(file_)) if regexp_fld.match(file_): fld_file = file_ # Now copy the results to the desired location: publish_dir. if fld_file and isfile(fld_file): logger.info("Found fld file: %s", fld_file) else: logger.info("Cannot find .fld file. Exiting") sys.exit(4) makedirs(publish_dir, exist_ok=True) publish_file = join(publish_dir, "export.fld") logger.info("Copying files to %s.", publish_file) try: copy2(fld_file, publish_file) except OSError as error: logger.info("Could not publish results in %s: %s.", publish_dir, error) now = datetime.datetime.now() logger.info("Script finished on %s", now.strftime("%Y-%m-%d %H:%M:%S")) ############################################### # Start execution ############################################### if __name__ == "__main__": logging.basicConfig(level=logging.INFO) main(auto_envvar_prefix='MVN_IDX_EXPORTER')