<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Paolo Gallina on Medium]]></title>
        <description><![CDATA[Stories by Paolo Gallina on Medium]]></description>
        <link>https://medium.com/@paolo.gallina?source=rss-2b8679c5a2b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xcYJpEMjY72q9_8bu85xsA.png</url>
            <title>Stories by Paolo Gallina on Medium</title>
            <link>https://medium.com/@paolo.gallina?source=rss-2b8679c5a2b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:38:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paolo.gallina/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Concurrent Programming: why synchronizing  data access is not enough]]></title>
            <link>https://itnext.io/concurrent-programming-why-synchronizing-data-access-is-not-enough-3b74e999ef7d?source=rss-2b8679c5a2b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b74e999ef7d</guid>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Paolo Gallina]]></dc:creator>
            <pubDate>Sat, 13 Aug 2022 10:00:14 GMT</pubDate>
            <atom:updated>2022-08-16T07:11:12.205Z</atom:updated>
            <content:encoded><![CDATA[<h3>Concurrent Programming: why synchronizing data access is not enough</h3><p>Synchronizing data access solves many challenges of concurrent programming. If correctly y implemented, you can be sure that only a workstream at a time is allowed to work on a shared portion of code.</p><p>On the other hand, a common issue is to forget that raw data (a variable, an attribute/field, an object, etc.) is not the only data you have to synchronize the access to.</p><h3>The pitfall</h3><p>Data retrieved or computed thanks to shared objects can be invalidated by a different thread/process before you use it hiding subtle bugs. For example, with mutexes you should keep the lock on the shared data as long as you want any decision, you made thanks to the shared data, to remain valid.</p><blockquote>As soon as you release an exclusive lock, everything retrieved or computed thanks to shared data could be no longer valid</blockquote><h4>Scenario</h4><blockquote>The following code shows a dummy example of the issue and how to reproduce it in <a href="https://gobyexample.com/mutexes"><em>Golang</em> with <em>mutexes</em></a>, but you could face the same for example in <em>Java</em> with <em>synchronized methods</em>.</blockquote><p>Having five Goroutines simultaneously increasing a single counter leads to issues if not synchronized. With mutexes, you can force to have only one Gorouting at a time to act on the counter value and shield yourself from unexpected behaviors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*hafqG_2z2t40Va5DB_L7ug.png" /></figure><p>On the other hand, you cannot rely on any information retrieved checking the value of the counter even if the data access was always synchronized with mutexes.</p><p>As soon as you release the mutex any decision made thanks to the data is now outdated and misleading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*4dVaZPK1KRRsLEF5WiBCYg.png" /></figure><p>Even if there is no other Goroutine that can access directlyokToIncrease, it is possible that such variable is invalid right after is computed.</p><pre><strong>if </strong>okToIncrease := d.isSafeToIncrease(); okToIncrease{<br>   d.increase()<br>}</pre><p>Therefore, even if both methodsisSafeToIncrease and increase leverages mutexes to access the counter, as soon as you enter in the if statement the Goroutine could be paused and when resumed you are exposed to the risk of an overflow.</p><p>This is because the locking mechanism is implemented at the wrong level ignoring how the data is used and that we should “lock” as well the decision we took.</p><h3>The code</h3><blockquote>You can check out the code example <a href="https://github.com/paologallinaharbur/concurrency">here</a></blockquote><p>Having for example a shared counter with a mutex to synchronize the access from different Goroutines:</p><pre><strong>const <em>maxCounter </em></strong>= 10<br><br><strong>type </strong>data <strong>struct </strong>{<br>   m       sync.Mutex<br>   counter int<br>}<br><br><strong>func </strong>(d *data) isSafeToIncrease() bool {<br>   d.m.Lock()<br>   <strong>defer </strong>d.m.Unlock()<br><br>   <strong>return </strong>d.counter &lt; <strong><em>maxCounter<br></em></strong>}<br><br><strong>func </strong>(d *data) increase() {<br>   d.m.Lock()<br>   <strong>defer </strong>d.m.Unlock()<br><br>   d.counter += 1<br>}</pre><p>We can test the counter and notice that everything seems to be working as expected. The value of the counter seems to be respecting the maxCounter and that no overflow can occur.</p><pre><strong>func </strong>TestExample(t *testing.T) {</pre><pre>   d := &amp;data{<br>      m: sync.Mutex{},<br>   }<br><br>   wg := &amp;sync.WaitGroup{}<br><br>   wg.Add(2)<br>   <strong>go </strong>increaseNTimes(wg, d, 10)<br>   <strong>go </strong>increaseNTimes(wg, d, 10)<br>   wg.Wait()<br><br>   require.Equal(t, <strong><em>maxCounter</em></strong>, d.getCounter())<br>}</pre><pre><strong>func </strong>increaseNTimes(wg *sync.WaitGroup, d *data, n int) {<br>   <strong>defer </strong>wg.Done()<br><br>   <strong>for </strong>i := 0; i &lt; n; i++ {<br>      <strong>if </strong>d.isSafeToIncrease() {<br>         d.increase()<br>      }<br><br>   }<br>   <strong>return<br></strong>}</pre><p>However, if we run the same test 1000 times we can see it fails on average 1% of the time. The bug it is had to spot since it is a data race that can happen merely in the last iteration. Having a higher <em>maxCounter would decrease further the occurrences of the bug.</em></p><pre><strong>func </strong>TestExample1000Times(t *testing.T) {<br>   <strong>for </strong>i := 0; i &lt; 1000; i++ {<br>      t.Run(fmt.Sprint(i), TestExample)<br>   }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSMRtTILSweBZsDtr6qZ8g.png" /><figcaption>10 out of 1000 executions failed and caused an overflow of the counter</figcaption></figure><p>In this case, the solution is obvious, but in large codebases the bug could be way more complex to spot and fix without locking a large portion of code.</p><pre>d.m.Lock()<br><strong>defer </strong>d.m.Unlock()<br><br><strong>if </strong>d.counter &lt; <strong><em>maxCounter </em></strong>{<br>   d.counter += 1<br>}</pre><p><a href="https://www.youtube.com/watch?v=oV9rvDllKEg&amp;t=47s">https://www.youtube.com/watch?v=oV9rvDllKEg]</a></p><h4>Takeaways</h4><p>In a large and complex codebase it could be a tricky bug to spot. <br>Be aware of it, especially whenever you are refactoring reducing the size of methods to respect the SRP (Single Responsibility Principle) you might be tempted to reduce excessively the scope of mutexes. <br>I reviewed several perfectly structured and well-designed code challenges still falling for this.</p><ul><li>raw data (a variable, an attribute/field, an object, etc) is not the only data you have to synchronize the access to.</li><li>As soon as you release an exclusive lock, everything retrieved or computed thanks to shared data could be no longer valid</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b74e999ef7d" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/concurrent-programming-why-synchronizing-data-access-is-not-enough-3b74e999ef7d">Concurrent Programming: why synchronizing  data access is not enough</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Releasing Helm Charts maintaining your mental health]]></title>
            <link>https://medium.com/@paolo.gallina/releasing-helm-charts-maintaining-your-mental-health-b382685390c8?source=rss-2b8679c5a2b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b382685390c8</guid>
            <category><![CDATA[helm-chart]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[helm]]></category>
            <dc:creator><![CDATA[Paolo Gallina]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 18:19:02 GMT</pubDate>
            <atom:updated>2022-02-28T16:02:59.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>How-to release Helm Charts maintaining your mental health</h3><h4>Three tips for maintaining and developing Helm charts</h4><p>If you work with Helm, or even worse you maintain a chart, you will understand <em>why</em> I love and hate Helm almost equally.</p><p>However, this feeling shift towards 100% rage when I have to introduce a breaking change making sure that for ( the 10000+ ) users the upgrade process is as painless as possible.</p><blockquote>Anyone can keep the Helm when the sea is calm.</blockquote><p>I’ll show you briefly the three things that helped me survive this kind of scenarios keeping my rage below 70% along the way.</p><h3>Helm Unit testing</h3><p>I guess that now you are thinking:</p><blockquote>Is there a way to create unit tests and I am not leveraging it???</blockquote><p>Don’t worry. I had the same feeling some months ago — just before entering in a cave starting to write unit tests for all the charts I was maintaining —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mVcRQkbHNZ0pCI30" /></figure><p>The <em>good news </em>is that it is what you always craved for: it is easy to be used, it is powerful, it is flexible and it is idiomatic <em>(not really sure about that, but it was really cool saying it)</em>.</p><p>The bad news is that the community is fragmented among three different plugins all forked from the same discontinued project.</p><p>However, my favourite one is <a href="https://github.com/quintush/helm-unittest">helm-unittest</a>.</p><p>You can tests and assert a lot of different things: chart errors, the number of files documents generated, the arrays’ length, etc.</p><p>Tests looks like the following and are easy to be understood:</p><pre>suite: test deployment<br>templates:<br>  - deployment.yaml<br>tests:<br>  - it: should work<br>    set:<br>      image.tag: latest<br>    asserts:<br>      - isKind:<br>          of: Deployment<br>      - matchRegex:<br>          path: metadata.name<br>          pattern: -my-chart$<br>      - equal:<br>          path: spec.template.spec.containers[0].image<br>          value: nginx:latest</pre><p>Installation and running tests is, as well, straightforward:</p><pre>helm plugin install https://github.com/quintush/helm-unittest<br>helm unittest ./charts/my-incredible-chart -3</pre><blockquote>Please do yourself a favour, just test any logic or “YAML programming” present in your chart.</blockquote><h3>Dealing with breaking changes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PDEUjr0_SgXuYVO8" /></figure><p>When you need to rename a <em>value,</em> the solution is simple and there is no need to introduce a breaking change: map old “<em>values</em>” to the new ones with an <em>_helper</em> function.</p><p>Something like the following is really basic, but you can do whatever you want if you need something more complex.</p><p>It returns the new value if available, otherwise it falls back on the legacy one if provided.</p><pre>{{- define &quot;compatibility.valueWithFallback&quot; -}}<br>{{- if .supported }}<br>{{- toYaml .supported}}<br>{{- else if .legacy -}}<br>{{- toYaml .legacy}}<br>{{- end }}<br>{{- end -}}</pre><p>However, sometimes it is not possible to do that due to a completely different logic and there is only one solution: f<em>ail as soon as possible</em>.</p><p>What would you prefer being an user of your chart?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*40kdG8IT3jm-uS3Y" /></figure><p><em>A smooth installation..</em> hiding that what you installed it is not doing what you intended, since an old value is not taken into account.</p><p><em>A failing installation..</em> providing in an error message the explanation of why a value cannot be used anymore</p><p>I you would choose the second, then you can do the following adding all the deprecated values you want to fail for and if they are provided you fail:</p><pre>{{ $errors:= &quot;\n&quot; }}<br><br>{{- if .Values.deprecatedValue }}<br>{{ $text:= (include &quot;compatibility.deprecatedValue&quot; . ) }}<br>{{ $errors = printf &quot;%s\n\n%s&quot; $errors $text }}<br>{{- end }}</pre><pre>[...]</pre><pre>{{- if $errors | trim}}<br>{{- fail $errors }}<br>{{- end }}</pre><p>The output will be like depending on the text function:</p><pre>Error: UPGRADE FAILED: execution error at (awesomeExample/templates/NOTES.txt:119:4):</pre><pre>The `deprecatedValue` option is no longer supported and has been replaced by superCoolNewOne.</pre><p>Obviously, you should just print a warning for values that can be safely ignored.</p><h3>Create Beta, Alpha, release candidates charts</h3><p>This is obvious, but you would be surprised that we did not consider to do it in the first place when we had to introduce our first breaking change.</p><blockquote>Why?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fsgo4WwqQeTuCHmt" /></figure><p>The answer is simple: <em>Helm Docs.</em></p><p>Maybe the document I was looking for is there, but I have never found a real guide or explanation of the chart release process.</p><p>Dealing with beta, alpha charts is fully supported, but a bit hidden and not well documented. <br>The only real explanation I found was hidden in the helper of the “--devel” flag supported by almost each command.</p><pre>use development versions, too. Equivalent to version &#39;&gt;0.0.0-0&#39;. If --version is set, this is ignored</pre><p>It works as you would imagine and maybe this is why once you know about its existence you do not need anything else. <br>Just tag a version with 0.0.0-something and it will be hidden to anyone not using such flags on pourpose.</p><pre>➜ helm search repo static-gallo-cedrone-repo -l<br>NAME                                 	CHART VERSION	APP VERSION	DESCRIPTION<br>static-gallo-cedrone-repo/fromgotok8s	0.1.0        	           	A Helm chart for Kubernetes<br><br>➜ helm search repo static-gallo-cedrone-repo -l --devel<br>NAME                                 	CHART VERSION	APP VERSION	DESCRIPTION<br>static-gallo-cedrone-repo/fromgotok8s	1.0.0-beta   	           	A Helm chart for Kubernetes<br>static-gallo-cedrone-repo/fromgotok8s	0.3.0-2      	           	A Helm chart for Kubernetes<br>static-gallo-cedrone-repo/fromgotok8s	0.2.0-alfa   	           	A Helm chart for Kubernetes<br>static-gallo-cedrone-repo/fromgotok8s	0.1.0        	           	A Helm chart for Kubernetes</pre><h3>Conclusion</h3><p>I hope you enjoyed it.</p><p>On the other hand, I am still looking for line 12, if you know how to properly debug helm charts, let me know.</p><pre>error converting YAML to JSON: yaml: line 12: could not find expected &#39;:&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3KtmadhVWZNp7GP4" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b382685390c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FromGoToK8s: a complete CI/DI Example]]></title>
            <link>https://medium.com/swlh/fromgotok8s-a-complete-ci-di-example-2ee49dd39f20?source=rss-2b8679c5a2b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ee49dd39f20</guid>
            <category><![CDATA[travis-ci]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Paolo Gallina]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 17:50:08 GMT</pubDate>
            <atom:updated>2020-04-18T11:34:24.261Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leveraging Travis, Docker, GKE, Coveralls, Helm, Snyk to automatize the testing and the release process of a Golang project.</h4><h3>Purpose of the article and disclaimers</h3><p>The goal of this article is to provide a general overview of a complete CI/CD pipeline <strong>skeleton</strong>. It leverages open-source projects and tools free of charge when building and testing public repositories.</p><p><strong>The only tool that is not free is GKE</strong> (Google Kubernetes Engine), leveraged to host the Kubernetes cluster where the project is going to be deployed automatically. Thankfully, Google provides $300 free credit for Google Cloud Platform <a href="https://cloud.google.com/free">new customers</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnapvx3rJ1THeflEu7jDUg.png" /><figcaption>Logos of the different tools mentioned: Golang, GitHub, Snyk, Coveralls, Travis, Docker, Docker Compose, Kubernetes, Helm, Google Cloud Platform, GKE</figcaption></figure><p>Strong Golang knowledge is not a prerequisite and the very same pipeline can be implemented for any programming language.</p><blockquote>The aim is to keep in this first article only a high level view of the project.</blockquote><blockquote>More articles will follow regarding the different components and tools involved. Each one of them will focus and explain how to setup and overcome common issues that can be faced. However, the whole code is already available in the <a href="https://github.com/gallo-cedrone/fromgotok8s">public Github repository</a> and everyone is free to dig into it.</blockquote><h3>Why is essential to have CI/CD in place?</h3><p>Setting up a new project can be challenging and many doubts can come up when starting from scratch. Handing off a project to a different team is way easier when most of the code is well documented, testable by design and covered by meaningful tests.</p><blockquote>Having a strong CI/CD pipeline requires an initial effort, however it greatly pays back in the long run. SaS tools can lower this initial spike and, in many scenarios, do not imply having to lose any functionality.</blockquote><p>A common belief starting a project is that tests can be added during a second phase and the release, still counting a few steps, might be performed manually. However, as soon as your codebase grows, either you have in place automatization or the overhead of such task can seriously damage your agility.</p><blockquote>Most of the tool and patterns can be introduced on a developed project. However, the cost is going to be greater and you will need to rewrite and rethink some parts of the codebase.</blockquote><h3>Which are the different parts involved?</h3><p>Several tools have been leveraged during the development of FromGoToK8s. Keep in mind that each one of them can be replaced and provides the possibility to work with private repositories.</p><p>First of all, we needed <strong>a small app to show all functionalities</strong>. I decided to use Golang to create a micro HTTP server that connects to a service at startup time. The application replies to clients with the service URL that has been called and the status code returned by the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*3n6x1fFg2eQWFGnb37vEMA.png" /></figure><p>The whole code is covered by <strong>unit tests and </strong><a href="https://coveralls.io/github/gallo-cedrone/fromgotok8s"><strong>Coveralls</strong></a> assures that the code coverage does not decrease after a pull request. Moreover, <strong>Docker compose </strong>is used to spin up a service (representing a generic dependency) and the compiled application to run integrations tests.</p><p><strong>Dep </strong>is the dependency management tool used since Snyk supports Go modules only with the CLI. Dependencies are locked and vendored in the repository and tested for <strong>vulnerabilities with </strong><a href="https://snyk.io/"><strong>Snyk</strong></a> during pull requests.<strong> </strong>Moreover, Snyk scans periodically the whole repository and send updates if it detects that any of the dependencies have been compromised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYWwnJpuYvGIvzTnp_yxUg.png" /><figcaption>Snyk report</figcaption></figure><p>A <strong>Makefile in the repo unifies the logic</strong> needed by the most common actions as compiling and running the code. It also includes less common ones as well: creating and pushing the docker image, creating the changelog and adding to helm the chartmuseum repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qr40mGiliyeCiBCyKTjPw.png" /><figcaption>Travis reporting the status of the pipeline triggered by a tag creation</figcaption></figure><p><a href="https://travis-ci.org/github/gallo-cedrone/fromgotok8s"><strong>Travis</strong></a><strong> is the orchestrator</strong> of the whole CI/CD pipeline and it is the main executor of the most important tasks. A .travis file is present in order to organize how the whole project is built, tested and pushed to GKE. When a tag is created, if the pipeline succeeds, Travis publishes the compiled binary and RPM to <a href="https://github.com/gallo-cedrone/fromgotok8s/releases/tag/1.0.1">Github releases</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npFC3BbQ8X4ijL2c3faxWQ.png" /><figcaption>Github release with binary uploaded</figcaption></figure><p>Each one of the images built is pushed to <strong>the Docker Hub</strong>. One image for each one of the branches and tags is kept. Notice that this behavior can be easily changed, for example, to keep an image for each commit.</p><p>The application is deployed to Kubernetes to perform long-running and canary testing. Kubernetes cluster management is simplified thanks to <a href="https://cloud.google.com/"><strong>Google Cloud</strong></a><strong> and in particular GKE.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjGeNKywNncsyIUAWi_UbQ.png" /><figcaption>Deployment generated by the pipeline for the branch master.</figcaption></figure><p>Helm3 is used to deploy the chart to a Kubernetes cluster. The chart hosted in a<strong> static chartmuseum published on </strong><a href="https://pages.github.com/"><strong>GitHub pages</strong></a> available <a href="https://gallo-cedrone.github.io/fromgotok8s/">here</a>.</p><p>Deployments are hosted in a different namespace, one for each branch and tag. Different commits of on the same branch generate deployments coexisting in the same namespace.</p><h4>The workflow in place</h4><p>Pushing the code to a branch, creating a new tag and opening a pull request trigger a Travis job with different parameters in order to customize its behavior. <em>(the commit checked out in case of pull requests is the one that would result from the merge of the two branches)</em></p><p>The pipeline compiles the code, runs unit tests together with integration ones with DockerCompose. If tests have been run successfully, it builds a Docker image having nothing but the binary and pushes it to the docker registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nJ2s0KGUh3hIExDHupIwg.png" /><figcaption>Imaged pushed to Docker Hub by Travis</figcaption></figure><p>Then, such image is deployed through an helm chart hosted in GitHub pages to a staging Kubernetes cluster; each one of the branches, pull requests and tags have their own namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1E5i1mwuXnv63D0tlKcJA.png" /><figcaption>Pod running in GKE</figcaption></figure><p>When a pull request is opened, GitHub displays the status of the checks. It denies the merge if the Travis job failed. The second requirement is that code coverage did not decrease (process managed by <a href="https://coveralls.io/github/gallo-cedrone/fromgotok8s">Coveralls</a>) and that no known vulnerabilities have been introduced(process managed by <a href="https://snyk.io/">Snyk</a>). However, the owners of the repositories still have the right to merge the code if needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CyFJivD806yOSRQ5v7q0Q.png" /><figcaption>Checks result in PR</figcaption></figure><blockquote>Be Ready for new articles, feel free to open PRs on the repository and improve the proposed solution.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWyd7WTEUDkVsBnHbl_6ZQ.png" /></figure><p>Interested in related topics? Check out my old articles:</p><ul><li><a href="https://medium.com/swlh/golang-tips-why-pointers-to-slices-are-useful-and-how-ignoring-them-can-lead-to-tricky-bugs-cac90f72e77b">Golang tips: why pointers to slices are useful and how ignoring them can lead to tricky bugs</a></li><li><a href="https://blog.harbur.io/kubernetes-crd-and-controllers-to-manage-google-cloud-sql-dbs-91b7c1250a64">Kubernetes: CRD and controllers to manage Google Cloud SQL DBs</a></li><li><a href="https://blog.harbur.io/leverage-k8s-crd-and-kubebuilder-to-create-a-telegram-message-resource-8ce8ac329d89">Leverage K8s CRD and Kubebuilder to create a Telegram message resource</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ee49dd39f20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/fromgotok8s-a-complete-ci-di-example-2ee49dd39f20">FromGoToK8s: a complete CI/DI Example</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang tips: why pointers to slices are useful and how ignoring them can lead to tricky bugs]]></title>
            <link>https://medium.com/swlh/golang-tips-why-pointers-to-slices-are-useful-and-how-ignoring-them-can-lead-to-tricky-bugs-cac90f72e77b?source=rss-2b8679c5a2b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cac90f72e77b</guid>
            <category><![CDATA[slice]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Paolo Gallina]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 23:49:52 GMT</pubDate>
            <atom:updated>2020-05-14T09:51:56.758Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pointers to slices: useless or indispensable?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vKJxdzfG5v5-raoD.png" /></figure><h4>Doubt</h4><p>Today while I was working a nice question arose:</p><blockquote>Why in many BuiltIn function and libraries it is common to see as arguments pointers to slices, aren’t slices always passed by reference?</blockquote><p>For example, in the implementation of the api-machinery of Kubernetes we can see<a href="https://github.com/kubernetes/apimachinery/blob/master/pkg/runtime/conversion.go"> a function</a> with the following signature:</p><pre>func Convert_Slice_string_To_string(input *[]string, out *string, s conversion.Scope) error;:</pre><p>, and in the <a href="https://golang.org/pkg/container/heap/">example</a> of the priority queues, we can find again something similar:</p><pre>func (pq *PriorityQueue) Pop() interface{};</pre><blockquote>Aren’t slices already pointers to the underlying data?</blockquote><blockquote>Let’s investigate a bit making use of the <a href="https://play.golang.org/">Go-Playground</a> to test the behaviours of the code reported.</blockquote><blockquote>During the whole explanation, I will make use of the same example: a function that initializes a slice, passes it as an argument to a second function, modifies it, and then prints the slice to verify the content.</blockquote><p>It is a common belief that slices are passed by reference, in fact, the following example will print [b,b] and [b,b] even if the slice was initialized to [a,a]since it got modified during the execution of the literal function and the change is visible to the <em>main</em>.</p><pre>func main() {<br>    slice:= []string{&quot;a&quot;,&quot;a&quot;}</pre><pre>    func(slice []string){<br>        slice[0]=&quot;b&quot;;<br>        slice[1]=&quot;b&quot;;<br>        fmt.Print(slice)<br>    }(slice)<br>    fmt.Print(slice) <br>}</pre><p>Making use of pointers leads to the same result, in fact, the following code</p><pre>func main() {<br>    slice:= []string{&quot;a&quot;,&quot;a&quot;}<br> <br>    func(slice *[]string){<br>        (*slice)[0]=&quot;b&quot;;<br>        (*slice)[1]=&quot;b&quot;; <br>        fmt.Print(*slice)<br>    }(&amp;slice)<br>    fmt.Print(slice) <br>}</pre><p>prints again [b,b] and [b,b]. Therefore passing it by pointer looks useless and it seems that the slice gets passed by reference anyway and the content is modified in both cases.</p><blockquote>So… why those functions have that signature?</blockquote><h4><strong>Explanation</strong></h4><p>You can roughly imagine the implementation of the slice as:</p><pre>type sliceHeader struct {<br>    Length        int<br>    Capacity      int<br>    ZerothElement *byte<br>}</pre><p>Passing a slice to a function by value, all the fields are copied and only the data can be modified and accessed from outside through <strong>the copy</strong> of the pointer.</p><p>However, keep in mind that if the pointer is overwritten or modified (due to a copy, an assign, or an append) no change will be visible outside the function, moreover, no change of length or capacity will be visible to the initial function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*Oh6i80UGIPYtBn7j.jpg" /></figure><p>The answer to the questions, then, is simple, but hidden inside the implementation of the slice itself:</p><blockquote>The pointer to a slice is indispensable when the function is going to modify the structure, the size, or the location in memory of the slice and every change should to be visible to those who call the function.</blockquote><p>When we pass a slice to a function as an argument<strong> the values of the slice are passed by reference </strong><em>(since we pass a copy of the pointer)</em><strong>, but all the metadata describing the slice itself are just copies.</strong></p><blockquote>We can modify the data of the slice in the literal function, however if the pointer to the data changes for any reason or the slice metadata is modified, the change can be <strong>partially</strong> <strong>or no visible</strong> at all to the outside function.</blockquote><blockquote>For example, if the slice gets allocated again, a new location of the memory is used; even if the values are the same, the slice points to a new location and therefore no modification of the values will be visible ouside, since the slices are pointing to two different localtions (the pointer in the slice copy got overwritten).</blockquote><p>Therefore the same example, forcing the slice to be allocated again,</p><pre>func main() {<br>    slice:= []string{&quot;a&quot;,&quot;a&quot;}<br> <br>    func(slice []string){<br>        slice= append(slice, &quot;a&quot;)<br>        slice[0]=&quot;b&quot;;<br>        slice[1]=&quot;b&quot;; <br>        fmt.Print(slice)<br>    }(slice)<br>    fmt.Print(slice) <br>}</pre><p>will print [b,b,a] and [a,a]. Moving the <em>append</em> after the manipulation of the slice, we can notice that the behavior is different since the slice got reallocated after the manipulation of the values and the pointer is still pointing to the initial memory address. You can check it with the following code</p><pre>func main() {<br>    slice:= []string{&quot;a&quot;,&quot;a&quot;}<br> <br>    func(slice []string){<br>        slice[0]=&quot;b&quot;;<br>        slice[1]=&quot;b&quot;; <br>        slice= append(slice, &quot;a&quot;)<br>        fmt.Print(slice)<br>    }(slice)<br>    fmt.Print(slice) <br>}</pre><p>that prints [b,b,a] and [b,b] for the reasons just explained.</p><p>This behavior can lead to tricky bugs to be spotted since the result depends on the size of the initial array, for example, the following code</p><pre>func main() {<br>    slice:= make([]string, 2, 3) <br>    func(slice []string){        <br>        slice= append(slice, &quot;a&quot;)        <br>        slice[0]=&quot;b&quot;;<br>        slice[1]=&quot;b&quot;; <br>        fmt.Print(slice)<br>    }(slice)<br>    fmt.Print(slice) <br>}</pre><p>prints [b,b,a] and [b,b] since the array is not allocated again and the pointer stays the same.</p><p>However appending a string more slice=append(slice, &quot;a&quot;, &quot;a&quot;), the array gets allocated again and the result would be [b,b,a,a] and [ ] ( an empty array since it was not initialized).</p><blockquote>To spot this kind of bugs in the middle of hundreds or thousands of lines can be quite difficult.</blockquote><blockquote>Therefore make sure to keep in mind that you can pass a slice by value if you want to modify merely the values of the elements, not their number or position, otherwise weird bugs will arise from time to time.</blockquote><p><strong>Now you are ready to understand which is the result of the following snippet of code</strong>, check the answer in the Golang playground or write it in the comments:</p><pre>func main() {<br>    slice:= make([]string, 1, 3)<br>  <br>    func(slice []string){<br>        slice=slice[1:3]<br>        slice[0]=&quot;b&quot;<br>        slice[1]=&quot;b&quot;<br>        fmt.Print(len(slice))<br>        fmt.Print(slice)<br>    }(slice)<br>    fmt.Print(len(slice)) <br>    fmt.Print(slice)<br>}</pre><p>Further reads:</p><ul><li><a href="https://blog.golang.org/go-slices-usage-and-internals">Go Slices: usage and internals</a></li><li><a href="https://blog.golang.org/slices">Arrays, slices (and strings): The mechanics of ‘append’</a></li></ul><p>My previous articles:</p><ul><li><a href="https://medium.com/@paolo.gallina/kubernetes-crd-and-controllers-to-manage-google-cloud-sql-dbs-91b7c1250a64">Kubernetes Example: leverage CRD to provision Google Cloud SQL DBs on demand</a></li><li><a href="https://blog.harbur.io/leverage-k8s-crd-and-kubebuilder-to-create-a-telegram-message-resource-8ce8ac329d89">Leveraging K8s CRDs &amp; Kubebuilder to create a Telegram message resource.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cac90f72e77b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/golang-tips-why-pointers-to-slices-are-useful-and-how-ignoring-them-can-lead-to-tricky-bugs-cac90f72e77b">Golang tips: why pointers to slices are useful and how ignoring them can lead to tricky bugs</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes: CRD and controllers to manage Google Cloud SQL DBs]]></title>
            <link>https://medium.com/harbur/kubernetes-crd-and-controllers-to-manage-google-cloud-sql-dbs-91b7c1250a64?source=rss-2b8679c5a2b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/91b7c1250a64</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[crd]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Paolo Gallina]]></dc:creator>
            <pubDate>Mon, 05 Aug 2019 17:11:11 GMT</pubDate>
            <atom:updated>2019-08-26T08:56:26.558Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes Example: leverage CRD to provision Google Cloud SQL DBs on demand</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*aTcgDW31cTDsnaGkI01ISg.jpeg" /></figure><p>The aim is to <em>implement</em> a controller to automatically provision a SQL database managed by Google Cloud to deployment when a user adds a specific annotation to a Deployment and delete it when it is no longer needed.</p><p>Moreover, the controller should automatically inject into the Pod belonging to the deployment the information needed to connect to the database, such as the IP of the instance, user and passwords.</p><p>The controller will take care of handling correctly passwords storing them in a Secret whose life cycle will be bond to the DB itself.</p><p>The solution is scalable and extendable, for example, at some point we could add a different cloud provider simply by adding a new cloud API layer. <em>(Take into consideration to improve the controller adding support for a new annotation `dbbroker-cloud-provider: AWS` to implement hybrid cloud. Create a PR and let’s discuss it).</em></p><blockquote>Difficulty: Medium — Time required: 30 minutes — Author: Paolo Gallina</blockquote><h3>Ingredients:</h3><ul><li>A running Kubernetes cluster, if you do not have one available, <a href="https://kubernetes.io/docs/setup/learning-environment/minikube/"><em>minikube</em></a> will work just fine.</li><li>A Google Cloud Project, if you don’t have one spare or you do not want to mess up your production, you can <a href="https://cloud.google.com/free/">always make use of the initial free credit</a>.</li><li>A valid Google Cloud <a href="https://cloud.google.com/iam/docs/creating-managing-service-accounts">service account</a> capable to manage your SQL instances.</li><li><a href="https://book.kubebuilder.io/">Kubebuilder</a> installed if you want to try from scratch or my <a href="https://github.com/paologallinaharbur/dbbroker">code downloaded</a> in your Go folder to directly test the solution.</li><li>Basic understanding of GoLang.</li></ul><p>Moreover, if you do not have any knowledge of controllers and you have never used Kubebuilder, I would recommend you to first check out <a href="https://blog.harbur.io/leverage-k8s-crd-and-kubebuilder-to-create-a-telegram-message-resource-8ce8ac329d89">my previous article</a> that aimed to introduce CRDs, controllers and how to leverage Kubebuilder to get started with them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qYioylzIyf6aRIT1" /></figure><h3>Directions:</h3><p>The task might seem difficult and complex, however, keeping it as simple as possible, we will have to code merely the following three elements:</p><ol><li>A custom resource to represent the DB instance into the cluster linking their lifecycles, I decided to call it <em>dbbroker</em>.</li><li>A controller to manage the reconcile process of the dbbroker object, to create the Db and to inject into the Pod the information needed to connect.</li><li>A controller to span a dbbroker object if a user adds the required annotation and to delete it if removed.</li></ol><p><strong>Reconciliation pattern</strong></p><p>All controllers follow the reconciliation pattern: basically, each time the object is modified the controller check if the status is the expected one given the specifications, if not, it tries to converge the status to the desirable one.</p><blockquote>Reconciler implements interfaces that attempt to reconcile the actual state of the world with the desired one by triggering actions.</blockquote><h4>Code the dbbroker CRD and implement the needed logic</h4><p>The idea is to link the lifecycle of the DB to a CRD called <em>dbbroker</em> in order to hide the complexity of both credential management and of DB creation. To do so we will listen for every change on the dbbroker instances:</p><ul><li>upon creation of the <em>dbbroker,</em> the DB instance will be created as well.</li><li>once the DB object is created we will have to wait till the actual Db instance is up and running to populate the info inside the Pods and set the dbbroker as initialized.</li><li>on deletion, we will garbage collect the resource in the cloud.</li></ul><p>Define the new resource as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f607bcbb1b0a35ffeeab3ee72b5947a/href">https://medium.com/media/3f607bcbb1b0a35ffeeab3ee72b5947a/href</a></iframe><p>To connect to GoogleCloud leverage the<a href="https://godoc.org/google.golang.org/api/sqladmin/v1beta4"> official GO client</a>, that, although it is currently a beta, it is really simple and it is going to be the official way to interact with GCP.<br><br>The authentication with the Google Cloud Platform will be managed by the client out of the box, the only action required from our side is to export an environment variable pointing to a GCP service account token having the cloud SQL admin permissions:</p><pre>export GOOGLE_APPLICATION_CREDENTIALS=&quot;/path/to/MyToken.json</pre><p>Each time a dbbroker instance gets modified this flow is called and in case the status is different from <em>initialized</em> we will call an idempotent function to trigger the creation of the DB.</p><blockquote>Idempotence is the property of certain operations in computer science whereby they can be applied multiple times without changing the result beyond the initial application.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f0f8aa7a129208c2d88efa8d3301b02/href">https://medium.com/media/6f0f8aa7a129208c2d88efa8d3301b02/href</a></iframe><p>Note that for sake of simplicity the specifications are hardcoded. <em>(Why don’t you try to improve the solution making all the fields configurable by annotations? I will be very happy to review any PR going in this direction)</em></p><p>The Root password is generated and injected directly into the instance making use of a secret stored in the same namespace, thus it never leaves the cluster and the namespace. For each dbbroker there will be one DB and one secret, the information stored will be exposed as environment variables in the target Pod.</p><blockquote>The secret is owned by the dbbroker resource, <em>in this way once deleted it will be cleaned automatically </em>and we can forget about it, Kubenetes will manage its lifecycle for us thanks to the OwnerReference.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7ab528812e3c81f20f8a5279aa1a94c/href">https://medium.com/media/b7ab528812e3c81f20f8a5279aa1a94c/href</a></iframe><p>Add also a no-Root user, that should be used during normal operation by the service running into the pod, both username and password should be randomly generated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/511cca16c9b00adfff34c8397882d04c/href">https://medium.com/media/511cca16c9b00adfff34c8397882d04c/href</a></iframe><p>Each time a new DB is created we will have to wait till the instance is up and running and the IP of the endpoint published by Google Cloud.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d41a5f9aa8cbc960a017ae9c541cb8cd/href">https://medium.com/media/d41a5f9aa8cbc960a017ae9c541cb8cd/href</a></iframe><p>The function will try recursively to fetch the IP each time waiting more time. After 10 retries the reconciliation will fail and the process will start from scratch, otherwise, there would be the possibility to incur into a deadlock.</p><p><strong>Populate Information into the deployment<br></strong>Once the Db is up and running all the data needed in order to connect will be known by the controller, however, it still has to pass it to the Pod. So far the passwords are stored into the secret owned by the dbbroker instance and the endpoint and the username are saved into the fields of the status.</p><p>Expose the information into the container as environment variables. To do so, first of all, fetch the deployment by the name and the namespace, information saved into the dbbroker specs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2430da720a673be5bae50f8f31040db4/href">https://medium.com/media/2430da720a673be5bae50f8f31040db4/href</a></iframe><p>The core of the logic of the last snippet is the function <em>checkIfInfoMissingAndPopulate</em>. It takes as argument the pointer to the specs of the first container of the deployment and if the information is not injected, it populates them and returns <em>true</em> to trigger the update of the deployment.</p><p>An example of how to inject an environment variable taking the values from a secret and from the status of the dbbroker instance follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfe28c08796037c2f546ab8d42511098/href">https://medium.com/media/cfe28c08796037c2f546ab8d42511098/href</a></iframe><p><em>(Consider to improve the solution giving the possibility to the user to choose in which container to inject credentials: 0,1,.., all of them)</em></p><h4>DeleteOldDb</h4><p>Keep in mind that the dbbroker CR is totally managed, it should be created and deleted automatically: <strong>the user should never act directly on the DB or on the resource owned by it</strong>. Therefore the deletion of the resource will be triggered in a normal scenario merely by the controller once the annotation `<em>dbbroker-db-required:true`</em> is removed or the deployment deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ywPA0kkVT4WhoYho" /></figure><p>In order to avoid a proliferation of old unused DBs (that will affect our GCP bill at the end of the month) we should make sure to get rid of the DBs once the dbbroker resource is deleted:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf12624f8c4a0b4c4c7f514b9185f64f/href">https://medium.com/media/cf12624f8c4a0b4c4c7f514b9185f64f/href</a></iframe><p>As we stated already the Secret will be garbaged collected by Kubernetes and we can forget about it.</p><p><strong>Creation of dbbroker instance</strong></p><p>If you arrived till this point, then from the beginning you have for sure one question in your mind: “<em>who is creating the dbbroker instance in the first place?</em>”</p><p>— A new controller, of course!</p><p>This time the controller is not listening on changes on the dbbroker but on all the deployments of our cluster, if needed, we can restrict the behavior for the sake of performances or due to security concerns.</p><p>We have again our reconciliation flow:</p><ul><li>when the annotation is spotted we trigger the creation of the DB if not already present. The DB will be called deploymentName-randomstring since in the Google Cloud Platform, unluckily we cannot recreate a DB having the same name without waiting some time</li><li>if the DB is already present we check if any info is missing, if so, we fetch them from the dbbroker instance and the secret.</li><li>If the annotation is removed we delete the dbbroker instance and clean the Pod environment variables from the Specs.</li></ul><p>Once again the dbbroker will be owned by the deployment thanks to the OwnerReferences, if someone deletes the deployment, then the dbbroker is deleted and the secret as well on cascade delete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2389ca9bcab78a57eb566a1580d697/href">https://medium.com/media/5d2389ca9bcab78a57eb566a1580d697/href</a></iframe><p>The creation of the dbbroker can be implemented as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ae39233c8e30454877b532b07af72a/href">https://medium.com/media/10ae39233c8e30454877b532b07af72a/href</a></iframe><p>Notice that we added a label to the dbbroker instance in order to fetch it through a <em>getList</em> without knowing its actual name since it has been partially randomly generated.</p><p><strong>DEMO</strong></p><p>Remember to export all the needed environment variables before running the controller and to add in the config/config.yaml the id of your google cloud project:</p><pre>➜ export GOOGLE_APPLICATION_CREDENTIALS = ”/users/paologallina/Downloads/yourToken.json”<br>➜ GOPATH = $HOME/go<br>➜ make; make install; make run</pre><p>Let’s create a simple deployment with the annotation, it will trigger the creation of all the resources:</p><pre> apiVersion: extensions/v1beta1<br> kind: Deployment<br> metadata:<br> annotations:<br> dbbroker: managed<br> dbbroker-db-required: ‘true’<br>...</pre><p>The controller is triggered and the dbbroker created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3msqfL2m3p50tarIfpaudw.png" /></figure><p>The dbbroker has been created, check form the status if it has been initialized already and notice its owner from the specs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvGy7-yc4ZvWX-rxCZSsFQ.png" /></figure><p>The secret as well has been created, therefore we can check the deployment looking for the injected information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLlzIKfsepIfz0aJKUtKvg.png" /></figure><p>The deployment Specs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*ECbOyts-9lsxn3O0eMwhbg.png" /></figure><p>If we exec into the pod we will notice all the environment variables already available to any process running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efJFH38b3aLOpXD5yVwC0w.png" /></figure><p>The last step is to check out the Google Console and, <em>YES,</em> here it is the DB!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YcvJ3CvfqSTQcoeKHe2nA.png" /></figure><p>Let’s try to clean out the DB, removing the annotation or simply by getting rid of the deployment itself.</p><pre>➜ dbbroker git:(master) ✗ kubectl delete deployment nginx<br>deployment.extensions “nginx” deleted</pre><pre>➜ dbbroker git:(master) ✗ kubuectl get secrets<br>zsh: command not found: kubuectl</pre><pre>➜ dbbroker git:(master) ✗ kubectl get secrets<br>NAME TYPE DATA AGE<br>default-token-nkljh kubernetes.io/service-account-token 3 38d</pre><p>Everything got deleted, as expected, in our GCP project as well!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CK7IpdVWK73iNJBHCiAbVA.png" /></figure><h4>Disclaimer</h4><p>For the sake of readability, the code shown is not <em>always </em>the one actually used inside the controller, some error checks are taken away and some parts collapsed, please check the full implementation <a href="https://github.com/paologallinaharbur/dbbroker">here</a>.</p><p>The solution has been developed not to be deployed in a production environment, but merely to show some of the most common patterns.</p><p>In the future, a video Demo will be added to the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KfqwqCFA-56Zom9S" /></figure><h4>Additional tool used</h4><ul><li><a href="https://github.com/spf13/viper">Viper</a> to deal with configuration</li><li><a href="https://www.jetbrains.com/go/">Goland</a> as IDE</li><li><a href="https://blog.harbur.io/leverage-k8s-crd-and-kubebuilder-to-create-a-telegram-message-resource-8ce8ac329d89">My previous article</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91b7c1250a64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/harbur/kubernetes-crd-and-controllers-to-manage-google-cloud-sql-dbs-91b7c1250a64">Kubernetes: CRD and controllers to manage Google Cloud SQL DBs</a> was originally published in <a href="https://medium.com/harbur">Harbur Cloud Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leverage K8s CRD and Kubebuilder to create a Telegram message resource.]]></title>
            <link>https://medium.com/harbur/leverage-k8s-crd-and-kubebuilder-to-create-a-telegram-message-resource-8ce8ac329d89?source=rss-2b8679c5a2b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ce8ac329d89</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[kubernetes-engine]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Paolo Gallina]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 19:31:35 GMT</pubDate>
            <atom:updated>2019-02-22T11:46:56.588Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leveraging K8s CRDs &amp; Kubebuilder to create a Telegram message resource.</h3><blockquote>Do you find introductions boring?<a href="#d602"> Jump to to the demo session</a>!</blockquote><p>Kubernetes comes shipped with several highly configurable resources and APIs that cover the majority of the use cases and scenarios. However, <strong>its real power is a design that, not only allows users to extend its functionality, but also makes it as easy as possible.</strong></p><p>Many companies are taking advantage of this particular design in order to build their open or proprietary solutions, providing new approaches to issues that are not general enough and therefore would hardly find a place inside Kubernetes itself.</p><p>The open source community, on the other hand, is creating hundreds of projects extending Kubernetes APIs to cover new use cases and to prototype implementation of functionalities aiming to be added to the official APIs in the future.</p><p>Just to have an idea, check out the approach of <a href="https://istio.io/">istio.io</a> or the Kubernetes <a href="https://www.aquasec.com/products/aqua-container-security-platform/">Aquasec</a> implementation or the prototyping done by Tomas Smetana in the following video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfnSNPgwXcUc%3Fstart%3D1%26feature%3Doembed%26start%3D1&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfnSNPgwXcUc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfnSNPgwXcUc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b729ac6fe72722599e577e7f9d395377/href">https://medium.com/media/b729ac6fe72722599e577e7f9d395377/href</a></iframe><blockquote>Choose the right tool with the right approach</blockquote><p>Currently, there are two different ways to create Custom Resources, characterized by different scopes and learning curves: <em>CRD with custom controllers</em> and <em>API Aggregation. </em><a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/">Here</a><em> </em>you can find<em> </em>a very useful comparison from the official documentation that can guide you to make your choice.</p><p>Today we check the “straightforward” approach making use of CRDs and custom controllers. We are going to leverage a tool called <a href="https://github.com/kubernetes-sigs/kubebuilder">Kubebuilder</a> to automatically generate the folder structure needed and to introduce additional layers of abstraction that save you the task of taking care of the controller queue and maintaining Lister and Client referenced.</p><p>We use Kubebuilder, but keep in mind that there are different methodologies to implement <em>CRDs and custom controllers</em>: check for example the <a href="https://itnext.io/under-the-hood-of-kubebuilder-framework-ff6b38c10796">comparison</a> with the <em>start from scratch</em> approach and an <a href="https://itnext.io/under-the-hood-of-the-operator-sdk-eebc8fdeebbf">additional one</a> covering <em>operator SDK</em>.</p><p>The objective is to create a CRD for a TelegramMessage resource and a controller that, upon detecting a new resource or an update, will be in charge of delivering the message through a Telegram Bot to a channel or a chat.</p><p>This short demo <strong>obviously</strong> does not claim to show any best practices regarding extra cluster communication and does not cover essential aspects such as security or performances.</p><blockquote>Demo Session</blockquote><p>The starting point is having kubebuilder installed and a single node of a <em>minikube</em> cluster running. Moreover, please notice that the whole code is available <a href="https://github.com/paologallinaharbur/k8s-CRD-TelegramMessage-kubebuilder">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m2YdFWI98LC9kMIa" /></figure><p>By leveraging kubebuilder we can easily create a collection of files that will serve as a starting point to implement our CR and the relative controller. Basically, we need a CRD implementing and validating our new resource and a controller to manage its lifecycle once created. In this demo, I’ve chosen myself as the owner and my <a href="https://harbur.io/">company</a> as the domain, and the new resource implemented will be called TelegramMessage.</p><p>Let’s run the required commands:</p><pre>$ kubebuilder init --domain harbur.io --license apache2 --owner &quot;Paolo.Gallina&quot;</pre><pre>$ kubebuilder create api --group harbur --version v1beta1 --kind TelegramMessage </pre><p>Kubebuilder automatically populates your working directory with a structure of files and folders. The main ones are the following:</p><ol><li>The cmd/... package contains the manager main program. The manager is responsible for initializing shared dependencies and starting/stopping Controllers. Users typically will not need to edit this package and can rely on the scaffolding.</li><li>The pkg/apis/... packages contain the API resource definitions. Users have to edit the *_types.go files under this director to implement their API definitions. Each resource lives in a similar file.</li><li>The pkg/controller/... packages contain the Controller implementations. Users have to edit the *_controller.go files under this directory to implement their Controllers.</li><li>The bin/ folder that once the code is compiled will contain the binaries of the controllers</li></ol><p>One of the core elements is the <strong>go definition of our new resource</strong> that the controller, once created, will have to manage. In our case, the resource is defined in telegram_message.go and we need to modify it to reach our goal, for example as follow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55b237b5489114c1822e5033ade437f4/href">https://medium.com/media/55b237b5489114c1822e5033ade437f4/href</a></iframe><p>Our TelegramMessage Struct is composed of two subStructs: one representing the message <em>specifications</em> defined by the user and, the other, its <em>status</em> populated by the controller. Please, note that the CRD with the corresponding validation fields will be generated automatically by kubebuilder. We added also as fields the token and the chatID in order to support multiple chats and bots at the same time: different instances can trigger messages to different bot/chats.</p><p>The most complex part is building the <strong>controller of the new resource</strong>. However, since this is just a proof of concept, I will keep it as simple as possible. We are interested in a controller that sends the message using the Telegram APIs when a new resource is created or modified or if, for some reason, the message is still not sent. In particular, we need to modify the Reconcile function that, as the documentation states:</p><p><em>“reads that state of the cluster for a TelegramMessage object and makes changes based on the state read and what is in the TelegramMessage.Spec”</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/085e24030e88f4912fa3278d41f91db6/href">https://medium.com/media/085e24030e88f4912fa3278d41f91db6/href</a></iframe><p>First of all, we fetch the current status of the resource by using the *ReconcileTelegramMessage r, saving it in a variable calledinstance. A function sending the message using the Telegram APIs is triggered when the Status.Delivered = No and when the current Spec.MessageToDeliver is different from the one sent previously, i.e. MessageDelivered. The encoded message is sent through an HTTP Post that uses the Bot token and ChatID as parameters.</p><p>In this release, a change of chatID or token will not trigger sending any message in order to make the demo simpler and the code more understandable. However, it can be introduced easily by adding an additional field in the status, for example, a hash of the Message, the chatID, and the token triggering the APIs in case any of those fields is changed. I decided also, for the sake of simplicity, to skip the creation of automatic tests for both, the resource and the controller, leaving a return true instead, even though <strong>this is not the best practice</strong>.</p><blockquote><em>Let’s verify now if the controller is working.</em></blockquote><p>To do so, we pass the CRD to the cluster and we run the controller locally:</p><pre>$ make; make install; make run</pre><p>These three commands create and install the CRD in the cluster, build the code and run the binary of the controller. We can check that everything is ok by retrieving the APIs currently supported by the cluster through kubectl api-version, which shows us (also) harbur.harbur.io/v1beta1.</p><p>Let’s test now the controller by creating a TelegramMessage object:</p><pre>$ kubectl apply -f config/samples/test.yaml</pre><p>, where test.yaml is a classical YAML file with the following structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffa8631b508214a44c42eaea6b7a6cc4/href">https://medium.com/media/ffa8631b508214a44c42eaea6b7a6cc4/href</a></iframe><p>If we look at the logs of the controller in our terminal, we visualize:</p><pre>10:52:31 Checking status of resource test<br>10:52:31 Sending message Hello Medium<br>10:52:32 Checking status of resource test</pre><p>Now it is time to check if the bot has sent the message to the specified chatID and <em>yes</em>, it worked!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*In9ayo8cMu1Dv5kThBGp1g.png" /></figure><p><em>If you are wondering how you can create a TelegramBot, get the relative token and retrieve a chatID, you can check the following resources:</em></p><ul><li><em>Startup guide: </em><a href="https://core.telegram.org/bots"><em>https://core.telegram.org/bots</em></a></li><li><em>ChatID: </em><a href="https://api.telegram.org/botYourBOTToken-/getUpdates"><em>https://api.telegram.org/bot&lt;YourBOTToken&gt;/getUpdates</em></a></li></ul><p><em>Just a spoiler: to create a bot you have to talk with the botFather, which is the father of all the bots. No kidding!</em></p><p>Let’s describe the resource to verify if it has been created correctly and if its status has been populated by the controller:</p><pre>Name: test<br>Namespace: default<br>Labels: sdfffcontroller-tools.k8s.io=1.0<br>Annotations: ...<br>API Version: harbur.harbur.io/v1beta1<br>Kind: TelegramMessage<br>Metadata:<br> Creation Timestamp: ...<br> Generation: 1<br> Resource Version: 133709<br> Self Link: ...<br> UID: ...<br>Spec:<br> Chatid: your-chat-id<br> Messagetodeliver: Hello Medium<br> Token: your-token<br>Status:<br> Delivered: Yes<br> Messagedelivered: Hello Medium<br>Events: &lt;none&gt;</pre><p>Since everything is working, we only need to push the controller into a container and run it in the cluster. Once again, kubebuilder helps us to perform this task:</p><pre>$ make docker-build<br>$ docker tag controller:latest your-repository/controller:latest<br>$ make docker push</pre><p>Let’s modify the controller YAML file by adding the URL of the image which was just pushed into the DockerHub paologallinaharbur/controller:latest as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17d7c09a9ea67d503366c4abe4a36005/href">https://medium.com/media/17d7c09a9ea67d503366c4abe4a36005/href</a></iframe><p>Only one step is missing: deploying the controller into the cluster and starting to use it!</p><pre>$ make deploy<br>$ kubectl apply -f config/samples/test2.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*mo22cUUXhLop_rbxq-ygcA.png" /></figure><blockquote>Message received!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y8oe_P0VqYEynQE8" /></figure><p>Some interesting links:</p><ul><li>to the <a href="https://book.kubebuilder.io/">Kubebuilder</a> gitbook.</li><li>to a <a href="https://itnext.io/under-the-hood-of-kubebuilder-framework-ff6b38c10796">comparison</a> to the start from scratch approach.</li><li>to a <a href="https://itnext.io/under-the-hood-of-the-operator-sdk-eebc8fdeebbf">comparison</a> to the operator SDK approach.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ce8ac329d89" width="1" height="1" alt=""><hr><p><a href="https://medium.com/harbur/leverage-k8s-crd-and-kubebuilder-to-create-a-telegram-message-resource-8ce8ac329d89">Leverage K8s CRD and Kubebuilder to create a Telegram message resource.</a> was originally published in <a href="https://medium.com/harbur">Harbur Cloud Solutions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>