顯示具有 gitlabci 標籤的文章。 顯示所有文章
顯示具有 gitlabci 標籤的文章。 顯示所有文章

2022/07/03

Make use of free tier gitlab pages for hosting with openapi document & coverage report

1. Goal

In this blog, I am going to make use of gitlab pages for hosting my openapi documents & coverage reports.

TL;DR,

FYI, this is a follow up blog for my flask learning. Before this blog, I have written a blog for showing how to setup the vscode’s debugger from scratch. Make sure to check them out if they are helpful for your cases.

1.1 Contents overview

  • In section 2, I will explain how to build the openapi document in cicd
  • In section 3, I will explain how to build the coverage report in html in cicd
  • In section 4, I will explain how to wrap up everything, and upload to the gitlab pages
  • In bonus section, I will write down my advices on writing openapi.yaml from scratch

2. Build OpenAPI document in cicd

In this section, I assume you have a valid openapi.yaml at the first place. If you don’t, please read my advices in bonus section before writing this file from scratch. It may help you a bit.

General idea

  • Convert the yaml to html files
  • Upload the html files to gitlab pages
  • Do this only if I am updating master / tagging

In order to build the OpenAPI document in gitlab cicd, you need following yaml

...
stages:
  - build
  - test
  - buildPages
  - deploy
...
buildOpenapiPages:
  image: node:18-alpine
  stage: buildPages
  dependencies: []
  script:
    - wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v4.12.0.tar.gz -O swagger.tar.gz
    - tar xvf swagger.tar.gz
    - mkdir -p build/openapi/
    - cp -fr swagger*/dist/* build/openapi/
    - npm install @apidevtools/swagger-cli
    - ./node_modules/.bin/swagger-cli bundle -o build/openapi/openapi.json ./openapi.yaml
    - sed -i
      "s#https://petstore\.swagger\.io/v2/swagger\.json#${OPENAPI_JSON_FILE_URL}#g"
      build/openapi/swagger-initializer.js
  artifacts:
    untracked: false
    expire_in: 1 hour
    paths:
      - build/openapi/
  only:
    - main
    - tags

Before explaining script, I will explain rest of the fields first

  • I have defined a new stage buildPages for building the related pages
    • Ensure we build pages only if it passed the pipeline
  • I only upload build/openapi/ since I only need files there
    • untracked is suggested from the IDE. It does not really matter
    • Set expire_in to a relative short period since I don’t need them after the pipeline
  • Use only to ensure this task will only be run on main branch, or tags (tagging)
  • Set dependencies to empty array in order to speed up the pipeline process. Otherwise, it will download the artifacts in the test stage

In script, there are 2 things happening

  • Installing a standalone swagger version as suggested by the official guide
  • Convert openapi.yaml to openapi.json as required by the standalone swagger ui
    • By using @apidevtools/swagger-cli
    • That’s why I need image node:18-alpine. Version is not important as long as it can run the above tool

After the installation & conversion, I put everything under build/openapi for uploading as gitlab’s artifacts.

A side note on ${OPENAPI_JSON_FILE_URL}. Since the swagger ui need this file in order to render my APIs properly, I need to make sure the swagger ui can find this file in the runtime. So, I copy this json file next to the swagger ui folder. Then, it will shares the same gitlab pages url with swagger ui.

3. Build coverage report in cicd

Back in 2017, my old blog described how to do that in general. So, in 2022, I will just modified a bit from my old works.
The yaml snippet required in this section.

runTests:
  ....
      - coverage html -d build/coverage
  ...
  artifacts:
   ...
    untracked: false
    expire_in: 1 hour
    paths:
      - build/coverage/
  • For artifacts, it is similar to section 2. But, I need build/coverage/ this time
  • I generate the coverage report by using coverage html -d build/coverage
  • A side note one the stage.
    • I generate the document at the end of task in test stage instead of creating a buildCoverageReport task.
    • This can save me some pipeline time for rerunning the coverage again.

That’s it.

4. Upload to gitlab pages

Finally, I need to copy all artifacts from previous stages to public/ in a specific pages task.

pages:
  stage: deploy
  image: alpine:3.16
  variables:
    GIT_STRATEGY: none
  script:
    - mkdir -p public
    - cp -r build/* public/
  artifacts:
    untracked: false
    expire_in: 1 hour
    paths:
      - public
  dependencies:
    - runTests
    - buildOpenapiPages
  only:
    - main
    - tags
  • Set dependencies explicitly. Personal habit. It inherits all artifacts from previous stages by default
  • Set GIT_STRATEGY to none for speeding up the pipeline process since I just need artifacts and nothing else
  • Rest of the keys are explained in previous stages

That’s it. After the pipeline’s run, I will have 2 different documentations under public/ that will hosted by gitlab pages

  • public/coverage/
  • public/openapi/

Check out the links in section 1 for the demo.

A side note on writing gitlab pages. Old gitlab pages will be erased whenever you publish new gitlab pages. So, please do not assume it will keep your stuff forever.

5. Bonus Section advices on writing openapi.yaml

5.1 Get an IDE

Personally, I am using vscode with extension 42Crunch.vscode-openapi. Features like linting, code hinting, and previewing with style are really important for writing documents (Or, codes). You don’t need to follow my IDE setup but I strongly recommend you to get an IDE that support above features. It will save you many time for debugging your syntax etc.

At least, you can use the online editor from swagger

5.2 Essential websites for openapi reference

IMO, there are no quick ways for learning openapi’s writing. It really takes time for studying openapi specifications. Otherwise, you cannot just really write something you want.

Personally, I will suggest you to go through their basic openapi guide first. It provide certain common snippets for you to start with.

Then, after you gathering certain set of snippets, I suggest you to start reading the schema section in openapi specification. As the meaning of the specification, it describes every bits in your snippets clearly.

Finally, you will behave just like me. You will keep jumping between schema & guide.

  • In schema, you will have a general idea about what fields you need
  • Go to guide, you will probably get some examples for your idea
  • Back to schema, try to tweak from the examples by understanding the schema throughly
  • Loop until you completed the yaml

Of cause, IDE helps you a lot in this process. For example, you can read what your changes IMMEDIATELY.

That’s it. I wish you can complete this yaml file soon. In my case, I spent couple hours lol…

References

​

2021/12/13

Learning Flask 1: Bootstrap with flask

Background

This is a follow up blog post of previous NETCONF blog. Below diagram recalls the application I am going to build.

In the last blog post, I have built a server for running netconfd effectively. In this blog post, I will focus on building the CoreServer (Frontend layer) with flask.
By the way, the full source code of this application is here

Why flask?

I do not have much experiences on python flaks. Actually, I am more familiar with Django instead. Django, however, is not fit in this application since it is sort of overkill in my requirement. I need something small, and easy to code at the first place.
After some research from this website, I pick flask from the list. By the way, Django is classified as full-stack framework while flask is simply a micro framework in this site.

Start the application with a boilerplate

Nowadays, as long as you are using well-known frameworks / libraries etc, usually, there are multiple open sources boilerplates for your framework / libraries. Then, you can save much efforts on building the ground.
Personally, I have picked this boilerplate for my application. This boilerplate provides the docker image, the docker-compose file, the folder structure.

The usage of docker image + docker-compose

They are essential for me to build the application in a docker manner, and they save my time on building the CI/CD pipeline easily

The folder structure

It saves my time for figuring out how to organise files in flaks manner.

Setup CI / CD pipeline

I strongly recommend readers to setup a CI / CD pipeline asap especially on a new project. After having a CI / CD pipeline, code’s quality is kind of guaranteed. For example, coding style, some basic tests etc

  • Below is the yml file for running a CI / CD pipeline in gitlab CI.
# You can override the included template(s) by including variable overrides
# SAST customization: https://docs.gitlab.com/ee/user/application_security/sast/#customizing-the-sast-settings
# Secret Detection customization: https://docs.gitlab.com/ee/user/application_security/secret_detection/#customizing-settings
# Dependency Scanning customization: https://docs.gitlab.com/ee/user/application_security/dependency_scanning/#customizing-the-dependency-scanning-settings
# Note that environment variables can be set in several places
# See https://docs.gitlab.com/ee/ci/variables/#cicd-variable-precedence
include:
  - template: Security/SAST.gitlab-ci.yml

stages:
  - build
  - test

variables:
  PIPELINE_REGISTRY_DOCKER_IMAGE: "${CI_REGISTRY_IMAGE}:pipeline"
  PIPELINE_RUNTIME_DOCKER_IMAGE: "hands-on-core-server:latest"
  DOCKER_COMPOSE_CI_YML_FILE_NAME: "docker-compose-ci.yml"

buildDockerImage:
  image: docker
  services:
      - docker:dind
  stage: build
  variables:
    DOCKER_BUILDKIT: 0
  script:
      - apk add --no-cache docker-compose
      - docker login -u "gitlab-ci-token" -p "$CI_JOB_TOKEN" "$CI_REGISTRY"
      - docker-compose -f "docker/${DOCKER_COMPOSE_CI_YML_FILE_NAME}" build CoreServer
      - docker tag "${PIPELINE_RUNTIME_DOCKER_IMAGE}" "${PIPELINE_REGISTRY_DOCKER_IMAGE}"
      - docker push "${PIPELINE_REGISTRY_DOCKER_IMAGE}"

sast:
  stage: test

runTests:
  image: ${PIPELINE_REGISTRY_DOCKER_IMAGE}
  stage: test
  script:
      - flake8
  • The sast task is provided by gitlab. Just ignore it
  • Pipeline’s contents are trivial. Literally,
    • I compose a docker image which holding all my boilerplates, and dependencies.
    • I setup a stage runTests which runs with the docker image above, and run lint check with flake8 only at this moment
  • Below is the Dockerfile for ci
FROM tiangolo/uwsgi-nginx-flask:python3.8

WORKDIR /workspace
COPY . /workspace

RUN \
    pip install -r requirements-test.txt && \
    pip install -r requirements.txt

Conclusions

Now, I have a good ground to build up my application in flask. There is a CI-CD pipeline to make sure my codes will be in good qualities in some sense. There is a flask-style folder structure for me to organise my codes.
The next step of the development will be writing some trivial tests, and make sure the pipeline will run them on each commit. They will be covered in the next blog

Useful links

​

2017/05/30

Unit test on python: Coverage report with gitlab ci

About

First, even test has 100% coverage, it does not mean no bugs. However, 100% coverage sounds compelling and reliable than those does not.
This is an article about how to generate coverage reports after testing and hosted them in gitlab

Prerequisites

Which project to work on

As this article follows my another blog, we reuse this project.

Gitlab CI

In case you have no idea about what is Gitlab CI. Please read documentation here for an introduction.

Write yml

Template

There are many templates from Gitlab. I pick this one.

YML

Image

This statement has two outcomes
  • Define we need to run in docker
  • Define which docker image we need
In our case, we need python:2.7 as pip and python are installed
image: python:2.7

Stages

Although 1 stage is sufficient in our case, let us define 2 stages for demonstration purpose.
Execute order: test -> deploy
stages:
- test
- deploy

Jobs

Define a global setup script for all jobs.

before_script:
    - pip install -r requirements.txt
Install dependencies before running any tests.

Define a job runTest which stop running unit tests as soon as possible if there are failures.

runTest:
    stage: test
    script:
        - nosetests -sx

Define a job coverage which generates a coverage report.

coverage:
    stage: test
    script:
        - nosetests -c .noserc -q --cover-html-dir=build --cover-html
        - coverage report -m
    coverage: '/TOTAL.+ ([0-9]{1,3}%)/'
    artifacts:
        paths:
            - build
        expire_in: 1 day
Notes:
  • Jobs in the same stage run in parallel. In order word, failure job cannot stop rest of the jobs at the same stage.
  • artifacts allows us to save reports for other jobs later on
  • As reports here are temporary, expire_in make sure they will be deleted.
  • coverage defines which number means coverage and such number will be presented in the README.md
  • For example, below are shell output when running commands for coverage.
$ nosetests -c .noserc -q --cover-html-dir=build --cover-html
.....
$ coverage report -m
Name                   Stmts   Miss Branch BrPart  Cover   Missing
------------------------------------------------------------------
tests\test_person.py      16      0      0      0   100%
use_mock\person.py         9      0      0      0   100%
------------------------------------------------------------------
TOTAL                     25      0      0      0   100%

Define a job apidoc which generate API doc for this module

apidoc:
    stage: test
    script:
        - cd docs
        - fab make
    artifacts:
        paths:
            - docs/build/html
        expire_in: 1 day

Define a job pages which generate gitlab page

pages:
    stage: deploy
    before_script:
        - "true"
    script:
        - mkdir -p public/coverage
        - cp -fr docs/build/html/* public/
        - cp -fr build/* public/coverage/
    dependencies:
        - coverage
        - apidoc
    artifacts:
        paths:
            - public
Notes
  • Belongs to deploy stage instead of test
  • pages is a keyword for Gitlab Page
  • Files under public are all Gitlab Pages. So, we move reports and docs there.
  • dependencies defines we need artifacts from those jobs.
  • before_script overrides the global one. It means do nothing here.
  • artifacts here saves pages for gitlab server

Debug

  • Syntax error
There is an official tool for linting your yml file.
  • Run time error
You must read logs from the runner’s report and find out what’s going on.
In our case, we can run a docker container with image docker:2.7 and try commands defined one by one and see whether there are any errors in local environment.

Product

  • For apidoc, click here.
  • For coverage, click here.
  • For badges in README.md, click here

References

​