CI – HoNoSoFt https://blog.honosoft.com Blog & Roll Tue, 13 Nov 2018 14:02:41 +0000 en-CA hourly 1 https://wordpress.org/?v=6.8.12 https://blog.honosoft.com/wp-content/uploads/2018/06/logo.png CI – HoNoSoFt https://blog.honosoft.com 32 32 Tutorial: Bamboo ➕ NDepend => How to integrate them together https://blog.honosoft.com/2018/11/13/tutorial-bamboo-%e2%9e%95-ndepend-how-to-integrate-them-together/?utm_source=rss&utm_medium=rss&utm_campaign=tutorial-bamboo-%25e2%259e%2595-ndepend-how-to-integrate-them-together https://blog.honosoft.com/2018/11/13/tutorial-bamboo-%e2%9e%95-ndepend-how-to-integrate-them-together/#respond Tue, 13 Nov 2018 12:44:26 +0000 https://blog.honosoft.com/?p=348 Continue Reading]]> This tutorial is intended to help you to integrate NDepend within your current builds or your new builds. In cases you missed it, NDepend is a tool in order to validate your dependencies within your project. You can look at the previous post on HoNoSoFt (French). The topic of this tutorial will be discussing about are the following:

What is Bamboo?

Quickly speaking, Bamboo is the Build server from Atlassian in it’s CI stack. It is often used with the integration of BitBucket and it also offer the possibilities to connect to any other repositories (GitHub included). Bamboo itself allow you to create build project, deployment strategy, interconnection with other Atlassian tools or even send automatically a message with the build status to your #Slack channels. If you already played with Jenkins, AppVeyor or GitLab, you should be already familiar with the daily usage of such a tool. In order to get more details on Bamboo, please follow this link, it will give a full details on Bamboo.

Pre-Requisites

  • Bamboo Server (or Agent) in Windows. In case you need to install a new instance, click here to download Bamboo.
    • It is mandatory to use or install the JDK 1.8 (Or JRE also seems to works) in a folder without any spaces. Any version greater than 8 won’t be working. This is supposed to become supported in the future.
    • If you run a test server locally in order to look how it works, it will be accessible on http://localhost:8085/
    • During the first time wizard a key will be required for activation (30 days or real license). To obtain a 30 days license, go into your Atlassian space or simply use this link in order to request the evaluation license for your account
  • NDepend Build license or Trial active on the build machine (or your current machine, if you run Bamboo locally)
  • PowerShell is not mandatory, but you will see later that it is a must in case you want to have a proper build without failure

Bamboo – Add NDepend Capability

What is a capability in Bamboo

In Bamboo, in order to be able to use any build related tools, you should normally set it for each agent in order to add a specific capabilities. In this case, we will be adding the NDepend capability to a Windows agent. That capability will be pointing to the NDepend.Console.exe coming from the NDepend package previously installed/downloaded. Don’t forget to launch it at least once in order to trigger the license. The details are available in the documentation. In my case, it is installed into [D:\Ndepend\NDepend_2018.2.1.9119]. I prefer to keep the version within the folder name. This is easy to know if my agent is using the proper version of the tool. This capability, if I change the executable folder will affect automatically all the build that was using this capability. It will not, in any cases, re-trigger an automatic build. The variable will then be re-applied starting from the next build.

It is common to keep those capabilities or executable in that screen. It regroup all your agent(s) features. More details on this feature can be found on the Atlassian website.

⚠Be aware: The capabilities displays dependencies with existing builds. That being said, if a capability variable is used within a script, you won’t see anywhere that as an active dependency. For that reason, you are required, in case of multiple agents, to specify manually what Agent should be used for your build stage.

Go to your agent configuration

  1. Click on the cog (options wheel);
  2. Select Agents;
  3. This will make you jump in the administration panel directly on the Agents build resources;
  4. Select your any of your Windows build Agent by simply clicking it.

Agent summary

  1. Validate that your agent name is valid;
  2. Go within the Capabilities tab;
  3. Click on the Add capability link button.

Adding the capability

  1. Capability type: Executable
  2. Type: Command
  3. Executable label: NDepend
  4. Path: [D:\Ndepend\NDepend_2018.2.1.9119\NDepend.Console.exe]

See the Agent specific capabilities

As you can see, after doing the previous steps, you will have your Agent specific capability added. Now, we can use that capability during our build.

Bamboo Build configuration – Capabilities (Easy)

Let’s consider you have your build already existing and that you want to add the NDepend console command. In the current tutorial bellow I will be taking a simple Dotnet Core 2.1 solution. The build will be named IdentityServer4.LdapExtension (GitHub project), where you would have your Git repository, NDepend project and your basic build already configured (checkout and build).

Add a new task to your build stage

  1. Ensure you are in the configuration of your project;
  2. Go to your build job where you usually run your tests and everything else;
  3. Within the tasks, you will find all the detail of your current job;
  4. Add a new task.

Once the popup show,

  1. Search for Command in the search box;
  2. Select Command by clicking it.

Let’s configure the command

  1. The new command task should be already displayed;
  2. The description of the task, in this case: NDepend;
  3. Select the executable you created for your agent capability: NDepend;
  4. Enter the argument to the full path of your NDPROJ  and override the indirs/outdirs parameters, see the Jenkins article for more details. Those path can be relative if you configured your project accordingly, otherwise it will be the full path. In case you don’t set those path properly, NDepend is not able to find your PDB’s files and consequently, do a proper analysis.
    • Example: ${bamboo.build.working.directory}/IdentityServer.LdapExtension.ndproj . You can add a “/silent” is if you don’t want to see all the output logs from NDepend, but I strongly not advise to do this within a build simply because you might need to debug using the logs one day. The indirs/outdirs are omitted considering you have pre-configured your project with relative path instead of the default full path.
  5. Save your configuration

Build your new configuration

I recommend to always build after doing modification. That way it’s easy to see if you caused the build to fail for a real reason (configuration) or if it’s due to code change (triggered builds).

In the case of NDepend, it’s execution returns an exit code. Be aware, the exit code will make your build fails if there’s any quality gate errors. You can read the following when executing the console application:

Notice that NDepend.Console.exe returns a non-zero exit code when at least one Quality Gate fails. This exit code can be used to eventually stop your build process in such situation.

Ref.: https://www.ndepend.com/docs/ndepend-console

The report, even on failure, will exists, however the build will be red and your artifact will probably not be even available. Since there’s no “/ErrorLevel” custom configuration for the exit code, then you will have to do differently in order to ignore those errors.

  • Option 1: Ignore the errors by adding the special tags from NDepend within your code.
    • In that case, simply add the NDepend ignore attributes where required and re-launch a build after your commit.
  • Option 2: Use a script instead of a command in order to control your flow completely and to continue even if there’s a quality gate issue
    • This is the topic of the next section

Bamboo Build configuration – PowerShell Script (Complex)

As stated previously, this is more for those who already have a project having no big issue which cause a quality gate to fail, or if you want to have the Quality Gate failed but still want to generate the reports.

Don’t get me wrong, the Capability created was not for nothing, however, the only drawback in this case is that the Capability will not be detecting our build dependency to NDepend.

In this case, instead of creating a command, we will be creating a script (or add to current Dotnet Core build script)

  1. Go in your Build configuration, default stage (or specific one) and click on Add task;
  2. Select the Script type;
  3. Enter the description and select Windows PowerShell as the Interpreter;
  4. In this case, we will be using the Inline type instead of a PS1 shell script. This option will create automatically a shell script behind the scene. After, simply re-write the code-snippet bellow the image.

The PowerShell is using the existing NDproj (XML file) and then replace the InDirs by the current build path in the command line. This is for your NDproj file that you wouldn’t have any relative path. Once this is completed, it will create the final command and execute it (Invoke-Expression). Here’s the PowerShell script used in the above picture.

# NDProj should normally be a variable in the build, the same goes for other parts. That way
# you can use a build script instead of inline, and that build script can be part of your build
# repository.
$ndproj = "IdentityServer.LdapExtension.ndproj"

# Load the NDepend XML project file.
$ndependXml = [xml](Get-Content .\${ndproj})

# If you have any spaces withn your project, you might encounter issue
# be aware of that. Here the string is a "vanilla" path.
$inDirs = (( `
    $ndependXml.SelectNodes("//Dir") |
    where {$_."#Text" -like "*IdentityServer4.LdapExtension*"} | 
    select -ExpandProperty "#Text" )`
    -replace '^.*(\\IdentityServer4\.LdapExtension\\)',"${bamboo.build.working.directory}\")`
    -join " "

## Launch NDepend command
$expr = "${bamboo.capability.system.builder.command.NDepend} " +`
   "${bamboo.build.working.directory}\${ndproj} " +`
   "/InDirs ${inDirs} " +`
   "/OutDir ${bamboo.build.working.directory}\NDependOut"

Invoke-Expression $expr

# Simple output for the execution result.
write-host "The exit code was: ${LASTEXITCODE}"

Generate the NDepend Artifact

Now, you should be able to build and have the NDepend output folder. In this demo, we have NDependOut as the folder. Todo so, we will have to add the artifact configuration. Please, go back in the Build configuration and your default stage where you have the NDepend script. Once this is complete, select the Artifacts tab and click on Create artifact button.

The fields to input are:

  • Name: NDepend
  • Location: NDependOut
  • Copy pattern: **/*

Once this is completed, you should be able to re-build your project and see if your build artifact is there. Note that if you want to have comparisons between your builds, you could re-use the shared artifact. This is a bit more complex, but it’s possible and it won’t be explored in this tutorial. Let’s say that you could simply avoid cleaning up the build folder every new build. I don’t suggest to do that, but it’s something that could work out.

For example, we have the following successful build:

  1. Green build = success
  2. Go in your artifacts of your build
  3. Click on the artifact name that interest you (NDepend in this case)

Once the artifact will open, it will show the content of the ZIP file. Simply click on the file NDependReport.html. This will then open a link that looks like: http://localhost:8085/artifact/I4E-ID/shared/build-19/NDepend/NDependReport.html#Main

Your page should look similar to this (It depends actually on your project):

Conclusion

Thank you for reading, and I hope it helped you configure your build! If you wish to also integrate with SonarQube, you also can. You simply have to do what is proposed in SonarQube integration with NDepend article and in your Bamboo script, where you build your Dotnet project, you add the NDepend Sonar Runner. The result can then be seen after your build directly within SonarQube. Don’t forget that you might want to install some Marketplace plugin in Bamboo for Sonar in order to send the data. In case you don’t want to use a plugin, don’t worry, it is also possible.

]]>
https://blog.honosoft.com/2018/11/13/tutorial-bamboo-%e2%9e%95-ndepend-how-to-integrate-them-together/feed/ 0
Intégration Continue (CI) > GitHub + AppVeyor + SonarQube (cloud) + BadgeIt https://blog.honosoft.com/2018/09/24/integration-continue-ci-github-appveyor-sonarqube-cloud-badgeit/?utm_source=rss&utm_medium=rss&utm_campaign=integration-continue-ci-github-appveyor-sonarqube-cloud-badgeit https://blog.honosoft.com/2018/09/24/integration-continue-ci-github-appveyor-sonarqube-cloud-badgeit/#respond Mon, 24 Sep 2018 13:59:16 +0000 https://blog.honosoft.com/?p=247 Continue Reading]]> Voici un premier article sur de l’intégration continue. Pour ceci, nous allons utiliser tous les outils “gratuit” disponible sur le web. Dans le futur, nous allons sans doute aussi traiter de GitLab. GitLab comprend déjà 2 des points mentionné dans le titre. C’est-à-dire la gestion du code source, le “build” ainsi que le déploiement.

Pour le moment, concentrons nous sur le scénario suivant:

  • GitHub : Gestion de code source
  • AppVeyor : Build automatisé tout particulièrement pour les application .Net, sinon comme alternative, vous pouvez utiliser Travis. Travis est plutôt bien, mais j’ai eu quelques problème par le passé concernant les applications .Net. Peut-être que c’est revenu à la normal depuis le temps.
  • SonarQube (Cloud) : Ici on prend la version cloud, cependant, vous pouvez l’installer sur un serveur local tout dépendant de votre usage.
  • BadgeIt : Projet créé par HoNoSoFt qui à pour but d’utiliser l’API de SonarQube ainsi que Shields.io afin de générer vos badges.
  • #Slack (Optionel) : Envoie des notifications avec Webhook lors de fin de build et d’analyse.

GitHub – Création de votre repo.

Si vous n’avez pas déjà un compte Github, shame on you :). Enfin, je dis ça, mais c’est plutôt pour vous aider à faire les étapes suivantes où vous n’aurez qu’un login ;). Du coup créez votre compte et continuez les étapes.

  1. Une fois connecté, allez sur votre image en haut et cliquez sur “Your repositories”
  2. De là simplement cliquer sur “New” après avoir bien entendu remplis le champ contenant le nom de votre projet.
    • Alternativement, dans le cas où vous êtes très paresseux, simplement dupliquer un projet existant que vous voulez faire le build et ajouter peut-être quelques fonctionnalités, pourquoi pas.
  3. Si vous avez créer votre nouveau repository, veuillez suivres les étapes afin d’ajouter votre code déjà existant. Ce sera d’ailleurs indiqué par défaut sur la page de tout votre nouveau projet.

Une fois complété, ça ressemblera à ce qui suit:

#Slack – Configuration de notification

Dans cet article, nous utiliserons Slack. Cependant, dans la vrai vie, n’importe quel system comportant un Webhook peut être utilisé. Étant donné que Slack est déjà prêt à être utilisé par toutes les applications de cet article, utilisons le. Si vous désirez, vous pouvez choisir un autre outil.

  1. Aller sur le site de #Slack
  2. Créer votre espace, ou bien utiliser un déjà existant
  3. Connectez vous à votre espace (web ou par l’application windows)
  4. Créez vous un channel qui s’appelle par exemple #ContinuousIntegration et invitez vos amis ;). Très utile si vous travaillez à plusieurs sur un projet.
  5. Sur le menu à gauche, vous trouverez une options appelé “Apps”. Appuyez sur ce bouton
  6. Dans la recherche, veuillez indiquer “Webhook” et sélectionnez “Incoming Webhook“
  7. Ajoutez le Webhook et changez la configuration à bon vous semble, cependant veuillez prendre en note le “Webhook URL“. Cet URL est utilisé afin de poussez vos notifications sur votre channel #Slack.

AppVeyor – Création de votre premier build, ou peut-être pas

Peut-être que vous avez déjà quelques build sur cette plateforme. Si c’est le cas, veuillez sauter dans la prochaine section, ou tout simplement lire en diagonale.

Ici on prendra pour acquis que vous allez builder une application .Net Core 2.1. Si vous avez un autre type d’application à bâtir, veuillez changer les choix afin de mieux vous accommoder.

  1. Accéder le site d’AppVeyor
  2. Vous connecter en utilisant votre compte GitHub
  3. Ajouter un projet existant (le bouton est plutôt évident et si vous n’avez pas trouvé, contactez moi je modifierai l’article).
  4. Avant de lancer votre build, vous devez impérativement configurer ce dernier.
    • Si vous n’êtes pas déjà sur votre projet, veuillez y accéder
    • Choisir le menu “Settings” > Onglet “General” sur la gauche (défaut)
      • Validez que le nom de votre projet est bien le bon ainsi que les options suivantes
    • Choisir le menu “Settings” > “Build”
      • Modifiez la configuration à “Release” si votre build est pour les mises en productions
      • Modifiez le “Before build script” et choisissez “CMD”
        • Insérrer “dotnet restore” (Sinon, votre restauration Nuget ne fonctionnera pas).
      • Appuyez sur “Save“
    • Choisir le menu “Settings” > “Environment”
      • Choisir Visual Studio 2017 au lieu du choix par défaut Visual Studio 2015
      • Appuyez sur “Save”
    • Choisir le menu “Settings” > “Notifications”
      • Choisir comme nouvelle notification “Slack“.
        • Insérez votre “Webhook URL” récupéré dans l’étape précédente (#Slack).
        • Choisir les événements désiré (Succès, …)
      • Appuyez sur “Save“
  5. Revenir sur le menu “Latest build”
    1. Lancer le “Build” en appuyant sur “New Build“
    2. Si le résultat est bon ou mauvais, vous devriez recevoir votre notification sur #Slack

Résultat une fois le build complété avec succès (notez le vert sur la gauche)

Résultat sur #Slack

SonarQube (Cloud) – Intégration pour valider votre qualité de code

Pour cette partie, je vais intégrer une partie de l’article AppVeyor+SonarQube disponible sur le site officiel de AppVeyor. Notez que SonarQube Cloud est gratuit pour les projet qui sont “publique” sur “GitHub”.

Important: Avec SonarCloud sous la version gratuite, les résultats seront publique et tout le monde pourra y accéder. Dans la plupart des scénario d’entreprise, ce ne sera pas le cas et vous aurez des soucis pour afficher les badges. Par soucis de sécurité, la prochaine section sera pour vous. Les badges pouvant être généré par votre propre système ou du moins sur votre réseau privé (subnet privé sur azure par exemple). Vous comprenez sans doutes où je veux en venir ;).

  1. Accéder au site de SonarQube Cloud
  2. Connectez-vous avec votre compte Github (pour la simplicité de la chose)
  3. Une fois connecté, veuillez aller sur votre profil (icône en haut à droite) et choisir “My account“
  4. Choisissez le menu “Security” afin de créer un nouveau Token qui sera ensuite utilisé par l’application BadgeIt.
    • Donnez un nom à votre token, e.g. “BadgeIt“
    • Appuyez sur “Generate“
    • Copiez et collez votre Token dans un fichier local sécuritaire ou un endroit afin de ne pas perdre cette information. Elle ne sera accessible qu’une fois, sinon vous devrez régénérer un nouveau Token.
  5. Créer un nouveau projet
  6. À ce moment, vous avez 2 choix, utiliser une nouvelle clé pour pouvoir pousser les résultats ou bien utiliser une clé existante. Je vous conseille ici de créer une clé seulement pour AppVeyor. Du coup, votre clé sera seulement pour cette application et la clé précédemment créé sera utilisé par la section qui suivre (BadgeIt).
    • Notez le nouveau Token
  7. Retour vers AppVeyor pour terminer la configuration du build.

Re-AppVeyor

Retour vers AppVeyor, allons re-configurer les événements de build ainsi que d’ajouter des variables d’environnement.

  1. Retour sur votre Project -> Settings -> Environment
  2. Ajoutez les 3 variables suivantes. Elles seront utilisé pour un script powershell. Ça évitera d’afficher publiquement certaines informations privées.
    • sonar_project_key: Déterminé lors de la création du projet dans SonarCloud. Cette clé doit normalement être unique.
    • solution: Nom de votre solution (peut contenir un “path” et non seulement le nom de la solution. Dans mon cas, c’est à la racine de mon repo. git)
    • sonar_api_key: Créé lors de l’étape précédente. Seulement coller votre valeur ici. N’oubliez pas de sauvegarder une fois que c’est fait ;).

Vous avez enfin les variables d’environnements, maintenant retournons sur la page de configuration du build.

  1. Retour sur votre Project -> Settings -> Build
  2. Allez au bas de la page de configuration et ensuite entrer ce qui suit dans “After build script“. Choisissez PS Core (ou powershell).
    • choco install "msbuild-sonarqube-runner" -y
      
      # Votre-organization vient aussi de SonarCloud. Du coup, veuillez renseigner le champ. Dans un SonarQube normal, vous n'aurez pas besoin de cette configuration.
      # Vous pouvez aussi ajouter cette variable d'environnement en tant que variable globale d'environnement sur AppVeyor
      $cmd = "MSBuild.SonarQube.Runner.exe begin /k:""${env:sonar_project_key}"" /d:sonar.organization=""VOTRE-ORGANISATION"" /d:""sonar.host.url=https://sonarcloud.io"" /d:""sonar.login=${env:sonar_api_key}"""
      Invoke-Expression $cmd
      
      msbuild $env:solution
      $cmd = "MSBuild.SonarQube.Runner.exe end /d:""sonar.login=${env:sonar_api_key}"""
      Invoke-Expression $cmd
    • Notez que le script peut aussi être modifié afin d’ajouter le numéro de version automatiquement et du coup synchronisez vos versions entre Sonar et AppVeyor.
  3. Sauvegarder

Relancer votre build et voilà, au rafraîchissement de la page Sonar vous devriez voir apparaître quelque chose comme ce qui suit:

Mon projet n’est pas parfait, mais ce n’est pas bien grave. Là plupart des “erreurs” sont dû à du HTML/JavaScript ou du code mort créé lors de refactoring récent. Je corrigerai, mais pour le moment ça montre que les chiffres ne sont pas tous à 0 et que ça a bien marché! 😀

BadgeIt – Configuration

Ici vous avez plusieurs choix. Je vous recommande votre environnement locale, mais SI vous ne pouvez pas, tournez vous vers votre hébergement favoris (Google, AWS, Azure, Heroku ou autre). Je vais donner quelques détails pour Azure, cependant ici nous allons nous attarder à la façon Heroku histoire de montrer comment déployer .Net Core 2.1 sous un container.

Azure (WebApp)

Pour ceux qui désire prendre le choix Azure, ce sera trivial:

  • Déploiement dans sur une WebApp ou similaire
  • Affecter les variables d’environnements
    • SonarQubeApi.ApiKey: Votre clée d’API créé lors de l’étape SonarQube (Cloud) et qui porte le nom de BadgeIt.
    • SonarQubeApi.BaseUri: Dans le cas ici présent: “https://sonarcloud.io/api/” ou sinon ce sera votre SonarQube privé.
    • BadgeApi.BaseUri: Par défaut, je vous recommande “https://img.shields.io/badge/”, mais si vous voulez un peu plus d’intimité et de performance, veuillez tout simplement installer le serveur Shields.IO localement. Veuillez vous référer au site Github de Shields.IO afin d’obtenir plus de détails.
  • Démarrer votre WebApp et voilà, vous pourrez suivre un peu plus loin comment utiliser l’API, sinon tout simplement charger la page principale de la WebApp, vous aurez un exemple et vous pourrez tester.

Azure (Docker container)

Veuillez suivre l’article MSDN afin de déployer votre application.

Heroku

Si vous n’avez pas déjà un compte Heroku, créez en un. Vous devrez aussi installer Heroku-Cli, car ce sera à partir de cette application que votre déploiement se fera. Sinon en générale, ce sera plutôt trivial. (Article Heroku à ce sujet)

  • Cloner le repo. HoNoSoFt.BadgeIt.SonarQube
  • Validez que vous avez bien le fichier “Dockerfile” dans le répertoire de l’application web (Dans notre cas: HoNoSoFt.BadgeIt.SonarQube.Web).
  • Connectez-vous au serveur de conteneurs Heroku
    • > heroku container:login
      • OU
    • > docker login –username=_ –password=$(heroku auth:token) registry.heroku.com
  • Poussez votre image
    • heroku container:push <process-type>
      • OU, si votre image existe déjà (tag plus push)
      • Exemple: > heroku container:push web –recursive -a badgeit
        • Important: La commande d’exécution doit absolument passer par CMD et non ENTRYPOINT.
    • docker tag <imageregistry.heroku.com/<app>/<process-type>
  • Vous pouvez ensuite faire une release de votre image
    • Exemple > heroku container:release web -a badgeit
  • N’oubliez pas d’aller configurer votre application heroku, car vous devrez mettre à jour les variables d’environnements.
    • Exemple:

Résultat:

Et voilà! Vous avez le tout de fonctionnel. Ce n’est pas bien de ne pas tout avoir dans le vert, mais ce n’est qu’une première version.

Possibilité de faire mieux (Oui, évidemment ;))

Petit exercice au cas où vous voulez vous amuser:

  1. Créer un docker-compose
    • Ajouter l’image de conteneur de Badgeit
    • Ajouter l’image de conteneur de Shields.io
    • Configurez le tout
    • Et testez
  2. Changer le message après le build afin d’envoyer un message personalisé à Slack en utilisant une image de votre badge service (badgeIt) ou autre.

À la prochaine!

]]>
https://blog.honosoft.com/2018/09/24/integration-continue-ci-github-appveyor-sonarqube-cloud-badgeit/feed/ 0