Introduction to SVG: The Basics

This entry is part 1 of 1 in the series Introduction to SVG

Lately I’ve been spending a some time building SVGs.
When I told my colleagues about what I was doing they asked me to write a short guide about what exactly that is and what you can do with it.
Since I got those questions, i thought that might be interesting for others out there, so here goes nothing:

First of all: what is SVG?

Just like JPEG or PNG, SVG is an image format, which lets us display images or graphics on the web.
SVG stands for ‘Scalable Vector Graphics’ – You might have heard about vectors in a different context already, like maths class or physics maybe?
The concept is the same: there is a direction and a force which helps to describe a path.
This means, that those graphics do not consist of fixed pixel values, but instead they’re a set of directions for whoever renders it (usually the user agent / browser) to follow.

SVG is written in a format that resembles XML, which means you have your image in a human readable plaintext file!

Why does that make it special?

The fact, that the graphics are made up with vectors comes with a bunch of useful qualities:

  • Scalability: It doesn’t matter, if you make the image 30x30px or 3000x3000px, it will stay sharp
  • Responsiveness: Because of its’ scalability you can have it take up whatever space you need it to
  • Programmable: Since your image is basically a text file, you can modify it programmatically as well, which gives it a flexibility unmatched by other common options.
  • Performance: Since we’re not sending out a binary blob of pixels but a text file, there is next to no loading time for the images.

The most common use cases are logos, icons and icon fonts, animations and diagrams.

What does it look like?

This is a simple svg, which we will be building together over the course of this blogpost:

First we define a simple 20×20 “coordinate system”, where 0,0 is in the top left corner.
In the viewBox we define what part of the SVG we will see when it is rendered. Positive x values move to the right and positive y values move downwards.
<svg viewBox="0 0 20 20"></svg> For a better understanding of the slightly mind-fucky topic of the viewBox property, check this out.

 

To start of with we want to draw the head:
For that we just use a <rect> element to draw a rectangle that fills the entire space.
<rect class="body" width="20" height="20"></rect>

 

The eyes consist of two <circle> elements that we position with cx and cy and give them a radius r of 1 unit.
<circle class="eye" cx="5" cy="15" r="1"></circle>
<circle class="eye" cx="15" cy="15" r="1"></circle>

 

When you put everything together the code for it looks something like this:

<svg viewBox="0 0 20 20">
  <rect class="body" width="20" height="20"></rect>
  <circle class="eye" cx="5" cy="15" r="1"></circle>
  <circle class="eye" cx="15" cy="15" r="1"></circle>
</svg>

So far we’d only have a black box, but as you might have noticed, I also added the class attribute into the elements.
This is for styling the SVG via CSS.
It is also possible to style the elements within their tags, but using CSS is usually preferred, since it makes it possible to style images with user themes as well!
This is the CSS:

.eye {
fill: #444;
}

.body {
stroke-width: 2;
stroke: #444;
fill: #f15a22;
}

 

The drawn lines can be edited with stroke  and if the fill attribute changes the colour that fills up the shape:

You can find the pen here.

Drawing our own images

Combining shapes is all nice and cool, but there are a lot more you can do with SVGs – for example create your own shapes.
We can do this with the path element. For it to know what to draw it needs the d attribute in which we can describe the path of the element.

<path d="M1,2 l4,4 h10 l4,-4 v17 h-18 Z"></path>

 

The d attribute has a syntax consisting of a few letters and a lot of numbers, that can look quite scary and unreadable at first, but when we break it down, it should look a lot clearer:
The letters are the commands and the numbers are their passing values.

 

M is the first command used. It’s the move command – so what it does is move the cursor to the position indicated by the numbers and is the starting point for our path.
M1,2 means it starts one unit to the right and two down.

 

The letters for the commands can either be uppercase to indicate absolute values or lowercase to indicate values that are relative to the last point we drew.
While m4,0 means “Move the cursor 4 units to the right”, M4,0 means move it to the position 4,0.

Basic commands for drawing lines

The next commands we want to look at describe straight lines:
L: any direction
H: horizontal
V: vertical
Z: last element for closing path

 

<path d="M1,2 L5,6 H15 L19,2 V19 H1 Z"></path>
We’re starting at M1,2.
First line is to position 5,6, so 4 to the right and 4 down with L5,6.
Then a horizontal line to H15.
Another line that goes up and to the right with L19,2.
Down to y value 19 with V19.
All the way left to x position 1 with H1
Finally, we close the path with the Z command.

 

It’s entirely up to you if you want to draw with relative or absolute values, in a 20×20 grid those two would draw the same image:

<path d="M1,2 l4,4 h10 l4,-4 v17 h-18 Z"></path>
<path d="M1,2 L5,6 H15 L19,2 V19 H1 Z"></path>

Adding the path together with the circles from our first head and applying the CSS again the image looks like this:

You can find the pen here.

Getting those round corners

The little fox looks a little square still, so we want to edit it to give it some round cheeks.

For this we use the q command, which stands for ‘quadratic curve’.

The q command requires two points, the one around which the curve should be and the point to which the line will go.

We draw the ears like we have before but instead of going down to the 19,19 corner, we stop 2 units further up.

From the point 19,17 we use the command Q19,19 17,19.
This indicates, that we want to wrap around the 19,19 and end at the 17,19 point.

The d value for this fox looks like this:

d="M1,2 L5,6 H15 L19,2 V17 Q19,19 17,19 H3 Q1,19 1,17 Z"

You can find the pen here.

 

Next in the series is going to be a bit more in depth about the more advanced commands and we will extend on the foxes head to make it look like this:
So stay tuned!

If you thought this was fun, maybe you want join our development team, to learn more about the SVGs and the like?

Feu Mourek
Feu Mourek
Developer

Feu verbrachte seine Kindheit im schönen Steigerwald und kämpfte sich bis zum Abitur durch die Schule. Seit September 2016 unterstützt es die Development Abteilung bei NETWAYS als Developer und UX Designer und widmet sich dort dem Web Development. Seine Freizeit verbringt es hauptsächlich in den virtuellen Welten von 'Dota 2' und diversen anderen Games, an der Kletterwand in der Boulderhalle, oder damit, mit Freunden und Kollegen Brett- und Pen and Paper Rollenspiele zu spielen.
GitLab-CI / YAML – Write less with Anchors, Extends and Hidden Keys

GitLab-CI / YAML – Write less with Anchors, Extends and Hidden Keys

Have you ever wanted to execute a GitLab-CI job for multiple operating systems and just copied every line of YAML multiple times?
Anchors, extends and hidden keys are coming to rescue!

Let’s say you have two jobs and the only difference between them being a single environment variable:

stages:
  - echo

echo-hello:
  stage: echo
  script:
    - echo $ECHO_TEXT
  variables: 
    ECHO_TEXT: "Hello world!"

echo-bye:
  stage: echo
  script:
    - echo $ECHO_TEXT
  variables: 
    ECHO_TEXT: "Bye bye!"

Anchors and extends

Writing the same job two times can already get quite messy and hard to maintain. The more jobs you add, the worse it gets.
But don’t worry, YAML has got you covered. Anchors and extends let you reuse parts of your config and extend on them.

In this example, we create the echo-hello job and extend on it in the echo-bye task:

stages:
  - echo

echo-hello: &echo #create an anchor named "echo"
  stage: echo
  script:
    - echo $ECHO_TEXT
  variables: 
    ECHO_TEXT: "Hello world!"

echo-bye:
  <<: *echo #use the anchor created above and extend it by using "<<"
  variables: 
    ECHO_TEXT: "Bye bye!"

Templating with hidden keys

One thing you can do to further improve on that is, by using a separate task just for templating using hidden keys.
Hidden keys can be defined in YAML using a . in front of a keys name. This prevents GitLab-CI from executing a job and allows us to use it as a template.

In our last example, we create an echo template job containing our stage and script. The echo job is then extended on in echo-hello and echo-bye:

stages:
 - echo

.echo: &echo #keys (jobs in this case) with a dot in front are hidden keys and won't be executed by GitLab
  stage: echo 
  script: 
    - echo $ECHO_TEXT  

echo-hello: 
  <<: *echo 
  variables:  
    ECHO_TEXT: "Hello world!"  

echo-bye: 
  <<: *echo  
  variables: 
    ECHO_TEXT: "Bye bye!"

Some real world examples can be found in our public Icinga 2 packaging repositories: https://git.icinga.com/packaging/rpm-icinga2

Noah Hilverling
Noah Hilverling
Developer

Nachdem Noah bei einer vierjährigen Exkursion nach Belgien seine Liebe zum Programmieren entdeckte, holte der gebürtige Euskirchener innerhalb kürzester Zeit gleich zwei Schulabschlüsse nach. Danach verließ Noah sogar den schönen Chiemsee, um sich ab September 2016 im Rahmen der Ausbildung zum Fachinformatiker für Anwendungsentwicklung bei NETWAYS voll und ganz dem Programmieren hinzugeben und viele unterschiedliche Erfahrungen zu sammeln. Wenn er mal nicht am Programmieren und Zocken ist, brettert er mit seinem Snowboard die Pisten runter,...

C++Go. Halb C++ – halb Go.

Scherz beiseite, die Go-Entwickler bieten noch keine Möglichkeit, C++-Bibliotheken ohne weiteres anzusprechen. Aber es geht ja auch mit weiteres. Das weitere besteht darin, dass C++-Funktionen mittels C-Bibliotheken gewrapped werden können. Und in meinem letzten Blogpost zu diesem Thema habe ich bereits erklärt, wie C-Bibliotheken in Go angesprochen werden können. Sprich, es braucht nur eine hauchdünne C-Schicht zwischen C++ und Go.

Multilingual++ in der Praxis

Wie auch letztes mal habe ich schon mal was vorbereitet – eine Schnittstelle für die Boost.Regex-Bibliothek. Diese findet sich in diesem GitHub-Repo und besteht aus folgenden Komponenten:

  • Ein Struct, das boost::basic_regex<char> wrapped
  • Eine C-Bibliothek, die den C++-Teil wrapped
  • Die Go-Bibliothek, die die C-Bibliothek verwendet

Wrapper-Struct

Dieses Struct ist Notwendig, da die Größe von boost::basic_regex<char> zwar C++ bekannt ist, aber nicht Go. Das Wrapper-Struct hingegen hat eine feste Größe (ein Zeiger).

libcxx/regex.hpp

#pragma once

#include <boost/regex.hpp>
// boost::basic_regex
// boost::match_results
// boost::regex_search

#include <utility>
// std::forward
// std::move

template<class Char>
struct Regex
{
	template<class... Args>
	inline
	Regex(Args&&... args) : Rgx(new boost::basic_regex<Char>(std::forward<Args>(args)...))
	{
	}

	Regex(const Regex& origin) : Rgx(new boost::basic_regex<Char>(*origin.Rgx))
	{
	}

	Regex& operator=(const Regex& origin)
	{
		Regex copy (origin);
		return *this = std::move(copy);
	}

	inline
	Regex(Regex&& origin) noexcept : Rgx(origin.Rgx)
	{
		origin.Rgx = nullptr;
	}

	inline
	Regex& operator=(Regex&& origin) noexcept
	{
		this->~Regex();
		new(this) Regex(std::move(origin));
		return *this;
	}

	inline
	~Regex()
	{
		delete this->Rgx;
	}

	template<class Iterator>
	bool MatchesSomewhere(Iterator first, Iterator last) const
	{
		boost::match_results<Iterator> m;
		return boost::regex_search(first, last, m, *(const boost::basic_regex<Char>*)this->Rgx);
	}

	boost::basic_regex<Char>* Rgx;
};

Eine C-Bibliothek, die den C++-Teil wrapped

Die folgenden Funktionen sind zwar waschechte C++-Funktionen, aber dank dem extern "C" werden sind sie in der Bibliothek als C-Funktionen sichtbar und können von Go angesprochen werden.

libcxx/regex.cpp

#include "regex.hpp"
// Regex

#include <boost/regex.hpp>
using boost::bad_expression;

#include <stdint.h>
// uint64_t

#include <utility>
using std::move;

extern "C" unsigned char CompileRegex(uint64_t pattern_start, uint64_t pattern_end, uint64_t out)
{
	try {
		*(Regex<char>*)out = Regex<char>((const char*)pattern_start, (const char*)pattern_end);
	} catch (const boost::bad_expression&) {
		return 2;
	} catch (...) {
		return 1;
	}

	return 0;
}

extern "C" void FreeRegex(uint64_t rgx)
{
	try {
		Regex<char> r (move(*(Regex<char>*)rgx));
	} catch (...) {
	}
}

extern "C" signed char MatchesSomewhere(uint64_t rgx, uint64_t subject_start, uint64_t subject_end)
{
	try {
		return ((const Regex<char>*)rgx)->MatchesSomewhere((const char*)subject_start, (const char*)subject_end);
	} catch (...) {
		return -1;
	}
}

libcxx/regex.h

#pragma once

#include <stdint.h>
// uint64_t

unsigned char CompileRegex(uint64_t pattern_start, uint64_t pattern_end, uint64_t out);

void FreeRegex(uint64_t rgx);

signed char MatchesSomewhere(uint64_t rgx, uint64_t subject_start, uint64_t subject_end);

Go-Bibliothek

Diese spricht letztendlich die C-Funktionen an. Dabei übergibt sie die Zeiger als Ganzzahlen, um gewisse Sicherheitsmaßnahmen von CGo zu umgehen. Das Regex-Struct entspricht dem Regex-Struct aus dem C++-Teil.

regex.go

package boostregex2go

import (
	"io"
	"reflect"
	"runtime"
	"unsafe"
)

/*
#include "libcxx/regex.h"
// CompileRegex
// FreeRegex
// MatchesSomewhere
*/
import "C"

type OOM struct {
}

var _ error = OOM{}

func (OOM) Error() string {
	return "out of memory"
}

type BadPattern struct {
}

var _ error = BadPattern{}

func (BadPattern) Error() string {
	return "bad pattern"
}

type Regex struct {
	rgx unsafe.Pointer
}

var _ io.Closer = (*Regex)(nil)

func (r *Regex) Close() error {
	C.FreeRegex(rgxPtr64(r))
	return nil
}

func (r *Regex) MatchesSomewhere(subject []byte) (bool, error) {
	defer runtime.KeepAlive(subject)
	start, end := bytesToCharRange(subject)

	switch C.MatchesSomewhere(rgxPtr64(r), start, end) {
	case 0:
		return false, nil
	case 1:
		return true, nil
	default:
		return false, OOM{}
	}
}

func NewRegex(pattern []byte) (*Regex, error) {
	rgx := &Regex{}

	defer runtime.KeepAlive(pattern)
	start, end := bytesToCharRange(pattern)

	switch C.CompileRegex(start, end, rgxPtr64(rgx)) {
	case 0:
		return rgx, nil
	case 2:
		return nil, BadPattern{}
	default:
		return nil, OOM{}
	}
}

func bytesToCharRange(b []byte) (C.uint64_t, C.uint64_t) {
	sh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	return C.uint64_t(sh.Data), C.uint64_t(sh.Data + uintptr(sh.Len))
}

func rgxPtr64(p *Regex) C.uint64_t {
	return C.uint64_t(uintptr(unsafe.Pointer(p)))
}

Fazit++

Wenn etwas abgedrehtes mal nicht zu gehen scheint, dann gebe ich doch nicht auf, sondern ich mache es einfach noch abgedrehter. Impossible is nothing.

Wenn Du auch lernen willst, wie man unmögliches möglich macht, komm auf unsere Seite der Macht.

Alexander Klimov
Alexander Klimov
Developer

Alexander hat 2017 seine Ausbildung zum Developer bei NETWAYS erfolgreich abgeschlossen. Als leidenschaftlicher Programmierer und begeisterter Anhänger der Idee freier Software, hat er sich dabei innerhalb kürzester Zeit in die Herzen seiner Kollegen im Development geschlichen. Wäre nicht ausgerechnet Gandhi sein Vorbild, würde er von dort aus daran arbeiten, seinen geheimen Plan, erst die Abteilung und dann die Weltherrschaft an sich zu reißen, zu realisieren - tut er aber nicht. Stattdessen beschreitet er mit der...

Flying blind – accessibility in the world wide web

Do you know how many visually impaired people there are out there?
I can tell you: There are roughly 188.5 million people with mild vision impairment, 1043 million have moderate to severe vision impairment, and 36 million people are blind (According to the world health organisation in 2018). When it comes to colour blindness there are approximately 300 million people affected – that’s almost as many people as the entire population of the USA! (According to the Colour Blind Awareness Community)

That’s a lot, isn’t it? And a lot of those people also use the web. Not everyone in the same way as most do though.

Have you ever used a screen reader? Or heard of the term at all? A screen reader is a tool used to have the content of your screen read out for you. They are usually used by people who have issues reading what’s presented – either because they cannot distinguish between what’s written and the background because of bad contrasts, because fonts that are too small or just because they can not read or see at all.
For anyone who is interested how it works there is a lot of material on youtube, like this video by the SLCC Universal Access channel. If you have the time you should also try it out yourself, there are a lot of free tools out in the www.

In order to make this all possible there are guidelines provided by the w3, which cover:

  • Web Content Accessibility Guidelines (WCAG) – how to make web content accessible
  • Authoring Tool Accessibility Guidelines (ATAG) – make authoring tools accessible
  • User Agent Accessibility Guidelines (UAAG) – make user agents accessible
  • Accessible Rich Internet Applications Suite (ARIA) – make web content and web applications accessible

For all of the (web) developers reading this, those are definitely worth a read! Sticking to those standards makes the web more accessible for everyone, and that’s what everyone should strive for, right?

For people who have difficulties with contrasts, there are standards set by the w3 and also high-contrast ‘themes’ available for some tools.

People affected by some form of colour vision deficiency there are colour blind variations in some tools – often times they are just being overlooked though. I have some pictures for you, that aim to visualise the most common kinds of colour vision:

colours with different simulated vision impairments

I used ‘Color Oracle’ for the simulated colours.

There is also a more detailed blogpost on icinga.com about our new ‘colour blind’ theme in Icinga Web 2.

Feu Mourek
Feu Mourek
Developer

Feu verbrachte seine Kindheit im schönen Steigerwald und kämpfte sich bis zum Abitur durch die Schule. Seit September 2016 unterstützt es die Development Abteilung bei NETWAYS als Developer und UX Designer und widmet sich dort dem Web Development. Seine Freizeit verbringt es hauptsächlich in den virtuellen Welten von 'Dota 2' und diversen anderen Games, an der Kletterwand in der Boulderhalle, oder damit, mit Freunden und Kollegen Brett- und Pen and Paper Rollenspiele zu spielen.

Entwicklerazubis: Jahr 1, das Projekt

Man bekommt nicht immer das, was man will… außer, man ist bei NETWAYS Azubi!

 

Mein erstes Jahr bei NETWAYS ist fast vorüber, und meine jugendlichen Ambitionen haben den Wunsch in mir erweckt, mit den beiden anderen Dev-Azubis meines Jahres, Loei und Niko, ein eigenes Projekt zu übernehmen, um unsere erlernten Fertigkeiten zu prüfen, eine Übersicht davon zu bekommen, auf welchem Stand wir alle sind, den ein oder anderen Trick voneinander aufzuschnappen und eigenverantwortlich und kooperativ ein Projekt zu vervollständigen. Und alles, was es gebraucht hat, um diesen Wunsch zu erfüllen, war diese Idee zu pitchen und klar und deutlich zu vermitteln, warum dieses Interesse besteht, und was wir uns davon erhoffen. Meine Vorgesetzten scheinen von der Idee zumindest angetan genug gewesen zu sein, dass wir drei Wochen eingeräumt bekommen haben, um uns um dieses Projekt zu kümmern. Danke, NETWAYS!

Die Aufgabe klingt einfach, hat es aber doch durchaus in sich – aus Berichten in Icinga sollen PDFs generiert werden. Die Funktionalität ist schon vorhanden – unsere Aufgabe ist es, den Benutzern mehr Features zur Verfügung zu stellen, damit man eigene Anpassungen an dem Aussehen der PDFs vornehmen kann. Das Schöne an dieser Aufgabe ist die Breite der Elemente und Bereiche, welche eine Rolle dabei spielen. Icingaweb, PHP, HTML, CSS, Google Chrome… es ist in gewisser Art und Weise eine große Reise in das Unbekannte, und natürlich können wir alle drei uns nicht sicher sein, welche Probleme und Hürden sich uns in den Weg stellen werden, und wie die zündenen Ideen kommen, die uns helfen, diese Hürden zu überwinden.

 

Boo

Much better

Und zündende Ideen gab’ es bereits! Ein Beispiel: Google Chrome baut sich aus HTML-Code die PDFs zusammen, lässt sich es aber nicht nehmen, automatisch generierte Header und Footer anzufügen, mit Seitenzahl und Datum. Das ist natürlich ein Element, welches wir gerne unter Kontrolle hätten! Der erste Hack, mit dem ich mich über diese Hürde bewegt habe, ist ein CSS-Styleelement an den übergeben HTML-Code anzufügen. Das ist in seinem momentanen Zustand natürlich noch etwas unschön gelöst, wenn einfach nur der HTML-Code um ein fest eingebautes Codeelement erweitert wird, aber wir haben einen Einstiegspunkt, einen Ansatz, mit der wir weiterbauen und -basteln können.

 

Scheue Dich vor Fragen nicht!

Auch wenn der Kerngedanke dieses Projekts natürlich daraus besteht, dass wir uns selbst beweisen, spricht natürlich Nichts dagegen, bei Fragen, die aufkommen, einen der zahlreichen Experten die NETWAYS hat zu involvieren. Was Benutzeroberflächen angeht, ist bei uns UX-Designer Florian der Ansprechpartner Nummer 1. Wir haben uns zusammengesetzt und konnten ihm live beim Bauen eines Mockups in Sketch zusehen. Eine Gelegenheit, durch die großen Augen, die wir gemacht haben, auch etwas über grundlegende Designansätze in Icingaweb zu lernen, und Grundsätze bezüglich Design. Mit diesem Wissen können wir erstmal diesen Pfad weiter selbst beschreiten, aber natürlich werden wir viel Rücksprache führen. Nur weil man bisher nicht dazu kam, sich extensive Kenntnisse in einem Bereich selbst anzueignen, heißt das nicht, dass man dieses Wissen, wenn es einem zur Verfügung steht, nicht nutzen kann. Und immer schön dran denken, selbst den Fundus an Talenten zu erweitern.

A mockup of things to come…

 

Kooperatives Kodieren

Einer der in meiner Einleitung angesprochenen Tricks, den ich einfach für neat halte, und sehr dem Spirit dieses Projektes entspricht, ist die Möglichkeit in git Co-Authoren einzutragen. Dafür muss man in der commit message einfach

 Co-authored-by: Name <e-mail>

angeben, und git verlinkt automatisch zwei Autoren für diesen commit. In diesem Fall meine beiden Kollegen bei diesem Projekt. Gute Arbeit, Jungs!

Da kann man ruhig mal klatschen! 👏

 

Willst Du uns vielleicht nächstes Jahr bei dem nächsten Entwicklungsprojekt behilflich sein? Dann raus mit Deiner Bewerbung an NETWAYS! Wir freuen uns schon auf dich!

Henrik Triem
Henrik Triem
Junior Developer

Henrik is Anwendungsentwickler in Ausbildung, verhindeter Rockstar, kaffeegetrieben und Open Source-begeistert. Zuhause lässt er es auch mal ruhiger mit Tee angehen, entspannt an Klavier oder Gitarre, erkundet neue Musik oder treibt sich mit seinen Freunden in Deutschland herum.
DEV stories: Icinga Core trainees in the making

DEV stories: Icinga Core trainees in the making

When my dev leads approached me with the idea to guide a trainee in the Icinga core topic, I was like … wow, sounds interesting and finally a chance to share my knowledge.

But where should I start and how can it be organized with my ongoing projects?

 

Prepare for the unexpected

My view on the code and how things are organized changed quite a bit since then. You cannot expect things, nor should you throw everything you know into the pool. While working on Icinga 2.11, I’ve collected ideas and issues for moving Henrik into these topics. In addition to that, we’ve improved on ticket and documentation quality, including technical concepts and much more.

My colleagues know me as the “Where is the test protocol?” PR reviewer. Also, reliable configuration and steps on reproducing the issues and problems are highly encouraged. Why? The past has proven that little to zero content in ticket makes debugging and problem analysis really hard. Knowledge transfer is an investment in the future of both NETWAYS and Icinga.

Some say, that documentation would replace their job. My mission is to document everything for my colleagues to make their life easier. Later on, they contribute to fixing bugs and implement new features while I’m moving into project management, architecture and future trainees. They learn what I know, especially “fresh” trainees can be challenged to learn new things and don’t necessarily need to change habits.

 

Clear instructions?

At the beginning, yes. Henrik started with the C++ basics, a really old book from my studies in 2002. C++11 is a thing here, still, the real “old fashioned” basics with short examples and feedback workshops prove the rule. Later on, we went for an online course and our own requirements.

Since Icinga 2 is a complex tool with an even more complex source code, I decided to not immediately throw Henrik into it. Instead, we had the chance to work with the Tinkerforge weather station. This follows the evaluation from our Startupdays and new product inside the NETWAYS shop. The instructions were simple, but not so detailed:

  • Put the components together and learn about the main functionality. This is where the “learn by playing” feeling helps a lot.
  • Explore the online documentation and learn how to use the API bindings to program the Tinkerforge bricks and sensors.
  • Use the existing check_tinkerforge plugin written in Python to see how it works
  • Write C++ code which talks to the API and fetches sensor data

Documentation, a blog post and keeping sales updated in an RT ticket was also part of the project. Having learned about the requirements, totally new environment and communication with multiple teams, this paves the way for future development projects.

 

Freedom

In order to debug and analyse problems or implement new features, we need to first understand the overall functionality. Starting a new project allows for own code, experiences, feedback, refactoring and what not. Icinga 2 as core has grown since early 2012, so it is key to understand the components and how everything is put together.

Where to start? Yep, visit the official Icinga trainings for a sound base. Then start with some Icinga cluster scenarios, with just pointing to the docs. This takes a while to understand, so Henrik was granted two weeks to fully install, test and prepare his findings.

With the freedom provided, and the lessons learned about documentation and feedback, I was surprised with a Powerpoint presentation on the Icinga cluster exercises. Essentially we discussed everything in the main area in our new NETWAYS office. A big flat screen and the chance that colleagues stop by and listen or even add to the discussion. Henrik was so inspired to write a blogpost on TLS.

 

Focus on knowledge

In the latest session, I decided to prove things and did throw a lot of Icinga DSL exercises at Henrik, also with the main question – what’s a DSL anyways?

Many things in the Icinga DSL are hidden gems, with the base parts documented, but missing the bits on how to build them together. From my experience, you cannot explain them in one shot, specific user and customer questions or debugging sessions enforce you to put them together. At the point when lambda functions with callbacks were on the horizon, a 5 hour drive through the DSL ended. Can you explain the following snippet? 😘

object HostGroup "hg1" { assign where host.check_command == "dummy" }
object HostGroup "hg2" {
  assign where true
//  assign where host.name in Cities
 }

object Host "runtime" {
  check_command = "dummy"
  check_interval = 5s
  retry_interval = 5s

  vars.dummy_text = {{
    var mygroup = "hg2"
    var mylog = "henrik"
  //  var nodes = get_objects(Host).filter(node => mygroup in node.groups)

    f = function (node) use(mygroup, mylog) {
      log(LogCritical, "Filterfunc", mylog+node.name )
      return mygroup in node.groups
    }
    var nodes = get_objects(Host).filter(f)

    var nodenames = nodes.map(n => n.name)
    return nodenames.join(",")
   // return Json.encode(nodes.map(n => n.name))
  }}

}

We also did some live coding in the DSL, this is now a new howto on the Icinga community channels: “DSL: Count check plugin usage from service checks“. Maybe we’ll offer an Icinga DSL workshop in the future. This is where I want our trainees become an active part, since it also involves programming knowledge and building the Icinga architecture.

 

Code?

Henrik’s first PR was an isolated request by myself, with executing a check in-memory instead of forking a plugin process. We had drawn lots of pictures already how check execution generally works, including the macro resolver. The first PR approved and merged. What a feeling.

We didn’t stop there – our NETWAYS trainees are working together with creating PRs all over the Icinga project. Henrik had the chance to review a PR from Alex, and also merge it. Slowly granting responsibility and trust is key.

Thanks to trainees asking about this, Icinga 2 now also got a style guide. This includes modern programming techniques such as “auto”, lambda functions and function doc headers shown below.

/**
 * Main interface for notification type to string representation.
 *
 * @param type Notification type enum (int)
 * @return Type as string. Returns empty if not found.
 */
String Notification::NotificationTypeToString(NotificationType type)
{
	auto typeMap = Notification::m_TypeFilterMap;

	auto it = std::find_if(typeMap.begin(), typeMap.end(),
		[&type](const std::pair<String, int>& p) {
			return p.second == type;
	});

	if (it == typeMap.end())
		return Empty;

	return it->first;
}

 

 

Learn and improve

There are many more things in Icinga: The config compiler itself with AST expressions, the newly written network stack including the REST API parts, feature integration with Graphite or Elastic and even more. We’ll cover these topics with future exercises and workshops.

While Henrik is in school, I’m working on Icinga 2.11 with our core team. Thus far, the new release offers improved docs for future trainees and developers:

This also includes evaluating new technologies, writing unit tests and planning code rewrites and/or improvements. Here’s some ideas for future pair programming sessions:

  • Boost.DateTime instead of using C-ish APIs for date and time manipulation. This blocks other ideas with timezones for TimePeriods, etc.
  • DSL methods to print values and retrieve external data
  • Metric enhancements and status endpoints

 

Trainees rock your world

Treat them as colleagues, listen to their questions and see them “grow up”. I admit it, I am sometimes really tired in the evening after talking all day long. On the other day, it makes me smile to see a ready-to-merge pull request or a presentation with own ideas inspired by an old senior dev. This makes me a better person, every day.

I’m looking forward to September with our two new DEV trainees joining our adventure. We are always searching for passionate developers, so why not immediately dive into the above with us? 🙂 Promise, it will be fun with #lifeatnetways and #drageekeksi ❤️

Michael Friedrich
Michael Friedrich
Senior Developer

Michael ist seit vielen Jahren Icinga-Entwickler und hat sich Ende 2012 in das Abenteuer NETWAYS gewagt. Ein Umzug von Wien nach Nürnberg mit der Vorliebe, österreichische Köstlichkeiten zu importieren - so mancher Kollege verzweifelt an den süchtig machenden Dragee-Keksi und der Linzer Torte. Oder schlicht am österreichischen Dialekt der gerne mit Thomas im Büro intensiviert wird ("Jo eh."). Wenn sich Michael mal nicht in der Community helfend meldet, arbeitet er am nächsten LEGO-Projekt oder geniesst...