From 24af5c812124da83a2e9a7a55b038a7a60852be9 Mon Sep 17 00:00:00 2001
From: Konrad Botor <kbotor@syncad.com>
Date: Fri, 4 Nov 2022 14:30:16 +0100
Subject: [PATCH] Merged prepare_data_image_job.yml from hive/hive> and
 hive/haf> - ref. hive/hive#406

---
 .gitlab-ci.yml                          | 45 ++++++++++++
 .yamllint                               |  4 ++
 README.md                               | 93 ++-----------------------
 misc/checkstyle2junit.xslt              | 44 ++++++++++++
 scripts/bash/delete-image.sh            | 21 ++++++
 scripts/bash/docker_image_utils.sh      | 89 +++++++++++++++++++++++
 scripts/bash/get_image4submodule.sh     | 64 +++++++++++++++++
 templates/data_image_jobs.gitlab-ci.yml | 56 +++++++++++++++
 8 files changed, 328 insertions(+), 88 deletions(-)
 create mode 100644 .gitlab-ci.yml
 create mode 100644 .yamllint
 create mode 100644 misc/checkstyle2junit.xslt
 create mode 100644 scripts/bash/delete-image.sh
 create mode 100644 scripts/bash/docker_image_utils.sh
 create mode 100644 scripts/bash/get_image4submodule.sh
 create mode 100644 templates/data_image_jobs.gitlab-ci.yml

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
new file mode 100644
index 0000000..be14fbc
--- /dev/null
+++ b/.gitlab-ci.yml
@@ -0,0 +1,45 @@
+stages:
+  - validation
+
+include:
+  template: Workflows/Branch-Pipelines.gitlab-ci.yml
+
+.validation_job:
+  stage: validation
+  artifacts:
+    name: validation-results
+    when: always
+  tags:
+    - public-runner-docker
+
+lint_bash_scripts:
+  extends: .validation_job
+  image: koalaman/shellcheck-alpine:latest
+  before_script:
+    - apk add xmlstarlet
+  script:
+    - shellcheck -f checkstyle scripts/bash/*.sh > shellcheck-checkstyle-result.xml 
+  after_script:
+    - xmlstarlet tr misc/checkstyle2junit.xslt shellcheck-checkstyle-result.xml > shellcheck-junit-result.xml
+  artifacts:
+    paths: 
+     - shellcheck-checkstyle-result.xml
+     - shellcheck-junit-result.xml
+    reports:
+      junit: shellcheck-junit-result.xml
+
+lint_ci_templates:
+  extends: .validation_job
+  image: python:latest
+  before_script:
+    - pip install yamllint-junit
+  script:
+    - yamllint --format parsable templates/ > yamllint-parsable-result.txt
+  after_script:
+    - yamllint-junit -o yamllint-junit-result.xml yamllint-parsable-result.txt
+  artifacts:
+    paths: 
+     - yamllint-parsable-result.txt
+     - yamllint-junit-result.xml
+    reports:
+      junit: yamllint-junit-result.xml
\ No newline at end of file
diff --git a/.yamllint b/.yamllint
new file mode 100644
index 0000000..b502b0b
--- /dev/null
+++ b/.yamllint
@@ -0,0 +1,4 @@
+extends: default
+rules:
+  line-length: enable
+  document-start: disable
diff --git a/README.md b/README.md
index f2cd1a1..0524dfa 100644
--- a/README.md
+++ b/README.md
@@ -1,92 +1,9 @@
 # Common CI Configuration
 
+This project contains the common CI templates and scripts.
 
+## Directory structure
 
-## Getting started
-
-To make it easy for you to get started with GitLab, here's a list of recommended next steps.
-
-Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
-
-## Add your files
-
-- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
-- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
-
-```
-cd existing_repo
-git remote add origin https://gitlab.syncad.com/hive/common-ci-configuration.git
-git branch -M main
-git push -uf origin main
-```
-
-## Integrate with your tools
-
-- [ ] [Set up project integrations](https://gitlab.syncad.com/hive/common-ci-configuration/-/settings/integrations)
-
-## Collaborate with your team
-
-- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
-- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
-- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
-- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
-- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
-
-## Test and Deploy
-
-Use the built-in continuous integration in GitLab.
-
-- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
-- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
-- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
-- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
-- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
-
-***
-
-# Editing this README
-
-When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
-
-## Suggestions for a good README
-Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
-
-## Name
-Choose a self-explaining name for your project.
-
-## Description
-Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
-
-## Badges
-On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
-
-## Visuals
-Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
-
-## Installation
-Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
-
-## Usage
-Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
-
-## Support
-Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
-
-## Roadmap
-If you have ideas for releases in the future, it is a good idea to list them in the README.
-
-## Contributing
-State if you are open to contributions and what your requirements are for accepting them.
-
-For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
-
-You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
-
-## Authors and acknowledgment
-Show your appreciation to those who have contributed to the project.
-
-## License
-For open source projects, say how it is licensed.
-
-## Project status
-If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
+- misc - miscellaneous files
+- scripts/bash - Bash scripts
+- templates - GitLab CI templates
diff --git a/misc/checkstyle2junit.xslt b/misc/checkstyle2junit.xslt
new file mode 100644
index 0000000..cb50142
--- /dev/null
+++ b/misc/checkstyle2junit.xslt
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
+  <xsl:output encoding="UTF-8" method="xml"></xsl:output>
+
+  <xsl:template match="/">
+    <testsuite>
+      <xsl:attribute name="tests">
+        <xsl:value-of select="count(.//file)" />
+      </xsl:attribute>
+      <xsl:attribute name="failures">
+        <xsl:value-of select="count(.//error)" />
+      </xsl:attribute>
+      <xsl:for-each select="//checkstyle">
+        <xsl:apply-templates />
+      </xsl:for-each>
+    </testsuite>
+  </xsl:template>
+
+  <xsl:template match="file">
+    <testcase>
+      <xsl:attribute name="classname">
+        <xsl:value-of select="@name" />
+      </xsl:attribute>
+      <xsl:attribute name="name">
+        <xsl:value-of select="@name" />
+      </xsl:attribute>
+      <xsl:apply-templates select="node()" />
+    </testcase>
+  </xsl:template>
+
+  <xsl:template match="error">
+    <failure>
+      <xsl:attribute name="type">
+        <xsl:value-of select="@source" />
+      </xsl:attribute>
+      <xsl:text>Line </xsl:text>
+      <xsl:value-of select="@line" />
+      <xsl:text>: </xsl:text>
+      <xsl:value-of select="@message" />
+      <xsl:text> See https://www.shellcheck.net/wiki/</xsl:text>
+      <xsl:value-of select="substring(@source, '12')" />
+    </failure>
+  </xsl:template>
+</xsl:stylesheet>
\ No newline at end of file
diff --git a/scripts/bash/delete-image.sh b/scripts/bash/delete-image.sh
new file mode 100644
index 0000000..831bb66
--- /dev/null
+++ b/scripts/bash/delete-image.sh
@@ -0,0 +1,21 @@
+#! /bin/bash
+
+set -ex
+
+REGISTRY_USER=${REGISTRY_USER:-gitlab-ci-token}
+REGISTRY_PASS=${REGISTRY_PASS:-${CI_JOB_TOKEN}}
+# DOCKER_IMAGE=${IMAGE_PATH:-${CI_REGISTRY}/${CI_PROJECT_PATH}}
+DOCKER_SERVER=${DOCKER_SERVER:-${CI_REGISTRY}}
+
+PROJECT_ID=${CI_PROJECT_ID}
+echo "Project ID: ${PROJECT_ID}"
+
+REGISTRY_ID=$( curl --request GET --url "https://gitlab.syncad.com/api/v4/projects/${PROJECT_ID}/registry/repositories" --header 'Accept: application/vnd.docker.distribution.manifest.v2+json' --header 'Authorization: Bearer' | jq -c ".[] | select (.location==\"${IMAGE_PATH}\") | .id" )
+echo "Repository ID: ${REGISTRY_ID}"
+
+# TST_REGISTRY_ID=${REGISTRY_ID:?"Missing a registry image matching to given path"}
+
+echo "Deleting '${IMAGE_PATH}:${IMAGE_TAG}' from registry..."
+
+curl --request DELETE --header "PRIVATE-TOKEN: ${REGISTRY_PASS}" \
+  "https://gitlab.syncad.com/api/v4/projects/${PROJECT_ID}/registry/repositories/${REGISTRY_ID}/tags/${IMAGE_TAG}"
diff --git a/scripts/bash/docker_image_utils.sh b/scripts/bash/docker_image_utils.sh
new file mode 100644
index 0000000..80cb468
--- /dev/null
+++ b/scripts/bash/docker_image_utils.sh
@@ -0,0 +1,89 @@
+#! /bin/bash
+
+function build_image_name() {
+  local -r image=$1
+  local -r tag=$2
+  local -r registry=${3}
+  echo "${registry}${image}:${image}-${tag}"
+}
+
+function build_image_registry_path() {
+  local -r image=$1
+  local -r tag=$2
+  local -r registry=${3}
+  echo "${registry}${image}"
+}
+
+function build_image_registry_tag() {
+  local -r image=$1
+  local -r tag=$2
+  local -r registry=${3}
+  echo "${image}-${tag}"
+}
+
+function docker_image_exists() {
+  local -r image=$1
+  local -r tag=$2
+  local -r registry=${3}
+  local -r __resultvar=${4:?"Missing required retval variable name"}
+  local -r look_to_registry=${5:-1}
+
+  local -r imgname=$( build_image_name "$image" "$tag" "$registry" )
+
+  local result=0
+
+  local old_set_e=0
+
+  [[ $- = *e* ]] && old_set_e=1
+  set +e
+
+  echo "Looking for: $imgname"
+  
+  if [ "${look_to_registry}" -eq "1" ];
+  then
+    docker manifest inspect "$imgname" >/dev/null 2>&1
+    result=$?
+    echo "docker manifest inspect returned $result"
+  else
+    docker image inspect --format '{{.Id}}' "$imgname" >/dev/null 2>&1
+    result=$?
+    echo "docker image inspect returned $result"
+  fi
+
+  ((old_set_e)) && set -e
+
+
+  local EXISTS=0
+
+  if [ "$result" -eq "0" ];
+  then
+    EXISTS=1
+  fi
+
+  if [[ "$__resultvar" ]]; then
+      eval "$__resultvar"="'$EXISTS'"
+  else
+      echo "$EXISTS"
+  fi
+}
+
+extract_files_from_image() {
+  IMAGE_TAGGED_NAME=${1:?"Missing image name"}
+  EXPORT_PATH=${2:?"Missing export target directory"}
+  # TST_ANY_FILE=${3:?"Missing file(s) to be exported"}
+  shift
+  shift 
+
+  FILES=("$@")
+
+  echo "Attempting to export file(s):" "${FILES[@]}" "from image: ${IMAGE_TAGGED_NAME} into directory: ${EXPORT_PATH}"
+
+  export DOCKER_BUILDKIT=1
+
+  docker build -o "${EXPORT_PATH}" - << EOF
+    FROM scratch
+    COPY --from=${IMAGE_TAGGED_NAME} "${FILES[@]}" /
+EOF
+
+}
+
diff --git a/scripts/bash/get_image4submodule.sh b/scripts/bash/get_image4submodule.sh
new file mode 100644
index 0000000..eb3b859
--- /dev/null
+++ b/scripts/bash/get_image4submodule.sh
@@ -0,0 +1,64 @@
+#! /bin/bash
+# shellcheck source-path=SCRIPTDIR
+
+set -euo pipefail
+
+SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
+
+IMGNAME="data"
+
+source "$SCRIPTPATH/docker_image_utils.sh"
+
+submodule_path=${1:?"Missing arg 1 for submodule path variable"}
+shift
+REGISTRY=${1:?"Missing arg 2 for REGISTRY variable"}
+shift
+DOTENV_VAR_NAME=${1:?"Missing name of dot-env variable"}
+shift
+REGISTRY_USER=${1:?"Missing arg 4 for REGISTRY_USER variable"}
+shift
+REGISTRY_PASSWORD=${1:?"Missing arg 5 for REGISTRY_PASSWORD variable"}
+shift
+BINARY_CACHE_PATH=${1:?"Missing arg 6 specific to binary cache path"}
+shift
+
+retrieve_submodule_commit () {
+  local -r p="${1}"
+  pushd "$p" >/dev/null 2>&1
+  local -r commit=$( git rev-parse HEAD )
+
+  popd >/dev/null 2>&1
+
+  echo "$commit"
+}
+
+echo "Attempting to get commit for: $submodule_path"
+
+commit=$( retrieve_submodule_commit "${submodule_path}" )
+
+img=$( build_image_name $IMGNAME "$commit" "$REGISTRY" )
+img_path=$( build_image_registry_path $IMGNAME "$commit" "$REGISTRY" )
+img_tag=$( build_image_registry_tag $IMGNAME "$commit" "$REGISTRY" )
+
+echo "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" "$REGISTRY" --password-stdin
+
+image_exists=0
+
+docker_image_exists "$IMGNAME" "$commit" "$REGISTRY" image_exists
+
+if [ "$image_exists" -eq 1 ];
+then
+  echo "Image already exists..."
+  "$SCRIPTPATH/export-binaries.sh" "${img}" "${BINARY_CACHE_PATH}"
+else
+  # Here continue an image build.
+  echo "${img} image is missing. Building it..."
+  "$SCRIPTPATH/build_data4commit.sh" "$commit" "$REGISTRY" --export-binaries="${BINARY_CACHE_PATH}"
+  time docker push "$img"
+fi
+
+echo "$DOTENV_VAR_NAME=$img" > docker_image_name.env
+echo "${DOTENV_VAR_NAME}_REGISTRY_PATH=$img_path" >> docker_image_name.env
+echo "${DOTENV_VAR_NAME}_REGISTRY_TAG=$img_tag" >> docker_image_name.env
+
+cat docker_image_name.env
diff --git a/templates/data_image_jobs.gitlab-ci.yml b/templates/data_image_jobs.gitlab-ci.yml
new file mode 100644
index 0000000..cb28afc
--- /dev/null
+++ b/templates/data_image_jobs.gitlab-ci.yml
@@ -0,0 +1,56 @@
+.docker_image_builder_job:
+  variables:
+    DOCKER_BUILDKIT: 1
+    DOCKER_DRIVER: overlay2
+    DOCKER_TLS_CERTDIR: "/certs"
+  image: docker:20.10.10
+  interruptible: true
+  services:
+    - docker:20.10.10-dind
+  before_script:
+    - apk update && apk add bash git ca-certificates curl
+
+.docker_image_cleanup_job:
+  image: alpine:3.16
+  interruptible: true
+  before_script:
+    - apk update && apk add bash curl jq
+  variables:
+    # Interface variables (to be overrided by derived jobs)
+    SUBMODULE_DIR: "$CI_PROJECT_DIR"
+    REGISTRY: $CI_REGISTRY_IMAGE
+    REGISTRY_USER: ""
+    REGISTRY_PASS: ""
+    IMAGE_PATH: ""
+    IMAGE_TAG: ""
+    SCRIPTS_PATH: "$SUBMODULE_DIR/scripts/bash"
+  script:
+    - echo "Attempting to cleanup an image $IMAGE_PATH using tag $IMAGE_TAG from $REGISTRY"
+    - "$SCRIPTS_PATH/delete-image.sh"
+
+  when: always
+
+.prepare_data_5m_image:
+  extends: .docker_image_builder_job
+  variables:
+    SUBMODULE_DIR: "$CI_PROJECT_DIR"
+    REGISTRY_USER: "$CI_IMG_BUILDER_USER"
+    REGISTRY_PASS: "$CI_IMG_BUILDER_PASSWORD"
+    SCRIPTS_PATH: "$SUBMODULE_DIR/scripts/bash"
+  artifacts:
+    reports:
+      dotenv: docker_image_name.env
+    paths:
+      - ./hived-mainnet-binaries/*
+    expire_in: 6 hours
+
+.prepare_hived_data_5m_image:
+  extends: .prepare_data_5m_image
+  script:
+    - $SCRIPTS_PATH/get_image4submodule.sh "$SUBMODULE_DIR" registry.gitlab.syncad.com/hive/hive/ "HIVED_IMAGE_NAME" "$REGISTRY_USER" "$REGISTRY_PASS" "hived-mainnet-binaries"
+    - ls -la ./hived-mainnet-binaries/*
+
+.prepare_haf_data_5m_image:
+  extends: .prepare_data_5m_image
+  script:
+    - $SCRIPTS_PATH/get_image4submodule.sh "$SUBMODULE_DIR" registry.gitlab.syncad.com/hive/haf/ "HAF_IMAGE_NAME" "$REGISTRY_USER" "$REGISTRY_PASS" "hived-mainnet-binaries"
-- 
GitLab