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

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

​

2020/08/08

Gitlab + letsencrypt + Private network

Requirements

This blog requires you to have following items:
  • Gitlab server
  • TLS from let’s encrypt
  • Private network, which outside world cannot reach directly
  • You own a public domain name
If your gitlab server is reachable from outside world, you can reference manual here for setup let’s encrypt.
For poor souls like me, stay tune, and keep reading.

What is let’s encrypt

For detail, please read their website yourself. To me, it is a service for me to have a valid TLS certificate but free of charge.

Gitlab server + letsencrypt

According to my experiments, till Gitlab 12.9.2, Gitlab does not support requesting certificate via DNS challenge. So, you can just disable the let’s encrypt configuration provided by gitlab if your gitlab server is not public at all.
Surprisingly, we can still benefits from let’s encrypt since it will still offer you a TLS certificate, and private key, even though you need to do the verification every 3 months.
In other words, once you have certificate, and private key, you should configure your gitlab to read them as if you are using traditional TLS certificate, which bought from some vendors.

Request certificate from letsencrypt via certbot

Firstly, you should get a certbot by following let’s encrypt manual here in your gitlab server host.
Then, you can run following command to request a certificate from letsencrypt with DNS challenge for verifications.
certbot -d YOUR_GITLAB_SERVER_DOMAIN_NAME --manual --preferred-challenges dns certonly
Follow instructions there, you will finally have a DNS challenge string. Setup a TXT record with that DNS challenge string in your public DNS.
Below is a picture I capture from Google to illustrate the txt record setup.
Once you have complete the DNS challenge, you should get a certificate, and private key as stated in the command output. Personally, I suggest you to write down those important notes generated into a file for future reference.

Configure gitlab server to read certificate from gitlab server

By default, you should have following default configurations in /etc/gitlab/gitlab.rb
# nginx['ssl_certificate'] = "/etc/gitlab/ssl/#{node['fqdn']}.crt"
# nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/#{node['fqdn']}.key"
You can overwrite them with value you like. For me, I just stick to the default configuration. Therefore, I copy the certificate, and private key to the destination above.
It is worth to point out that you should name your certificate as YOUR_DOMAIN_NAME.crt, and private key as YOUR_DOMAIN_NAME.key if your are using default configuration like mine.
Finally, you can restart your gitlab server, and checkout your new certificate by reading them in your browser.
​

2018/11/25

A stupid way to semi automate steps for creating Merge Request on gitlab

Hello all. I have been away for writing a blog a while. Today, I would like to share how I semi automate steps for creating a MR on gitlab via command line.

Show me source codes

This is simply a script for filling information, for regular MR contents, and open a browser, which is a GUI for me to verify the contents, to fire MR. It, however, saves my time for filling boring and redundant MR contents. Here we go.

import subprocess

# Where is your project: NAMESPACE/REPO_NAME
MR_URL_ARGVS = {
    'NAMESPACE': 'mondwan',
    'REPO_NAME': 'scripts_for_creating_gitlab_mr',
}

# What will be the arguments for the MR URL
MR_SETTINGS = {
    # 'source_branch': 'feature_branch_1',
    'target_branch': 'master',
    # 'force_remove_source_branch': 'true',
    'title': 'New%20MR',
    # User ID in the gitlab
    'assignee_id': '1158561',
}

# The base url
MR_URL_BASE = \
    'https://gitlab.com/{NAMESPACE}/{REPO_NAME}/merge_requests/new?'.format(
        **MR_URL_ARGVS
    )

# Fill up source branch by current branch name via system git command
currentBranchName = subprocess.check_output(
    'git rev-parse --abbrev-ref HEAD'.split(' ')
).strip('\n')
MR_SETTINGS['source_branch'] = currentBranchName

# Create params list for the MR which will be pasted at the END of URL
getParams = '&'.join([
    'merge_request%%5B%s%%5D=%s' % (k, v) for k, v in MR_SETTINGS.items()
])

# The final url
url = MR_URL_BASE + getParams

# Launch a browser for given url with command line in ubuntu
print 'gnome-open "%s"' % url
Below explain how it works part by part.

How it works

If you studied carefully, gitlab accept a hand made URL for creating Merge request.
We can prefill whatever information in that MR if we can craft a specific URL.
Below is how to craft the first part of the URL, where variables are the namespace and repository name.

# Where is your project: NAMESPACE/REPO_NAME
MR_URL_ARGVS = {
    'NAMESPACE': 'mondwan',
    'REPO_NAME': 'scripts_for_creating_gitlab_mr',
}

# The base url
MR_URL_BASE = \
    'https://gitlab.com/{NAMESPACE}/{REPO_NAME}/merge_requests/new?'.format(
        **MR_URL_ARGVS
    )
The next question is how can I fill text into a field like title, contents, or source branch. Get Params is the answer.
For example, if you append string merge_request%5Btitle%5D=New%20MR at the end of the URL, title of that page will be New MR.
Below shows how to create a MR where title is New MR, assigned to an user with id 1158561, and set master to be the target branch

# What will be the arguments for the MR URL
MR_SETTINGS = {
    # 'source_branch': 'feature_branch_1',
    'target_branch': 'master',
    # 'force_remove_source_branch': 'true',
    'title': 'New%20MR',
    # User ID in the gitlab
    'assignee_id': '1158561',
}



# Create params list for the MR which will be pasted at the END of URL
getParams = '&'.join([
    'merge_request%%5B%s%%5D=%s' % (k, v) for k, v in MR_SETTINGS.items()
])
You may wonder how can I know what should be the key in order to fill up a field. The answer is looking them up via your browser’s console. For example, I would like to look up the key of source branch. I will see something like that in the console after watching the corresponding DOM element from the HTML.
As you can see in the diagram, we can locate merge_request[source_branch] in the HTML. That’s the key (source_branch) we need.
For me, it will be convenient if my script is able to fetch the name of current branch and put that in to the source branch field.

# Fill up source branch by current branch name via system git command
currentBranchName = subprocess.check_output(
    'git rev-parse --abbrev-ref HEAD'.split(' ')
).strip('\n')
MR_SETTINGS['source_branch'] = currentBranchName
Finally, I would like to launch a browser through command line by using gnome-open

 # The final url
url = MR_URL_BASE + getParams

# Launch a browser for given url with command line in ubuntu
print 'gnome-open "%s"' % url
Then, I can copy and paste that URL into the command line. A browser, for me it is Firefox, will be jumped out eventually in Ubuntu.

The repository for this script

Alternative

For advance developers, you may try to automate the entire process by using official APIs. For python developers, you can try to code them up with this cli library.
Although I have not tried to code this alternative, I guess this is much more time consuming than my approach, in term of time spent on development, listed above. One thing, however, I can sure is that this alternative is much more efficient than my approach.

Change logs

20181125: Add alternative section, refine some of the wordings
​

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

​