WireMock + Recorder : mocker une API existante

Aperçu

WireMock est un outil formidable ❤ qui permet de mocker une API REST, ou tout autre service Web.

D’autres fonctionnalités bien utiles sont fournies, comme l’enregistrement du comportement d’une API à partir d’un serveur réel.

Recorder

Pour cela il va falloir utiliser le recorder fourni par WireMock. La procédure est décrite à cette page : Record and Playback.

Au préalable il faudra démarrer un serveur WireMock, en mode standalone par exemple. Supposons que le serveur tourne sur le port 8080.

Il faut ensuite se rendre à la page http://localhost:8080/__admin/recorder .

Puis on va renseigner l’URL de l’API qu’on veut mocker. Prenons par exemple l’API Star Wars : https://swapi.dev/ .

On saisit donc l’URL de l’API : https://swapi.dev/api/ . Et on clique sur « Record ».

Ensuite on va se servir de ce serveur comme d’un proxy, et il va enregistrer les requêtes et les réponses dans des fichiers locaux, pour pouvoir ensuite les reproduire sans être connecté au serveur d’origine.

Les différents endpoints utilisables de cette API sont répertoriés dans la documentation : https://swapi.dev/documentation#start.

Donc au lieu d’accéder à cette URL :

On va passer par le serveur WireMock avec :

Si on utilise curl, on lancera donc la commande :

$ curl -i -s -X GET http://localhost:8080/people/1/

HTTP/2 200
server: nginx/1.16.1
date: Fri, 03 Feb 2023 21:00:12 GMT
content-type: application/json
vary: Accept, Cookie
x-frame-options: SAMEORIGIN
etag: "ee398610435c328f4d0a4e1b0d2f7bbc"
allow: GET, HEAD, OPTIONS
strict-transport-security: max-age=15768000

{"name":"Luke Skywalker","height":"172","mass":"77","hair_color":"blond","skin_color":"fair","eye_color":"blue","birth_year":"19BBY","gender":"male","homeworld":"https://swapi.dev/api/planets/1/","films":["https://swapi.dev/api/films/1/","https://swapi.dev/api/films/2/","https://swapi.dev/api/films/3/","https://swapi.dev/api/films/6/"],"species":[],"vehicles":["https://swapi.dev/api/vehicles/14/","https://swapi.dev/api/vehicles/30/"],"starships":["https://swapi.dev/api/starships/12/","https://swapi.dev/api/starships/22/"],"created":"2014-12-09T13:50:51.644000Z","edited":"2014-12-20T21:17:56.891000Z","url":"https://swapi.dev/api/people/1/"}

Vous pouvez en profiter pour tester d’autres URL pour enregistrer davantage de mappings, comme :

Quand vous avez terminé, cliquez sur « Stop ».

Des fichiers JSON ont été créés dans le répertoire mappings. On peut les retrouver à cette URL : http://localhost:8080/__admin/mappings .

Le premier mapping va donc générer un fichier mappings/people_1-989db380-8a58-4c35-a8d6-ac709f14b773.json, avec le contenu :

{
  "id" : "989db380-8a58-4c35-a8d6-ac709f14b773",
  "name" : "people_1",
  "request" : {
    "url" : "/people/1/",
    "method" : "GET"
  },
  "response" : {
    "status" : 200,
    "body" : "{\"name\":\"Luke Skywalker\",\"height\":\"172\",\"mass\":\"77\",\"hair_color\":\"blond\",\"skin_color\":\"fair\",\"eye_color\":\"blue\",\"birth_year\":\"19BBY\",\"gender\":\"male\",\"homeworld\":\"https://swapi.dev/api/planets/1/\",\"films\":[\"https://swapi.dev/api/films/1/\",\"https://swapi.dev/api/films/2/\",\"https://swapi.dev/api/films/3/\",\"https://swapi.dev/api/films/6/\"],\"species\":[],\"vehicles\":[\"https://swapi.dev/api/vehicles/14/\",\"https://swapi.dev/api/vehicles/30/\"],\"starships\":[\"https://swapi.dev/api/starships/12/\",\"https://swapi.dev/api/starships/22/\"],\"created\":\"2014-12-09T13:50:51.644000Z\",\"edited\":\"2014-12-20T21:17:56.891000Z\",\"url\":\"https://swapi.dev/api/people/1/\"}",
    "headers" : {
      "Server" : "nginx/1.16.1",
      "Date" : "Fri, 03 Feb 2023 21:25:47 GMT",
      "Content-Type" : "application/json",
      "Vary" : "Accept, Cookie",
      "X-Frame-Options" : "SAMEORIGIN",
      "ETag" : "\"ee398610435c328f4d0a4e1b0d2f7bbc\"",
      "Allow" : "GET, HEAD, OPTIONS",
      "Strict-Transport-Security" : "max-age=15768000"
    }
  },
  "uuid" : "989db380-8a58-4c35-a8d6-ac709f14b773",
  "persistent" : true,
  "insertionIndex" : 7
}

Et voilà, à chaque fois qu’on exécutera la requête GET sur http://localhost:8080/people/1/, le serveur WireMock répondra avec la réponse HTTP enregistrée comme ci-dessus.

Using iconv under Windows 10 thanks to Docker

Iconv

Iconv is a command-line program, provided on Unix and Unix-like systems, used to convert text files between different character encodings (https://en.wikipedia.org/wiki/Iconv).
For example, we can convert a file from ISO-8859-1 to UTF-8, with this command :
iconv -f iso-8859-1 -t utf-8 <infile> -o <outfile>
Sometimes we would like to use iconv to convert the encoding of some text files, but it’s not natively available for Windows.

Batch processing with iconv

However iconv can only convert one file at a time.
So if we need to convert a whole set of files, we’ll need to use batch processing.
Let’s say we want to convert Java sources (*.java) in the src directory, from ISO-8859-1 to UTF-8, and overwrite the original files, we could try this :
find ./src -name "*.java" -type f -exec iconv -f iso88591 -t utf8 -o "{}" "{}" \;

Docker

Now, let’s suppose we don’t have any virtual machine with Linux installed, nor any installation of WSL with Windows… That’s where Docker can be useful, by providing images where iconv is already embedded. This is the case with images like debian or ubuntu.
First let’s verify that iconv is present in a given Docker image :
docker run --rm debian:11 which iconv
Or
docker run --rm ubuntu:20.04 which iconv
It should be located at /usr/bin/iconv.

If iconv is present, no need to build our custom image and install iconv with apt.

The final step

The directory containing the sources that we want to convert will have to be bind mounted to be accessible by our container. We’ll use Docker volumes for that.
Here is how we can do that, assuming the sources we want to convert are located in the src directory :

docker run --rm -v $(pwd):/code debian:11 find /code/src -name "*.java" -type f -exec iconv -f iso88591 -t utf8 -o "{}" "{}" \;

Note

If you can’t use the pwd command because you don’t use a Unix-like terminal, please read this article : Sharing files between host and container in Docker Desktop for Windows.

But it may fail… 😬

Oh yes, if you try to overwrite the original file with iconv, it may fail ! So it’s not always a good idea…

In fact if you see the following error with the batch conversion (using find -exec) :

iconv terminated by signal 7

or if using iconv on a single file you have the following error (with exit code = 135) :

Bus error

Then it can occur because the input file is greater than 32 KB, indeed iconv uses a buffer (32 KB I guess) when reading the original file. If the buffer is full, the input file still open, and it tries to write to the same file, it will fail. So it may be a better strategy to write converted files to another location.

So here is a better way to make it work :

for file in $(find . -name "*.java")
do
    iconv -f iso88591 -t utf8 -o "$file.utf8" "$file" &&
    mv -f "$file.utf8" "$file"
done

References

Bonus

You can try to detect the type and encoding of a file with the Unix command file. It can display the charset used for a text file.

Alternative without Docker : Git Bash

If you don’t have Docker installed, but you installed Git for Windows, you can use Git Bash.

It contains basic Unix tools like find, file, and above all iconv 🤩 !

Sharing files between host and container in Docker Desktop for Windows

Sharing files or directories with Docker is relatively simple on Linux, when you look at the Docker documentation : https://docs.docker.com/storage/volumes/ .

When you want to share a local directory on your host file system with a container, you just have to run something like (example) :

$ docker run --rm -it -v $(pwd)/localdir/:/app/ ubuntu bash

Doing the same in Windows 10

Doing the same in Windows 10 can be a little bit tricky.

You can find some people who tried hard to make it work, like there in the forums :

Using WSL2

If using WSL2, you may have a base path in the Ubuntu terminal like « /mnt/c/Users/me ».
Considering that you have a local directory named « test/ », you can bind mount this directory into your container doing :

$ docker run --rm -it -v /mnt/c/Users/me/test:/test ubuntu bash

You can check that the contents of the directory is what you expect by doing :

# ls /test/

You can check also check that the directory is mounted. The mount type will be « 9p » in that case.

# mount -t 9p

Note

You can however simply use the pwd command if using a linux terminal, which will resolve to an absolute path. You just need to be located in your working directory.

Using Hyper-V

If using Hyper-V, you can make it with the same directory « test/ » like :

$ docker run --rm -it -v //c/Users/me/test:/test ubuntu bash

Then check it :

# ls /test/

References

Créer une VM Linux dans Windows 10 Pro avec Hyper-V, le tout automatisé avec Vagrant

Objectif

On souhaite créer une VM Linux sous Windows 10 Pro. On va donc passer directement par l’outil Hyper-V (fourni avec Windows 10 Pro), et installer une VM Ubuntu par exemple. Mais cela impose pas mal de taches manuelles interactives, donc on va essayer de l’automatiser.

Pour cela on va utiliser un outil d’Infrastructure as Code, en l’occurrence Vagrant. D’autres existent comme Terraform, Ansible, Chef, Puppet…

Pourquoi Hyper-V ? En effet parfois on n’a pas la possibilité d’utiliser WSL 2 par exemple, ou ce dernier ne répond pas au besoin. Si on ne dispose pas de Windows 10 Pro et Hyper-V, on pourrait aussi simplement utiliser VirtualBox, compatible avec Vagrant.

Pour information, Vagrant est plutôt destiné à des environnement hors production, comme pour du développement ou des tests.

Installer Vagrant

Tout d’abord il faudra installer Vagrant pour votre OS, et en l’occurrence, pour Windows dans notre cas.

Activer Hyper-V

Bien sûr il faut s’assurer que Hyper-V est activé dans Windows. On pourra utiliser la commande suivante avec PowerShell :

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

Sinon on peut aussi l’activer via le menu Programmes et fonctionnalités, comme suit :

Fichier Vagrantfile

Le fichier Vagrantfile va permettre de décrire en lignes de code la machine que l’on veut créer, en essayant de garder une certaine portabilité entre les différentes plateformes.

On trouvera notamment le paramètre config.vm.box, indiquant à partir de quelle box ou image on veut créer notre VM. Un catalogue de box est disponible ici : https://app.vagrantup.com/boxes/search.

Dans notre cas, on va choisir generic/ubuntu2004, qui est compatible Hyper-V.

Exemple de script Vagrantfile :

# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://vagrantcloud.com/search.
#config.vm.box = "base"
#config.vm.box = "generic/debian10"
#config.vm.box = "hashicorp/bionic64"
config.vm.box = "generic/ubuntu2004"
# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
# config.vm.box_check_update = false
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# NOTE: This will enable public access to the opened port
# config.vm.network "forwarded_port", guest: 80, host: 8080
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine and only allow access
# via 127.0.0.1 to disable public access
# config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
# Create a private network, which allows host-only access to the machine
# using a specific IP.
# config.vm.network "private_network", ip: "192.168.33.10"
# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
# your network.
# config.vm.network "public_network"
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"
config.vm.synced_folder "../data-test", "/vagrant_data"
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
# View the documentation for the provider you are using for more
# information on available options.
# https://www.vagrantup.com/docs/providers/hyperv
config.vm.provider "hyperv" do |hv|
hv.cpus = "2"
hv.memory = "2048"
hv.enable_enhanced_session_mode = true
end
# https://www.vagrantup.com/docs/providers/virtualbox
config.vm.provider "virtualbox" do |vb|
vb.cpus = "2"
vb.memory = "2048"
end
# Enable provisioning with a shell script. Additional provisioners such as
# Ansible, Chef, Docker, Puppet and Salt are also available. Please see the
# documentation for more information about their specific syntax and use.
config.vm.provision "shell", inline: <<-SHELL
add-apt-repository ppa:git-core/ppa -y
apt-get update
apt-get install -y git git-svn svn2git
SHELL
end
view raw Vagrantfile hosted with ❤ by GitHub

Partage de fichiers

Cela pourra être pratique de mettre en place un partage de fichier entre l’hôte et la VM invitée, bien que ce ne soit pas obligatoire. C’est l’objet de la propriété :

config.vm.synced_folder "../data-test", "/vagrant_data"

Dans ce cas il faudra s’authentifier pour mettre en place le partage SMB.

Une fois dans la VM, on pourra voir ce dossier partagé dans la liste des mounts, et accéder au chemin /vagrant_data.

Exécution du script

On va maintenant demander à Vagrant de créer une VM correspondant au Vagrantfile. Pour ce faire, se placer dans le répertoire contenant le fichier Vagrantfile et lancer :

vagrant up --provider hyperv

Attention, si on ne spécifie pas le provider, par défaut Vagrant va essayer de créer une VM avec VirtualBox. Voir : https://www.vagrantup.com/docs/providers/default.

Lister les box Vagrant

Si la VM a bien été créée, une box a normalement été téléchargée. On peut vérifier çà avec cette commande :

vagrant box list

Vérification

On peut vérifier le statut de la VM (running si tout va bien) avec la commande suivante :

vagrant status

Il existe une commande globale pour lister toutes les VMs, que l’on peut exécuter de n’importe quel endroit :

vagrant global-status

Accéder à la VM

Il est maintenant possible d’accéder à la VM via SSH. Vous pouvez par exemple utiliser PuTTY. Vagrant propose aussi une commande pour cela :

vagrant ssh

A la création de la VM, Vagrant a créé une configuration SSH. On peut consulter ces infos (adresse IP, username, clé privée) avec la commande :

vagrant ssh-config

Arrêter la VM

On peut suspendre la VM avec la commande :

vagrant suspend

Détruire la VM

Si vous n’en avez plus besoin, vous pouvez aussi supprimer une VM :

vagrant destroy

Besoin de configurer un proxy ?

Allez voir cette réponse à la question How to use vagrant in a proxy environment?

C’est le plugin vagrant-proxyconf qui sera utilisé dans ce cas, et qui devra auparavant avoir été installé comme suit :

vagrant plugin install vagrant-proxyconf

Il faudra simplement penser à définir les variables d’environnement VAGRANT_HTTP_PROXY, VAGRANT_HTTPS_PROXY, voire VAGRANT_NO_PROXY. Comme précisé dans la réponse plus haut, les variables http_proxy et https_proxy sont nécessaires pour pouvoir télécharger la box sur internet.

La bonne nouvelle c’est que ce plugin permet non seulement de télécharger la box Vagrant nécessaire pour initialiser la VM, mais aussi de configurer le proxy de différents programmes.

Par exemple pour Apt c’est ce plugin qui va configurer le fichier /etc/apt/apt.conf.d/01proxy. Donc plus besoin de suivre cette manip : Configure proxy for APT.

Références externes

GitLab CI : utiliser son propre Runner dédié à Maven avec des settings personnalisés

Contexte

GitLab est un serveur d’hébergement de code source (SCM) dédié à Git. GitLab peut être utilisé avec une instance publique sur Internet (https://gitlab.com/), de façon similaire à GitHub (https://github.com/), ou bien avec une instance hébergée chez soi ou dans une entreprise (on premise).

GitLab intègre une partie « Intégration Continue », connue sous le nom de GitLab CI. Cela permet de vérifier que le logiciel peut être construit correctement, éventuellement d’exécuter des tests unitaires, voire de publier le logiciel. Et bien d’autres choses encore.

La particularité de GitLab CI est de déléguer l’exécution du pipeline d’intégration continue, découpé en tâches (nommées jobs), à d’autres machines, appelées Runners. Ces runners peuvent être mis à disposition d’une instance GitLab via des shared runners, mais on peut également dédier des runners spécifiques à son projet ou son groupe de projets.

On peut ainsi exécuter des runners sur sa propre machine, en installant des GitLab Runners, que l’on soit sous Windows, Mac, Linux, ou même avec une infrastructure plus complexe comme Kubernetes.

Cas d’utilisation

L’objectif ici est de permettre de construire un projet Java dans GitLab CI, à l’aide de Maven.

Bien souvent en entreprise on va aussi utiliser notre propre dépôt (repository) de librairies Java compatible avec Maven notamment. Cela permet à la fois de servir de cache et de proxy pour tous les développeurs qui auraient besoin d’accéder à des librairies externes, disponibles sur Internet. Cela va également permettre d’héberger nos propres librairies ou artefacts, sur un serveur privé. Pour ce faire, on peut par exemple utiliser Sonatype Nexus. Il existe aussi d’autres solutions, comme Artifactory.

Pour faciliter les choses, on souhaite également utiliser Docker, une solution à base de containers.

L’enjeu sera essentiellement ici de pouvoir exécuter les tâches Maven dans GitLab CI, en configurant le settings.xml de Maven afin d’utiliser un repository Nexus interne.

L’exécution de Maven se fera dans chaque job à l’aide d’un executor défini dans le GitLab Runner et configuré pour utiliser Docker. Ainsi, chaque exécution de job consistera à instancier un container Docker et exécuter un script à l’intérieur. On tentera donc au maximum d’utiliser les images Maven officielles présentes sur Docker Hub pour cela. Un des avantages de Docker est notamment d’éviter l’installation de toute une série d’outils sur la machine hôte, comme un JDK et une version de Maven dans ce cas. Ces derniers sont simplement packagés dans l’image Docker correspondante, en isolation de la machine hôte.

Environnement

Dans cet article on va considérer que l’on travaille sur une machine Linux. C’est possible de le faire fonctionner sous Windows, mais cela rajoute quelques contraintes, et le cas de Linux est sûrement plus pertinent en production.

Installation du runner

Si ce n’est déjà fait, il faut installer le GitLab Runner qui fonctionnera comme un service.
Globalement on va suivre la procédure expliquée à cette page : https://docs.gitlab.com/runner/install/linux-manually.html. Pour Ubuntu / Debian on aura donc un package nommé gitlab-runner_x86_64.deb, à installer avec la commande dpkg.
Il est aussi possible de télécharger le binaire pour d’autres architectures comme expliqué dans le lien plus haut.

Pour vérifier que le service est actif, exécuter au choix :

  • sudo gitlab-runner status
  • service gitlab-runner status

Si le service n’est pas démarré, exécuter :

  • sudo gitlab-runner start

Configuration du runner

Pour configurer le runner, on va en général utiliser le fichier config.toml. Voir : https://docs.gitlab.com/runner/configuration/.
Par exemple le paramètre concurrent va définir le nombre de jobs exécutés simultanément.

Enregistrement des runners

Ensuite, un ou plusieurs runners peuvent être enregistrés. Dans notre cas, on utilisera les runners spécifiques à un projet. Il faudra au préalable aller dans le projet GitLab dans la section Settings > CI/CD et ouvrir Runners pour récupérer l’URL et le token.
Par exemple, on va enregistrer un runner spécifique aux jobs Maven.

sudo gitlab-runner register \
  --non-interactive \
  --url "https://gitlab.com/" \
  --registration-token "PROJECT_REGISTRATION_TOKEN" \
  --executor "docker" \
  --docker-image maven:latest \
  --description "Runner Maven" \
  --tag-list "maven" \
  --run-untagged="false" \
  --locked="false" \
  --access-level="not_protected"

La valeur de registration-token doit être valorisée avec la valeur du token du projet.

On veut aussi restreindre les images Docker utilisables dans ce runner. On va donc rajouter

--allowed_images="maven:*"

pour n’utiliser que des images Docker Maven officielles.

Lister les runners enregistrés

sudo gitlab-runner list

La liste des runners configurés doit s’afficher.

Tester l’exécution du pipeline dans le runner

Normalement à ce stade le runner est enregistré et prêt à exécuter des jobs du projet. Si un fichier .gitlab-ci.yml a déjà été ajouté aux sources du projet, vous pouvez tester la bonne exécution du pipeline en rajoutant un commit dans le projet ou en forçant son exécution.

Comme on a associé un tag à notre runner, il ne faut pas oublier de le spécifier dans la déclaration du job, comme par exemple :

build:
  stage: build
  image: maven:3.6-jdk-8
  script:
    - mvn $MAVEN_CLI_OPTS verify
  tags:
    - maven

Problème de proxy ?

Bon si vous êtes derrière un proxy, il est probable de rencontrer des problèmes. Il faudra peut-être regarder ici : Running GitLab Runner behind a proxy.

Utilisation d’un registry Docker privé ?

Il est aussi possible que vous deviez passer par un registry Docker privé pour le téléchargement des images Docker. Dans ce cas GitLab Runner devra être configuré en conséquence, voir Using a private container registry. On pourra également restreindre l’origine des images autorisées (allowed_images) à un registry privé.

Voir les détails spécifiques à Docker dans Define an image from a private Container Registry et en particulier la définition de la variable DOCKER_AUTH_CONFIG (credentials + registry).

Concernant la configuration spécifique à Docker pour l’utilisation d’un registry privé en mode proxy, voir Registry as a pull through cache.

Voir aussi ces issues :

Etape suivante : utiliser un repository Maven privé

Ensuite nous souhaitons que notre job, exécuté dans un container Docker avec une image Maven utilise un repository Maven spécifique.

Avant tout, on va démarrer un serveur Sonatype Nexus pour se mettre en conditions réelles.

Avec Docker c’est assez simple :

docker run -d -p 8081:8081 --name nexus sonatype/nexus3

Une fois démarré, un serveur Nexus doit être accessible à http://localhost:8081.

Configuration des settings Maven

On va ensuite définir des settings personnalisés pour Maven avec un fichier custom-settings.xml comme suit :

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
	<localRepository/>
	<mirrors>
		<mirror>
			<id>private-nexus-repo</id>
			<name>My Nexus Maven Repository</name>
			<url>http://localhost:8081/repository/maven-public/</url>
			<mirrorOf>central</mirrorOf>
		</mirror>
	</mirrors>
</settings>

Ces settings doivent ensuite être passés au conteneur Docker au moyen d’un bind mount en utilisant les volumes Docker. Les volumes sont configurés au niveau du runner GitLab.

Dans la configuration config.toml, on ajoutera ou modifiera donc cette section :

  [runners.docker]
    ...
    volumes = ["/cache", "/host/path/custom-settings.xml:/root/.m2/settings.xml:ro"]

En pratique, on peut valider que les settings Maven sont corrects en exécutant simplement un container Docker comme ici :

docker run --rm -v $(pwd)/custom-settings.xml:/root/.m2/settings.xml:ro maven:3 mvn help:effective-settings

Au minimum le plugin help devrait être téléchargé via Nexus, ainsi que ses dépendances. Cela permet aussi de valider que le montage de volume du fichier settings.xml est correct et bien pris en compte dans le container. Un chemin absolu est nécessaire quand on passe par Docker CLI (contrairement à Docker Compose).
Le résultat de la commande précédente devrait ressembler à çà au final :

[INFO] 
Effective user-specific configuration settings:
<?xml version="1.0" encoding="UTF-8"?>
<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Generated by Maven Help Plugin on 2021-03-02T18:12:40Z                 -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/                -->
<!--                                                                        -->
<!-- ====================================================================== -->
<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Effective Settings for 'root' on '19791eb218d0'                        -->
<!--                                                                        -->
<!-- ====================================================================== -->
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <localRepository>/root/.m2/repository</localRepository>
  <mirrors>
    <mirror>
      <mirrorOf>central</mirrorOf>
      <name>My Nexus Maven Repository</name>
      <url>http://172.17.0.1:8081/repository/maven-public/</url>
      <id>private-nexus-repo</id>
    </mirror>
  </mirrors>
  <pluginGroups>
    <pluginGroup>org.apache.maven.plugins</pluginGroup>
    <pluginGroup>org.codehaus.mojo</pluginGroup>
  </pluginGroups>
</settings>
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  59.360 s
[INFO] Finished at: 2021-03-02T18:12:40Z
[INFO] ------------------------------------------------------------------------

Accès au serveur Nexus à partir du conteneur Docker

Attention si le conteneur souhaite accéder à un service hébergé sur son hôte, il ne pourra pas résoudre localhost, et il faudra remplacer par exemple localhost par son ip résolue. Voir :

Tester avec cette commande par exemple :

ip addr show docker0

Résultat attendu

Normalement à ce point, tout devrait fonctionner. Dans le log du job Maven du pipeline on devrait avoir quelque chose comme çà :

Running with gitlab-runner 13.9.0 (2ebc4dc4)
  on Runner Maven XHUSESdz
Preparing the "docker" executor
00:06
Using Docker executor with image maven:3.6-jdk-8 ...
Pulling docker image maven:3.6-jdk-8 ...
Using docker image sha256:75cbe9c11be24bae1cb8064cbc33c26df79321b5047c30ff8e29abcd2e5289a9 for maven:3.6-jdk-8 with digest maven@sha256:d4a4bb5d83a95c012615c5294f665ee042e721298c941eea32db3ea0ca588e9b ...
Preparing environment
00:02
Running on runner-xhusesdz-project-23778885-concurrent-0 via guillaume-F3JP...
Getting source from Git repository
00:05
Fetching changes with git depth set to 50...
Reinitialized existing Git repository in /builds/ghusta/maven-git-flow-test/.git/
Checking out c170a61a as feature/gitlab-ci-tags-custom-runner...
Removing .m2/
Removing target/
Skipping Git submodules setup
Restoring cache
00:03
Checking cache for default...
No URL provided, cache will not be downloaded from shared cache server. Instead a local version of cache will be extracted. 
Successfully extracted cache
Executing "step_script" stage of the job script
00:10
Using docker image sha256:75cbe9c11be24bae1cb8064cbc33c26df79321b5047c30ff8e29abcd2e5289a9 for maven:3.6-jdk-8 with digest maven@sha256:d4a4bb5d83a95c012615c5294f665ee042e721298c941eea32db3ea0ca588e9b ...
$ mvn $MAVEN_CLI_OPTS verify
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/share/maven
Java version: 1.8.0_282, vendor: Oracle Corporation, runtime: /usr/local/openjdk-8/jre
Default locale: en, platform encoding: UTF-8
OS name: "linux", version: "5.4.0-66-generic", arch: "amd64", family: "unix"
3361 [INFO] Error stacktraces are turned on.
3477 [INFO] Scanning for projects...
...
7330 [INFO] ------------------------------------------------------------------------
7336 [INFO] BUILD SUCCESS
7337 [INFO] ------------------------------------------------------------------------
7340 [INFO] Total time:  3.910 s
7345 [INFO] Finished at: 2021-02-28T21:08:20Z
7348 [INFO] ------------------------------------------------------------------------
Saving cache for successful job
00:01
Creating cache default...
.m2/repository: found 977 matching files and directories 
Archive is up to date!                             
Created cache
Cleaning up file based variables
00:01
Job succeeded

Et voilà çà marche !

Et n’importe quelle image Docker Maven peut être configurée dans le fichier .gitlab-ci.yml, au choix du développeur. Comme par exemple :

  • maven
  • maven:3.6
  • maven:3-jdk-8
  • maven:3-openjdk-11
  • maven:3-openjdk-17-slim
  • etc…

Hibernate : what does « hbm2ddl.auto=validate » ?

hibernate-logo2

Usage

Hibernate property

Activation with (documentation) :

hibernate.hbm2ddl.auto = validate

By programmation, use org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, set with values in enum org.hibernate.tool.schema.Action.

What does it validate ?

    • Check if table exists
    • Check if column exists
    • Check if column’s type matches (for example VARCHAR String)
    • Check if sequence exists and if increment size matches depending how org.hibernate.dialect.H2Dialect#getQuerySequencesString() and org.hibernate.dialect.Dialect#getSequenceInformationExtractor() are implemented in the current Hibernate Dialect. At the moment it is fully implemented for H2 database.

Implementation details

Interface : org.hibernate.tool.schema.spi.SchemaValidator#doValidation

Implementation : org.hibernate.tool.schema.internal.AbstractSchemaValidator#doValidation
Will call :

  • validateTables(...)
  • validateTable(...)
  • validateColumnType(...)
  • validateSequence(...)

Checking the sequence’s increment size

This check will only be done for H2 databases for the moment.

See classes : org.hibernate.tool.schema.extract.internal.SequenceInformationImpl (contains incrementSize) and implementations of org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor.

For PostgreSQL, org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl will be used, where SequenceInformationImpl#getIncrementSize() is always == -1.

The comprehensive details about sequences could be retrieved with PostgreSQL using this query, as of version 8.2 (from official doc and SO answer) :
SELECT * FROM information_schema.sequences;

The interesting columns in our case would be "sequence_name" and "increment".

Changes as of Hibernate 5.4

Since Hibernate ORM 5.4, it has been refactored and sequences validation should work as expected. A new configuration setting has also been introduced : « hibernate.id.sequence.increment_size_mismatch_strategy », referenced by AvailableSettings.SEQUENCE_INCREMENT_SIZE_MISMATCH_STRATEGY.

See HHH-12973 for details : « Inconsistent identity generation when using the default @SequenceGenerator with a database sequence having the increment size of 1 ».

See also this related commit in sources, in particular in PostgreSQL81Dialect.

Télécharger une vidéo YouTube en Full HD en ligne de commande

logo_small_2x-vfl4_cFqn
On a parfois besoin de télécharger une vidéo sur YouTube. Il existe différents moyens pour cela.
Je vais vous présenter une méthode utilisant des outils en ligne de commande. Ces outils ont l’avantage de disposer de nombreuses options.

Formats audio et vidéo

Le format de la vidéo est évidemment un critère essentiel. On pourra par exemple choisir une résolution pour la vidéo, comme HD avec 720 lignes, Full HD (FHD) avec 1080 lignes, Ultra HD (UHD ou 4K) avec 2160 lignes, etc. Voir Résolutions et formats recommandés par YouTube pour les formats recommandés en entrée.
Pour l’extension du fichier avec YouTube on aura généralement le choix entre mp4, 3gp ou webm.
Plusieurs codecs vidéo sont proposés au téléchargement, comme VP9, VP8, AV1.
Pour le flux audio, il est également possible de choisir le codec utilisé, ainsi que le bitrate (débit).

Outil de téléchargement des flux audio et vidéo

Pour télécharger une vidéo YouTube, il existe un outil génial qui s’appelle youtube-dl, disponible pour Windows, Mac, Linux. Cet outil est écrit en Python, le projet est en open source et hébergé sur GitHub : https://github.com/rg3/youtube-dl.
Tout un tas d’options sont disponibles.
Tout d’abord, on va installer l’outil en suivant ces instructions.
Ensuite on va pouvoir télécharger une première vidéo. Pour commencer on va simplement utiliser les options par défaut, pour obtenir une vidéo contenant un flux audio. Cette vidéo devrait être au format HD 720p, avec une extension MP4.
Exemple :
$ youtube-dl https://www.youtube.com/watch?v=sXsr_7Una_A
[youtube] sXsr_7Una_A: Downloading webpage
[youtube] sXsr_7Una_A: Downloading video info webpage
[download] Destination: Les Indestructibles 2 - Bande-annonce officielle-sXsr_7Una_A.mp4
[download] 100% of 16.62MiB in 00:14
Notez que si vous êtes en entreprise, la plupart du temps un proxy va vous embêter. Pour cela l’option –proxy https://hote:port pourra vous être utile.
Si vous voulez obtenir la liste des formats disponibles, rajoutez l’option -F :
$ youtube-dl -F https://www.youtube.com/watch?v=sXsr_7Una_A
[youtube] sXsr_7Una_A: Downloading webpage
[youtube] sXsr_7Una_A: Downloading video info webpage
[info] Available formats for sXsr_7Una_A:
format code extension resolution note
249 webm audio only DASH audio 53k , opus @ 50k, 799.86KiB
250 webm audio only DASH audio 67k , opus @ 70k, 1.02MiB
171 webm audio only DASH audio 122k , vorbis@128k, 1.87MiB
140 m4a audio only DASH audio 128k , m4a_dash container, mp4a.40.2@128k, 2.09MiB
251 webm audio only DASH audio 136k , opus @160k, 2.00MiB
278 webm 256x144 144p 94k , webm container, vp9, 24fps, video only, 1.50MiB
160 mp4 256x144 144p 110k , avc1.4d400c, 24fps, video only, 1.19MiB
242 webm 426x240 240p 189k , vp9, 24fps, video only, 2.29MiB
133 mp4 426x240 240p 273k , avc1.4d4015, 24fps, video only, 2.71MiB
243 webm 640x360 360p 344k , vp9, 24fps, video only, 4.48MiB
134 mp4 640x360 360p 633k , avc1.4d401e, 24fps, video only, 5.84MiB
244 webm 854x480 480p 648k , vp9, 24fps, video only, 7.99MiB
135 mp4 854x480 480p 1160k , avc1.4d401e, 24fps, video only, 10.11MiB
247 webm 1280x720 720p 1344k , vp9, 24fps, video only, 12.96MiB
136 mp4 1280x720 720p 1885k , avc1.4d401f, 24fps, video only, 14.53MiB
248 webm 1920x1080 1080p 2262k , vp9, 24fps, video only, 22.18MiB
137 mp4 1920x1080 1080p 2801k , avc1.640028, 24fps, video only, 23.42MiB
17 3gp 176x144 small , mp4v.20.3, mp4a.40.2@ 24k, 1.36MiB
36 3gp 320x180 small , mp4v.20.3, mp4a.40.2, 3.72MiB
18 mp4 640x360 medium , avc1.42001E, mp4a.40.2@ 96k, 8.86MiB
43 webm 640x360 medium , vp8.0, vorbis@128k, 11.89MiB
22 mp4 1280x720 hd720 , avc1.64001F, mp4a.40.2@192k (best)

Ainsi on peut remarquer que la vidéo téléchargée précédemment est celle avec le code 22. Si l’on souhaite télécharger une vidéo en 1080p, on pourra utiliser le code 137 en rajoutant l’option -f 137 devant l’URL en ligne de commande. Seul problème, cette vidéo ne contient pas de flux audio comme indiqué (video only).

Donc si l’on souhaite aussi obtenir la piste audio, on pourra choisir le code 140, en procédant comme pour le flux vidéo, pour obtenir un fichier en extension M4A :

$ youtube-dl -f 140 https://www.youtube.com/watch?v=sXsr_7Una_A
[youtube] sXsr_7Una_A: Downloading webpage
[youtube] sXsr_7Una_A: Downloading video info webpage
[download] Destination: Les Indestructibles 2 - Bande-annonce officielle-sXsr_7Una_A.m4a
[download] 100% of 2.09MiB in 00:02
WARNING: sXsr_7Una_A: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.

Il restera ensuite à assembler ces 2 fichiers (MP4 + M4A), pour n’en avoir qu’un seul.

Outil d’assemblage des flux audio et vidéo

Pour cela on va utiliser un outil : FFmpeg. En réalité il s’agit d’un ensemble d’outils, ayant pour but de traiter des contenus multimédia, comme des flux audio ou vidéo.
Le projet FFmpeg est open source, on peut le trouver sur GitHub.
La documentation fournie est abondante.
Pour assembler le flux vidéo 1080p, et le flux audio m4a, on va utiliser cette commande :
$ ffmpeg -i video_file.1080p.mp4 -i audio_file.m4a -acodec copy -vcodec copy output.mp4

On obtient donc un fichier output.mp4 en sortie, contenant les 2 flux.

Automatiser ce processus avec ffmpeg

Si les binaires de ffmpeg sont présents dans le path, cela va simplifier le processus de fusion.

En effet dans ce cas youtube-dl va utiliser ffmpeg pour télécharger les 2 meilleurs flux et les fusionner dans un container à la fin (mp4, mkv, etc.).

Exemple :

[[download]] Destination: myvideo-xxx.f137.mp4
[[download]] 100% of 181.64MiB in 01:32
[[download]] Destination: myvideo-xxx.f140.m4a
[[download]] 100% of 37.34MiB in 00:20
[[ffmpeg]] Merging formats into "myvideo-xxx.mp4"

Les fichiers de sous-titres

Maintenant on souhaiterait aussi récupérer les sous-titres de la vidéo, qu’ils soient générés automatiquement par YouTube ou non. Il existe une option pour cela.

On avait l’habitude des fichiers en extension SRT (SubRip). Cependant un nouveau format, adapté au web et HTML5, a vu le jour : WebVTT. C’est ce dernier format qui sera préféré par YouTube. Pour information, VLC 3.0 reconnaît ce format.

Pour télécharger un fichier vtt, on va utiliser la commande suivante :

$ youtube-dl --write-sub --skip-download https://www.youtube.com/watch?v=sXsr_7Una_A

L’option –skip-download permet de ne pas re-télécharger la vidéo.

L’option –list-subs permet de lister les sous-titres disponibles.

Et les pubs ?

Normalement il ne devrait pas y avoir de publicités dans les vidéos téléchargées, la publicité étant réservée aux vidéos en ligne.

Voir plus de détails sur https://www.youtube.com/yt/advertise/.

Métadonnées

Il peut être utile d’extraire les métadonnées d’une vidéo, ou de les rajouter lors du téléchargement.
Voir options : –write-info-json ou –add-metadata
Exemple :
$ youtube-dl --write-info-json https://www.youtube.com/watch?v=sXsr_7Una_A
...
[info] Writing video description metadata as JSON to: Les Indestructibles 2 - Bande-annonce officielle-sXsr_7Una_A.info.json

Personnaliser le nom de fichier en sortie

Il est possible d’utiliser des variables correspondant aux métadonnées (titre, date d’upload, format, résolution, extension, etc.), pour personnaliser le nom du fichier téléchargé. Voir la documentation : output template.

Références externes

How to update Docker CLI client for Windows

Sometimes you need to update your Docker Client for Windows, which was installed with Docker Toolbox. But you can’t find an easy way to do that (see this thread for example).

Docker Toolbox is the legacy way to use Docker on Windows, using VirtualBox, but it’s still useful when :

Upgrading the Docker Engine (server side) is easy with docker-machine. Just use :

docker-machine upgrade <machine_name>

and it will try to download the latest release (boot2docker.iso, working on VirtualBox) on https://github.com/boot2docker/boot2docker/releases/latest .

To update Docker Client, you could reinstall Docker Toolbox, but it’s quite cumbersome. In fact you can rebuild docker.exe from sources. After Docker Toolbox installation, this file can normally be found in « C:\Program Files\Docker Toolbox\docker.exe« .

How to build an exe for Windows

I found in Docker Toolbox sources how docker.exe was built and embedded.
It’s partly in this line :

RUN cp /go/src/github.com/docker/cli/build/docker-windows-amd64 docker.exe

Then I found that the CLI tool is in this repo : https://github.com/docker/docker-ce, under components/cli . So we can follow the instructions to build it.

For example, if you want to build docker.exe for a given version, let’s say « 18.05.0-ce », you can follow this script :

git clone https://github.com/docker/docker-ce.git
# List all tags (exclude the rc)
git tag --list 'v*-ce'
# Checkout desired version (tag)
git checkout 18.05.0-ce
# Build docker.exe CLI for Windows
cd components/cli
make -f docker.Makefile binary-windows
# find . -name docker-windows-amd64
cp build/docker-windows-amd64 docker.exe

Install the new exe

Then you can backup your old docker.exe in « C:\Program Files\Docker Toolbox\docker.exe » and replace it with the new one.

Test the new version

Check that the new version is working :

> docker --version
Docker version 18.05.0-ce, build

Docker : my container was OOMKilled

Intro

Un container Docker dispose de ressources limitées à sa création (cpu, mémoire…). Il se peut que le container crashe subitement s’il dispose de ressources insuffisantes. Dans le cas d’un manque de mémoire, on aura donc une erreur du type OOMKilled.

Vérification de l’état du container

Toutes les informations sur l’état du container :

docker inspect --format="{{json .State}}" $INSTANCE_ID

Retourne par exemple :

{"Status":"running","Running":true,"Paused":false,"Restarting":false,
"OOMKilled":false,"Dead":false,"Pid":2862,"ExitCode":0,"Error":"",
"StartedAt":"2018-06-13T13:41:47.205270058Z","FinishedAt":"2018-06-13T13:39:41.797869481Z"}

Flag OOMKilled :

docker inspect --format='{{.State.OOMKilled}}' $INSTANCE_ID

Retourne true si OOM

Flag ExitCode :

docker inspect --format='{{.State.ExitCode}}' $INSTANCE_ID

Retourne 137 en cas de crash dû à OOM.
137 = (128+9) Container received a SIGKILL

Tracer le problème dans une JVM

Au sein d’une JVM, on peut essayer de tracer l’erreur.

Voir par exemple les paramètres :

java -XX:+PrintFlagsFinal -version | grep -i outofmemoryerror

bool CrashOnOutOfMemoryError = false {product}
bool ExitOnOutOfMemoryError = false {product}
bool HeapDumpOnOutOfMemoryError = false {manageable}
ccstrlist OnOutOfMemoryError = {product}

Une version de JVM container-friendly

Des paramètres ont été rajoutés dans les versions récentes de la JVM, pour essayer d’adapter les paramètres mémoire de la JVM (Xms, Xmx) avec ceux du container dans lequel elle s’exécute.

A partir de JDK 8u131+ et JDK 9 on trouve donc de nouveaux paramètres, notamment pour la mémoire :

-XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap

Tickets concernés

Références

Configure Git to use with a proxy and switching back

git-logo-2color

Sometimes it can be useful and even necessary to configure Git to use a proxy in the global configuration.
It’s a easy as (https://git-scm.com/docs/git-config#git-config-httpproxy) :
git config --global http.proxy host:port

This configuration will then be written in ~/.gitconfig.

You will then have something like that :

[user]
	name = Me
	email = me@company.com
[http]
	proxy = host:port

Then one day you want to switch and use a different proxy, or none.

But it’s not obvious to configure, regarding the official documentation (https://git-scm.com/docs/git-config).

I could simply unset the proxy if I want to use none, like this :
git config --global --unset http.proxy

I also tried to create aliases to switch to another configuration, like :

  1. git config --global alias.proxy-local 'config --local http.proxy host:port'
  2. git config --global alias.noproxy-local 'config --local http.proxy none'

So I can use ‘git proxy-local’ or ‘git noproxy-local’ depending of the project.

But it could be more practical. By searching further I found a way to configure the proxy depending on the URL. Within the configuration we can use this format to configure options : http.<url>.* (https://git-scm.com/docs/git-config#git-config-httplturlgt).
Some examples are also documented like this :

; HTTP
[http]
	sslVerify
[http "https://weak.example.com"]
	sslVerify = false
	cookieFile = /tmp/cookie.txt

So that way you can configure a proxy by default, and for some URL use another proxy or none :

; Use a proxy by default
[http]
	proxy = host:port
; Use no proxy on internal server
[http "http://myserver.mycompany/"]
	proxy = 

That’s it !