<?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 Carlos Vicens on Medium]]></title>
        <description><![CDATA[Stories by Carlos Vicens on Medium]]></description>
        <link>https://medium.com/@carlos.vicens.alonso?source=rss-15c32cd806ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ysTINaLAxExiei-nYV_rCw.jpeg</url>
            <title>Stories by Carlos Vicens on Medium</title>
            <link>https://medium.com/@carlos.vicens.alonso?source=rss-15c32cd806ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:19:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carlos.vicens.alonso/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[Lab and demo using the new Operator SDK 1.0.0]]></title>
            <link>https://faun.pub/lab-and-demo-using-the-new-operator-sdk-1-0-0-def583f35f2d?source=rss-15c32cd806ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/def583f35f2d</guid>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[operator-sdk]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Carlos Vicens]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 15:10:46 GMT</pubDate>
            <atom:updated>2020-09-16T07:54:51.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*76Xd7NWcZKn0Ynl2IZGqDg.png" /><figcaption>Image by prettysleepy1from Pixabay</figcaption></figure><h4>The Operator Framework XT Edition Lab using the new Operator SDK 1.0.0</h4><p>I know it sounds like a terrible title for an article about Operators, too close to a typical gaming YouTube channel video, but I’m very excited… Why?</p><p>Well, I started developing “demo/dummy” operators for research first, then to answer customers&#39; doubts and guide them through the process of developing operators, and finally because I like the subject. In any case, I started somewhere around February 2019 and since then till some days ago all versions of the Operator SDK were 0.x ... not anymore the Operator SDK 1.0.0 is here and it comes with a lot of changes!.</p><p>For a thorough explanation of those changes, I suggest you to go <a href="https://www.openshift.com/blog/operator-sdk-reaches-v1.0">here</a>.</p><p>Among of those changes I’d like to highlight:</p><ul><li>Makefile including a bunch of useful targets that will make your life easier especially at the beginning.</li><li>Use of kubebuilder to define RBAC rules (role/role binding) which means RBAC is in your Controller code and defined in the same way as validations and Form UI tweaks in Types, etc.</li><li>Operator metadata format now defaults to Bundle instead of PackageManifests</li><li>Use of <a href="https://github.com/kubernetes-sigs/kustomize">kustomize</a> to generate manifests, deployment descriptors, etc.</li></ul><p>So to celebrate v1.0.0 I decided to dust off my Gramola Operator code that I had developed 6 months ago. Ok, ok, not that much dust had settled... ok, again, I wasn&#39;t exactly celebrating I had to migrate my code... But It was very rewarding, I have improved the code, and also it was the best way to see the value of the changes introduced.</p><p><em>Gramola and Gramola Operator</em> you say? Bear with me, it’s just a demo app and the operator to deploy it. An excuse to explain how to develop an operator and upgrade it using the Operator Lifecycle Manager or OLM.</p><p>Gramola is a simple application that shows a list of (musical) Events (hence the name of the app). It comprises:</p><ul><li>frontend: NodeJS/Angular application</li><li>gateway: Quarkus simple API gateway</li><li>events: Quarkus simple API</li><li>events-database: PostgreSQL 10 Database</li></ul><p>The operator deploys all the components, creates tables, Ingress rules or OpenShift Routes, etc. it also upgrades the database schema and migrates data if needed… BUT it’s just a sample operator to, somewhat, open your eyes to the possibilities the Operator Framework offers…</p><p>Here you have a screenshot showing the end result and ultimate goal of the operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UyhwHH48YAkqAJ6X.png" /></figure><p>Nice Carlos… you’re excited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/0*8GJtLnteCzIZDKXL.png" /></figure><p>Ok, ok, TL;DR I guess.</p><h3>TL;DR</h3><p>I’m presenting an end-to-end Operator Framework laboratory and demo guide for Operator SDK 1.0.0 all in the same <a href="https://github.com/atarazana/gramola-operator">repository</a></p><p>The purpose of this repository is twofold:</p><ul><li>Providing a lab guide to create and upgrade an operator from scratch and using the Operator Lifecycle Manager</li><li>Holding the code and demo script of Gramola</li></ul><p>So you can develop your own operator to then deploy it and upgrade it using OLM (for the brave!) or just deploy and upgrade the Gramola Operator (for… also the brave!).</p><p>This guide is divided into two parts.</p><p>In Part One you’ll learn:</p><ol><li>How to create an operator and how to deploy version 0.0.1</li><li>You will also learn how to evolve an operator as we’ll move from version 0.0.1 to 0.0.2.</li><li>And even more importantly how to use the <a href="https://github.com/operator-framework/operator-lifecycle-manager">Operator Lifecycle Manager</a> (OLM) to do all this automatically.</li></ol><blockquote><em>NOTE: In order to make the Part One easier (Gramola is not complicated but it has too many moving parts) we’re going to use the </em><a href="https://sdk.operatorframework.io/docs/building-operators/golang/tutorial/"><em>Golang Based Operator Tutorial</em></a><em> as a base for this lab.</em></blockquote><p>The 2nd part of the guide explains how to run a complete demonstration using the Gramola operator on Kubernetes, no need to code just enjoy deploying and upgrading Gramola.</p><p>How is this guide different to others?</p><ol><li>It shows you how to get it all done from zero to upgrade your operator seamlessly using the Operator Lifecycle Manager.</li><li>It also shows you how to do this with Minikube and OpenShift.</li></ol><h3>Why developing operators in the first place</h3><p>If you’ve arrived here maybe you don’t need any additional motivations… if that’s not the case, then don’t skip this point.</p><p>Operators in general are there to help you <em>to deploy</em> <em>and maintain</em> complex, stateful systems. Some examples:</p><ul><li>DataBases</li><li>Monitoring Systems</li><li>Streaming and Messaging</li><li>Networking, Storage, …</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Dbgb1pk_IKbElCx.png" /></figure><p>Ok, apparently basic systems your applications rely on, not your Apps themselves, because to deploy and maintain your apps you use CI/CD pipelines.</p><p>Well… I think that under some circumstances Operators are (another) very valid options to deploy applications. Let’s have a look at some of those circumstances:</p><ul><li>You deploy complex systems for different branches in your company in Kubernetes clusters in different geolocations… Do your pipelines reach those locations? Or do you use scripts or other means to replicate the state of production in your main (1st) cluster?</li><li>You’re a software vendor and your portfolio (Event Ticketing system, SAP-based XYZ system) can be SaaS or on-premise on top of Kubernetes. You develop a product and use CI/CD pipelines internally but you have to deliver and maintain a product.</li><li>You don’t develop all the custom software you consume. Do this 3rd companies developing for you end their pipelines in your cluster? Or do they use some automation mechanism or even scripts to deploy in production while their CI/CD pipelines are internal?</li></ul><p>My humble opinion is that it makes sense to develop an Operator given these or similar circumstances. Operators contain the logic otherwise scattered between different layers… and they’re Kubernetes native objects.</p><h3>The guide, the code, well all of it</h3><p>You can find it all <a href="https://github.com/atarazana/gramola-operator">here</a>. By the way… maybe you’re wondering (or will wonder later) why in a GitHub organization and not under my user… This is to make all the guides resemble what you would have in your own company, organization. It’s not mandatory to do it like me just make it all look closer to reality.</p><h3>Being grateful first</h3><p>Thanks to <a href="https://github.com/tahonen">Tero Ahonen</a> who pushed me (inadvertently?) to create this.</p><p>Parts of the code of this operator were borrowed from another <a href="https://github.com/mcouliba/openshift-workshop-operator">operator</a> coded by my colleague <a href="https://github.com/mcouliba">Madou Couliba</a>.</p><p><a href="https://github.com/luisarizmendi">Luis Arizmendi</a> was key to start working with OLM, <a href="https://medium.com/@luis.ariz/operator-lifecycle-manager-review-f0885f9f3f1f">here</a> the article that helped me with this subject.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Subscribe to </strong><a href="https://www.faun.dev/join?utm_source=medium.com/faun&amp;utm_medium=medium&amp;utm_campaign=faunmediumprebanner"><strong>FAUN topics</strong></a><strong> and get your weekly curated email of the must-read tech stories, news, and tutorials </strong>🗞️</p><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and </strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷 <strong>and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook</strong></a><strong> and </strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin</strong></a><strong> Groups </strong>💬</p><figure><a href="https://www.faun.dev/join?utm_source=medium.com/faun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cT0_laE4iPcqW1qrbstAg.gif" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def583f35f2d" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/lab-and-demo-using-the-new-operator-sdk-1-0-0-def583f35f2d">Lab and demo using the new Operator SDK 1.0.0</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop an Event Driven Application based on Kafka, Camel K and a Telegram Bot on OpenShift step…]]></title>
            <link>https://faun.pub/develop-an-event-driven-application-based-on-kafka-camel-k-and-a-telegram-bot-on-openshift-step-2d60c94f3f33?source=rss-15c32cd806ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d60c94f3f33</guid>
            <category><![CDATA[camelk]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[telegram]]></category>
            <dc:creator><![CDATA[Carlos Vicens]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 18:29:50 GMT</pubDate>
            <atom:updated>2020-01-17T08:58:12.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YseoTS2bHTgv_2K83xGqig.jpeg" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Knickerbocker_Hospital.jpg">https://commons.wikimedia.org/wiki/File:Knickerbocker_Hospital.jpg</a></figcaption></figure><h3>Develop an Event Driven Application based on Kafka, Camel K and a Telegram bot on OpenShift step by step</h3><h3>Intro</h3><p>Some months ago I started playing with <a href="https://github.com/apache/camel-k">Camel K</a>, I instantly fell in love with it (and I didn’t have any previous experience with Camel), easy to deploy fast development, tons of components, you name it. As it usually happens (not just to me, right ;-) ) we tech people try a new good thing and if we love it… we tend to use it everywhere… ok, that was my case, I started to think of crazy scenarios, but one of them stood out and after some refinement ended up being this project.</p><blockquote><strong><em>NOTE:</em></strong><em> Ideally you will read and do and see results… and (hopefully) learn some basics to create your own EDA (Event Driven Application). This lab is not really about creating everything from scratch but more about having an example project up and running and then exploring possibilities while learning.</em></blockquote><p>You can find the code and this guide <a href="https://github.com/cvicens/state-machine-assistant">here</a></p><h3>The Idea</h3><p>The idea came to me after remembering how many times I had to go with my youngest daughter to the Emergency Room (nothing serious but recurrent) and all those times waiting for results, moving to the next stage and informing my wife (who was with my other daughter). Wouldn’t if be nice to receive a message to my Telegram App every time the state of the patient changes? Well, that’s the aim of this project: serving as an example EDA (Event Driven Application) running on Kubernetes/OpenShift that sends out notifications via a Telegram Bot whenever the state/status of a patient changes.</p><p>In order to give our example EDA a bit more of (fictitious) context, let’s imagine there’s a Health Information System (HIS) at a hospital called Black Mountain Hospital. This application has a UI where you can change the status of a patient and every time a change happens a proper HL7 message is sent.</p><blockquote><strong><em>NOTE:</em></strong><em> this is an over simplified HIS, please health related professionals don’t get too mad at me, I know how complex a real HIS is ;-)</em></blockquote><p>The scenario portrayed by this example application of the fictitious<strong> Black Mountain Hospital</strong> comprises these elements:</p><ul><li><strong>HIS frontend (Angular JS)</strong> where you can change the status of a patient</li><li><strong>HIS backend (Spring Boot REST API)</strong> exposing the patient info API, data is persisted in a PostgreSQL Database. This piece sends out HL7 messages to a Kafka topic</li><li><strong>Integration layer (Camel K)</strong> that translates HL7 events to plain events you can send to a human</li><li><strong>Telegram Bot (Node JS)</strong> where you can signup with your ID, again data is persisted in a PostgreSQL Database</li></ul><h3><strong>Prerequisites</strong></h3><p>You need access to an OpenShift 4.2+ cluster and be cluster-admin (or request your administrator to install a couple of elements for you). You can also run your own local 4.x cluster using <a href="https://code-ready.github.io/crc/">CodeReady Containers</a>.</p><h3><strong>Scope</strong></h3><p>In this guide we’ll cover:</p><ul><li>the deployment of infrastructure elements in OpenShift: databases, kafka cluster, etc.</li><li>local development of UI, services and also the integration layer</li><li>the deployment of services on OpenShift</li></ul><h3><strong>Get yourself ready</strong></h3><p>Git clone this repository and change dir… the usual.</p><h3><strong>Deployment of infrastructure</strong></h3><p>We need to deploy a couple of databases, Kafka and also Camel K… let’s get to it.</p><h4><strong>Deploying Kafka</strong></h4><p>In order to ease the deployment of Kafka we’re going to use the Red Hat AMQ Operator (go <a href="http://red.ht/operators">here</a> to learn more about operators).</p><blockquote><strong><em>WARNING:</em></strong><em> This task should be run by a cluster administrator</em></blockquote><p>Log in as a cluster admin to your cluster and go to Operators-&gt;Operator Hub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sEnLuo7i06Pzq6n-.png" /></figure><p>In the search field start typing amq. Then click on AMQ Streams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oYrau85_dxZMNZxB.png" /></figure><p>Click on Install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*py2g0Eb8fLzF6oOT.png" /></figure><p>Leave the default values and click Subscribe, as you can see we&#39;re going to install the operator so that it&#39;s available to all namespaces. This will allow to use the operator as a normal user in any namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2-WxUu40JWh3wVkt.png" /></figure><p>Wait until Status changes to InstallSucceeded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*acnbsDjAC5GW1zfA.png" /></figure><p>If status is InstallSucceeded you have installed the operator successfully in namespace openshift-operators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9INtkFzJtf6RDMK-.png" /></figure><p>Now you could start creating custom resources managed by the AMQ Streams Operator, such as Kafka, Kafka Connect, etc.</p><h4><strong>Deploying the Camel K Operator</strong></h4><p>As we have explained before we need a couple of Camel integrations; to translate HL7 messages coming in to a Kafka topic and another one to send those translated messages to a Telegram Bot. Well, in order to run this Camel integrations (routes) we can do it manually in a Java project, or use Camel K. For all the reasons mentions before and more we’re going to use an operator the Camel K Operator.</p><blockquote><strong><em>WARNING:</em></strong><em> This task should be run by a cluster administrator</em></blockquote><p>Log in as to your cluster as cluster-admin and go to Operators-&gt;Operator Hub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7_WvedvRE6dSMLp3.png" /></figure><p>In the search field start typing camel. Then click on Camel K.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z4J8sp9xVxEy0jXF.png" /></figure><p>Click on Continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4P9f3KWFI6qn6ORD.png" /></figure><p>Click on Install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ayihaa5efGfM1bY-.png" /></figure><p>Leave the default values and click Subscribe, as you can see we&#39;re going to install the operator so that it&#39;s available to all namespaces. This will allow to use the operator as a normal user in any namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cqFCvIrmypwMR8G-.png" /></figure><p>Wait until Status changes to InstallSucceeded, if that is the case you have installed the operator successfully in namespace openshift-operators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uxGDOwtJJP7TlN-m.png" /></figure><p>Now you could start creating custom resources managed by the Camel K Operator, such as Integration, Build, etc.</p><h4>Deploying Kafka using the AMQ Streams Operator</h4><p>As we mentioned before we need a couple of Topics, one for HL7 events and another one for translated events… and of course we need a Kafka cluster to support them.</p><blockquote><strong><em>NOTE:</em></strong><em> This task and the next ones don’t require special permissions apart from being able to create namespaces, deployments, PODs, etc.</em></blockquote><p>We have prepared a set of numbered shell scripts, please have a look to the one numbered 00 where some base environment variables are set. You may need to change the project name to be sure it&#39;s unique in your cluster...</p><p>Set the environment any time by doing this. Please run the next command, we’ll need to use $PROJECT_NAME environment variable later:</p><p>In this step we will run ./01-deploy-kafka.sh, please have a look to this script, there are a couple of important bits there.</p><p><strong>First</strong>, it creates a project to hold all the elements. Next is the excerpt</p><pre>oc new-project ${PROJECT_NAME}</pre><blockquote><strong>IMPORTANT: </strong><em>if you run the scripts in order (and you don’t create another project in between), the default project will be automatically set to the project create, that is the one set by $PROJECT_NAME environment variable, see </em><em>00-environment.sh. If you have created another project or just want to be sure the default project is set correctly, please use: </em><em>oc project. If you need to set the default project back to $PROJECT_NAME do this: </em><em>. ./00-environment.sh &amp;&amp; oc project $PROJECT_NAME</em></blockquote><p><strong>Second</strong>, it also creates a Custom Resource (CR) of type Kafka that defines a Kafka cluster with 3 replicas, three listeners, plain, secure and https based (external). And a couple of CRs of type KafkaTopic for each of the kafka topics we need.</p><blockquote><strong><em>NOTE 1:</em></strong><em> The </em><em>AMQ Streams Operator reacts to the creation/update/delete of a set of Custom Resource Definitions, go </em><a href="https://access.redhat.com/documentation/en-us/red_hat_amq/7.3/html/using_amq_streams_on_openshift_container_platform/getting-started-str#cluster-operator-str"><em>here</em></a><em> for further details</em></blockquote><blockquote><strong><em>NOTE 2:</em></strong><em> The </em><strong><em>external listener</em></strong><em> is needed only while running the backend logic locally because the kafka cluster is running in OpenShift. In general this external listener is not needed when the logic run in the same cluster as the kafka cluster.</em></blockquote><p>Now please run the script.</p><blockquote><strong><em>WARNING:</em></strong><em> Be sure you’re logged in, if unsure run </em><em>oc whoami</em></blockquote><p>To monitor the status of the deployment you can run the next command.</p><blockquote><em>As you can see, there are 3 replicas both for the kafka cluster and for the zookeeper cluster, all of them are running.</em></blockquote><pre>$ oc get pod -n $PROJECT_NAME | grep state-machine-cluster<br>state-machine-cluster-entity-operator-55d6f79ccf-dckht 3/3 Running 16 5d15h<br>state-machine-cluster-kafka-0     2/2 Running 11 5d15h <br>state-machine-cluster-kafka-1 .   2/2 Running 11 5d15h <br>state-machine-cluster-kafka-2     2/2 Running 11 5d15h<br>state-machine-cluster-zookeeper-0 2/2 Running 8 5d15h<br>state-machine-cluster-zookeeper-1 2/2 Running 8 5d15h<br>state-machine-cluster-zookeeper-2 2/2 Running 8 5d15h</pre><p>Another test you can run, this one to check if our topics were created properly.</p><pre>$ oc rsh -n $PROJECT_NAME state-machine-cluster-kafka-0 bin/kafka-topics.sh --list --bootstrap-server localhost:9092<br>Defaulting container name to kafka.<br>Use &#39;oc describe pod/state-machine-cluster-kafka-0 -n state-machine-assistant&#39; to see all of the containers in this pod.<br>OpenJDK 64-Bit Server VM warning: If the number of processors is expected to increase from one, then you should configure the number of parallel GC threads appropriately using -XX:ParallelGCThreads=N<br>__consumer_offsets<br>events-topic<br>hl7-events-topic</pre><h4><strong>Install Camel K CLI</strong></h4><p>This step is quite easy… it only requires to download the Camel K CLI binary, kamel.</p><p>Please run this script.</p><blockquote><strong><em>NOTE:</em></strong><em> open the script </em><em>00-environment.sh if you want to change the cli version</em></blockquote><pre>./02-install-camel-k-cli.sh</pre><p>This script leaves the kamel binary in the same directory where the script is run... so it&#39;s not in your <em>PATH</em> so be sure to execute it like this ./kamel or add it to you <em>PATH</em>.</p><h4><strong>Deploying the HIS Backend and Telegram Bot databases</strong></h4><p>We’re going to use oc new-app commands to deploy two single node PostgreSQL databases, one for the HIS backend and another one for the Telegram Bot.</p><p>If you have a look to script 03 you&#39;ll find the next couple of commands, these are normal oc new-app commands that create the needed descriptors to run an OCI image centos/postgresql-10-centos7.</p><p>Pay attention to the following:</p><ol><li>We are deploying the same image twice because we need two databases</li><li>The name given to the application is different: backend-database vs telegram-bot-database</li><li>Finally, there are a couple of environment variables that set user and password with the same values for both databases. Yes, not very secure… but remember this is for development purposes</li></ol><pre>oc new-app -e POSTGRESQL_USER=luke \<br>  -ePOSTGRESQL_PASSWORD=secret -ePOSTGRESQL_DATABASE=my_data \<br>  centos/postgresql-10-centos7 --name=backend-database</pre><pre>oc new-app -e POSTGRESQL_USER=luke \<br>  -ePOSTGRESQL_PASSWORD=secret -ePOSTGRESQL_DATABASE=my_data \ <br>  centos/postgresql-10-centos7 --name=telegram-bot-database</pre><p>Now run the script.</p><pre>./03-deploy-databases.sh</pre><p>Check the status of the deployment with this command. Eventually you should see something like this where the status of our database pods is Running, like backend-database-1-ttq2b in this example output.</p><pre>$ oc get pod -n $PROJECT_NAME | grep database<br>backend-database-1-deploy      0/1 Completed 0 5m<br>backend-database-1-ttq2b       1/1 Running   4 4m<br>telegram-bot-database-1-7qv4d  1/1 Running   4 4m<br>telegram-bot-database-1-deploy 0/1 Completed 0 5m</pre><h4>Preparing the development environment</h4><p>One of the goals of the lab is to help you with the local development stage. For instance, regarding the HIS backend, our Spring Boot service (Java) needs to be able to connect to an HTTPS listener, hence you need the root CA certificate related to that listener added as a trusted CA to a keystore.</p><p>To do so, we have prepared this script ./04-prepare-development-env.sh. It basically does the following:</p><p><em>Extracts the root CA cert from a secret</em></p><pre>oc extract secret/${CLUSTER_NAME}-cluster-ca-cert -n ${PROJECT_NAME} --keys=ca.crt --to=- &gt; src/main/resources/ca.crt</pre><p><em>Adds it to a Java Keystore</em></p><pre>$ keytool -delete -alias root -keystore src/main/resources/keystore.jks -storepass password -noprompt<br>$ keytool -import -trustcacerts -alias root -file src/main/resources/ca.crt -keystore src/main/resources/keystore.jks -storepass password -noprompt</pre><p>How does the Spring Boot application know which Keystore use to connect to kafka?</p><p>Well, there’s a class called KafkaConfig that prepares the configuration to connect to Kafka, open file backend/src/main/java/com/redhat/his/service/KafkaConfig.java to see how we use NONE to exclude some properties when running in OpenShift.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8338d07fb2b43829e5de5d86b0272725/href">https://medium.com/media/8338d07fb2b43829e5de5d86b0272725/href</a></iframe><p>Then we have to different profiles default and openshift, so, when developing we use default (application.properties) and when running in OpenShift we use openshift (application-opeshift.properties).</p><p>Next you can find the relevant properties in the default profile.</p><pre># Kafka Bootstrap Servers =&gt; ./06-run-backend.sh sets KAFKA_SERVICE_HOST automatically for local dev.</pre><pre>kafka.bootstrap-servers=${KAFKA_SERVICE_HOST}:443</pre><pre># Client and Group</pre><pre>kafka.clientId  = kafkaClientHisBackend</pre><pre>kafka.groupId   = kafkaHisBackendConsumerGroup</pre><pre># Topics</pre><pre>kafka.topic = hl7-events-topic</pre><pre>kafka.security.protocol = SSL</pre><pre>kafka.ssl.truststore.location = src/main/resources/keystore.jks</pre><pre>kafka.ssl.truststore.password = password</pre><pre>kafka.ssl.keystore.location = src/main/resources/keystore.jks</pre><pre>kafka.ssl.keystore.password = password</pre><p>And this is the openshift profile cuonterpart.</p><pre># Kafka Bootstrap Servers</pre><pre>kafka.bootstrap-servers=state-machine-cluster-kafka-brokers:9092</pre><pre># Client and Group</pre><pre>kafka.clientId  = kafkaClientHisBackend</pre><pre>kafka.groupId   = kafkaHisBackendConsumerGroup</pre><pre># Topics</pre><pre>kafka.topic = hl7-events-topic</pre><pre>kafka.security.protocol = NONE</pre><pre>kafka.ssl.truststore.location = NONE</pre><pre>kafka.ssl.truststore.password = NONE</pre><pre>kafka.ssl.keystore.location = NONE</pre><pre>kafka.ssl.keystore.password = NONE</pre><p>The other thing done by ./04-prepare-development-env.sh is to install all dependencies needed by the Telegram Bot and the HIS Front end, bot Node JS applications.</p><p>Now please run this command.</p><pre>./04-prepare-development-env.sh</pre><h3>Developing our EDA locally</h3><p>So there are 4 pieces we need to be able to run locally first and then move to our OpenShift cluster, namely:</p><ul><li>Telegram Bot</li><li>HIS Backend</li><li>Integrations: HL7 to Events and Events to Telegram Bot</li><li>HIS Frontend</li></ul><p>Let’s run them test them one by one</p><h4>Telegram Bot</h4><p>First you need to use BotFather in order to create you Telegram Bot</p><p>Go to your Telegram App, here we’ll show you haow to do it with the desktop app but it should work in any supported platform.</p><p>Look for BotFather.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OQa1YLfnHhSpex5z.png" /></figure><p>Now create a new bot with /newbot. Just follow the steps, when done you should receive a token, please copy it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vbHdp77XsGMiAyLT.png" /></figure><p>Time to paste this token, open ./05a-run-telegram-bot.sh and paste it when required.</p><blockquote><em>Run this script in an new terminal window. Be aware that it will use </em><em>oc port-forward to open a tunnel with the database running in OpenShift. By the way this script could also work properly completely local if you uncomment the required lines </em><em>Using docker to run a database.</em></blockquote><pre>$ . ./00-environment.sh</pre><pre>$ ./05a-run-telegram-bot.sh</pre><pre>PASTE TOKEN: YOUR_TOKEN</pre><pre>USING TOKEN YOUR_TOKEN</pre><pre>&gt; telegram-bot@1.0.0 start /Users/cvicensa/Projects/openshift/tap/state-machine-assistant/telegram-bot</pre><pre>&gt; node app.js</pre><pre>node-telegram-bot-api deprecated Automatic enabling of cancellation of promises is deprecated.</pre><pre>In the future, you will have to enable it yourself.</pre><pre>See https://github.com/yagop/node-telegram-bot-api/issues/319. internal/modules/cjs/loader.js:959:30</pre><pre>DEV: true</pre><pre>body-parser deprecated bodyParser: use individual json/urlencoded middlewares app.js:21:9</pre><pre>body-parser deprecated undefined extended: provide extended option node_modules/body-parser/index.js:105:29</pre><pre>Health Assistant Bot has started. Start conversations in your Telegram.</pre><pre>Telegram Bot started at: Tue Jan 14 2020 16:06:36 GMT+0100 (Central European Standard Time) on port: 9090</pre><pre>Error: connect ECONNREFUSED 127.0.0.1:5432</pre><pre>at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1129:14) {</pre><pre>errno: &#39;ECONNREFUSED&#39;,</pre><pre>code: &#39;ECONNREFUSED&#39;,</pre><pre>syscall: &#39;connect&#39;,</pre><pre>address: &#39;127.0.0.1&#39;,</pre><pre>port: 5432</pre><pre>}</pre><pre>Forwarding from 127.0.0.1:5432 -&gt; 5432</pre><pre>Forwarding from [::1]:5432 -&gt; 5432</pre><p>Hopefully your Telegram Bot is running in localhost and is connected to PostgreSQL (local or remote). Let’s test it.</p><p>First, open your Telegram App and look for your bot, in our case state machin finds our bot. Second click on START</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MtwEPy8WOp3tflHq.png" /></figure><p>As you can see some help is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c6CJBGKKK4qKOm8W.png" /></figure><p>Create a user (in our case user already existed).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jCF1xfkNXt5SQTIS.png" /></figure><p>Finally send a message and see the result in your Telegram App. Something like Patient JOHN SMITH with ID(PATID1234) has been admitted (ZZZ)</p><pre>./telegram-bot/send-message.sh 9876543210W <a href="http://localhost:9090/">http://localhost:9090</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RzMaWOADB9DlBKPe.png" /></figure><h4><strong>Deploy the Telegram Bot</strong></h4><p>Before we can run the integration layer we need to deploy the Telegram Bot to OpenShift.</p><blockquote><strong><em>INFO:</em></strong><em> This is so, because the integration layer runs in the cluster so it would be required for your local Telegram Bot to be listening in an external IP reachable from the cluster</em></blockquote><p>We’re going to deploy our application using <a href="https://github.com/nodeshift/nodeshift">Nodeshift</a>. Nodeshift helps us deploying our NodeJS application from the command line using <a href="https://github.com/openshift/source-to-image">Source to image</a> behind scenes. in order to do that you have to provide minimal information in the shape of YAML descriptors in a folder named and being logged in to an OpenShift cluster.</p><p>Here’s a list of descriptors already prepared for deploying the Telegram Bot:</p><ul><li><a href="https://github.com/cvicens/state-machine-assistant/blob/master/telegram-bot/.nodeshift/credentials-secret.yml">credentials-secret.yml</a> is a proper k8s Secret object containing the database credentials</li><li><a href="https://github.com/cvicens/state-machine-assistant/blob/master/telegram-bot/.nodeshift/route.yml">route.yml</a> is a fragment of a Route object that routes to the Service object</li><li><a href="https://github.com/cvicens/state-machine-assistant/blob/master/telegram-bot/.nodeshift/deployment.yml">deployment.yml</a> is a fragment of a DeploymentConfig object. You’ll notice that there are some <em>environment variables</em> there <em>for database host</em> (literal, hardcoded), <em>credentials</em> (value comes from the secret mentioned above) and the <em>Telegram token</em> (value refers to a ConfigMap)</li></ul><p>Hmm may be you’ve notice some things are missing here:</p><ul><li><strong>Where’s the ConfigMap to get the token from?</strong> It’ll be created when you run ./05b-deploy-telegram-bot.sh</li><li><strong>Where are the Service, ImageStream, BuildConfig objects?</strong> Those are inferred by Nodeshift along with the missing pieces when the object is not complete but a fragment as in the case of deployment.yml</li></ul><p>Now please run this command and provide the Telegram Token you obtained before.</p><blockquote><strong><em>INFO:</em></strong><em> If you happen to forget the token, you can always go to BotFater and ask him with </em><em>/mybots ;-)</em></blockquote><pre>$ ./05b-deploy-telegram-bot.sh<br>PASTE TOKEN: YOUR_TOKEN<br>USING TOKEN YOUR_TOKEN<br>&gt; telegram-bot@1.0.0 openshift /Users/cvicensa/Projects/openshift/tap/state-machine-assistant/telegram-bot<br>&gt; nodeshift - strictSSL=false - dockerImage=registry.access.redhat.com/rhoar-nodejs/nodejs-10<br>2020–01–15T11:02:43.945Z INFO loading configuration<br>2020–01–15T11:02:43.952Z INFO using namespace state-machine-assistant at <a href="https://api.cluster-kharon-be2a.kharon-be2a.example.opentlc.com:6443/">https://api.cluster-kharon-be2a.kharon-be2a.example.opentlc.com:6443</a><br>…<br>2020–01–15T11:04:07.398Z TRACE npm info ok<br>2020–01–15T11:04:07.398Z TRACE<br>…<br>2020–01–15T11:04:08.393Z TRACE Getting image source signatures<br>2020–01–15T11:04:08.716Z TRACE Copying blob sha256:04dbaef9d44294aedd58690d85eb37e5b57dd98d9e922be36e4ae4e019b21619<br>…<br>2020–01–15T11:04:09.214Z TRACE Copying config sha256:1e16c354e3774215a388a4a0b94c1376c6f042f3e0965d1c7ac16972de8b7a1c<br>2020–01–15T11:04:09.556Z TRACE Writing manifest to image destination<br>2020–01–15T11:04:09.559Z TRACE Storing signatures<br>2020–01–15T11:04:10.957Z TRACE 1e16c354e3774215a388a4a0b94c1376c6f042f3e0965d1c7ac16972de8b7a1c<br>2020–01–15T11:04:14.130Z TRACE<br>2020–01–15T11:04:14.131Z TRACE Pushing image image-registry.openshift-image-registry.svc:5000/state-machine-assistant/telegram-bot:latest …<br>2020–01–15T11:04:14.132Z TRACE Getting image source signatures<br>2020–01–15T11:04:14.223Z TRACE Copying blob sha256:5af42566e7d1943de0196a7d22dc5abb18d916ae5cdb762dffd28d305a11ad41<br>…<br>2020–01–15T11:04:15.572Z TRACE Copying config sha256:1e16c354e3774215a388a4a0b94c1376c6f042f3e0965d1c7ac16972de8b7a1c<br>2020–01–15T11:04:16.615Z TRACE Writing manifest to image destination<br>2020–01–15T11:04:16.708Z TRACE Storing signatures<br>2020–01–15T11:04:16.710Z TRACE Successfully pushed image-registry.openshift-image-registry.svc:5000/state-machine-assistant/telegram-bot@sha256:f49ed9fbd0baf545ccbba03cf6246ba1ef29c647012d049fb3768e817599c9b3<br>2020–01–15T11:04:16.719Z TRACE Push successful<br>2020–01–15T11:04:19.345Z INFO build telegram-bot-s2i-6 complete<br>2020–01–15T11:04:19.392Z INFO openshift.yaml and openshift.json written to /Users/cvicensa/Projects/openshift/tap/state-machine-assistant/telegram-bot/tmp/nodeshift/resource/<br>2020–01–15T11:04:19.808Z INFO creating new configMap telegram-bot<br>2020–01–15T11:04:19.846Z INFO creating new secret telegram-bot-database-secret<br>2020–01–15T11:04:19.849Z INFO creating new service telegram-bot<br>2020–01–15T11:04:19.855Z INFO creating new route telegram-bot<br>2020–01–15T11:04:19.857Z INFO creating deployment configuration telegram-bot<br>2020–01–15T11:04:19.999Z INFO route host mapping telegram-bot-state-machine-assistant.apps.cluster-kharon-be2a.kharon-be2a.example.opentlc.com<br>2020–01–15T11:04:20.003Z INFO complete</pre><p><strong>HIS Backend</strong></p><p>Now it’s time to run, locally, our Spring Boot HIS API. In order to do so we run <a href="https://github.com/cvicens/state-machine-assistant/blob/master/06-run-backend.sh">./06-run-backend.sh</a>. Open a new terminal and run it:</p><blockquote><strong><em>INFO:</em></strong><em> This script runs our application which connects to the Kafka topic $HL7_EVENTS_TOPIC. If you’re wondering why it connects to the Kafka cluster, the answer is this environment variable KAFKA_SERVICE_HOST. When run locally it’s filled with the result of running this command: </em><em>=$(oc -n ${PROJECT_NAME} get routes ${CLUSTER_NAME}-kafka-bootstrap -o=jsonpath=&#39;{.status.ingress[0].host}{&quot;\n&quot;}&#39;), when running in OpenShift the value is predefined in </em><em>application-openshifr.properties and equals to </em><em>state-machine-cluster-kafka-brokers:9092.</em></blockquote><pre>./06-run-backend.sh</pre><p>If it all works properly you should get something like this:</p><pre>...</pre><pre>2020-01-14 19:22:44.229  INFO 80644 --- [  restartedMain] o.a.k.clients.consumer.ConsumerConfig    : ConsumerConfig values:</pre><pre>auto.commit.interval.ms = 5000</pre><pre>auto.offset.reset = latest</pre><pre>bootstrap.servers = [state-machine-cluster-kafka-bootstrap-state-machine-assistant.apps.cluster-kharon-be2a.kharon-be2a.example.opentlc.com:443]</pre><pre>check.crcs = true</pre><pre>client.id =</pre><pre>connections.max.idle.ms = 540000</pre><pre>default.api.timeout.ms = 60000</pre><pre>enable.auto.commit = false</pre><pre>exclude.internal.topics = true</pre><pre>fetch.max.bytes = 52428800</pre><pre>fetch.max.wait.ms = 500</pre><pre>fetch.min.bytes = 1</pre><pre>group.id = kafkaHisBackendConsumerGroup</pre><pre>heartbeat.interval.ms = 3000</pre><pre>interceptor.classes = []</pre><pre>internal.leave.group.on.close = true</pre><pre>isolation.level = read_uncommitted</pre><pre>key.deserializer = class org.apache.kafka.common.serialization.LongDeserializer</pre><pre>max.partition.fetch.bytes = 1048576</pre><pre>max.poll.interval.ms = 300000</pre><pre>max.poll.records = 500</pre><pre>metadata.max.age.ms = 300000</pre><pre>metric.reporters = []</pre><pre>metrics.num.samples = 2</pre><pre>metrics.recording.level = INFO</pre><pre>metrics.sample.window.ms = 30000</pre><pre>partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor]</pre><pre>receive.buffer.bytes = 65536</pre><pre>reconnect.backoff.max.ms = 1000</pre><pre>reconnect.backoff.ms = 50</pre><pre>request.timeout.ms = 30000</pre><pre>retry.backoff.ms = 100</pre><pre>sasl.client.callback.handler.class = null</pre><pre>sasl.jaas.config = null</pre><pre>sasl.kerberos.kinit.cmd = /usr/bin/kinit</pre><pre>sasl.kerberos.min.time.before.relogin = 60000</pre><pre>sasl.kerberos.service.name = null</pre><pre>sasl.kerberos.ticket.renew.jitter = 0.05</pre><pre>sasl.kerberos.ticket.renew.window.factor = 0.8</pre><pre>sasl.login.callback.handler.class = null</pre><pre>sasl.login.class = null</pre><pre>sasl.login.refresh.buffer.seconds = 300</pre><pre>sasl.login.refresh.min.period.seconds = 60</pre><pre>sasl.login.refresh.window.factor = 0.8</pre><pre>sasl.login.refresh.window.jitter = 0.05</pre><pre>sasl.mechanism = GSSAPI</pre><pre>security.protocol = SSL</pre><pre>send.buffer.bytes = 131072</pre><pre>session.timeout.ms = 10000</pre><pre>ssl.cipher.suites = null</pre><pre>ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]</pre><pre>ssl.endpoint.identification.algorithm = https</pre><pre>ssl.key.password = null</pre><pre>ssl.keymanager.algorithm = SunX509</pre><pre>ssl.keystore.location = src/main/resources/keystore.jks</pre><pre>ssl.keystore.password = [hidden]</pre><pre>ssl.keystore.type = JKS</pre><pre>ssl.protocol = TLS</pre><pre>ssl.provider = null</pre><pre>ssl.secure.random.implementation = null</pre><pre>ssl.trustmanager.algorithm = PKIX</pre><pre>ssl.truststore.location = src/main/resources/keystore.jks</pre><pre>ssl.truststore.password = [hidden]</pre><pre>ssl.truststore.type = JKS</pre><pre>value.deserializer = class org.apache.kafka.common.serialization.StringDeserializer</pre><pre>2020-01-14 19:22:44.391  INFO 80644 --- [  restartedMain] o.a.kafka.common.utils.AppInfoParser     : Kafka version : 2.0.1</pre><pre>2020-01-14 19:22:44.391  INFO 80644 --- [  restartedMain] o.a.kafka.common.utils.AppInfoParser     : Kafka commitId : fa14705e51bd2ce5</pre><pre>&gt;&gt;&gt; init() with topics = hl7-events-topic</pre><pre>2020-01-14 19:22:44.898  INFO 80644 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService &#39;applicationTaskExecutor&#39;</pre><pre>2020-01-14 19:22:44.953  WARN 80644 --- [  restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning</pre><pre>2020-01-14 19:22:45.024  INFO 80644 --- [       Thread-8] org.apache.kafka.clients.Metadata        : Cluster ID: JiCToAYZTHCDpbNYVyMlKA</pre><pre>2020-01-14 19:22:45.029  INFO 80644 --- [       Thread-8] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=kafkaHisBackendConsumerGroup] Discovered group coordinator state-machine-cluster-kafka-1-state-machine-assistant.apps.cluster-kharon-be2a.kharon-be2a.example.opentlc.com:443 (id: 2147483646 rack: null)</pre><pre>2020-01-14 19:22:45.038  INFO 80644 --- [  restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]</pre><pre>2020-01-14 19:22:45.040  INFO 80644 --- [       Thread-8] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-1, groupId=kafkaHisBackendConsumerGroup] Revoking previously assigned partitions []</pre><pre>2020-01-14 19:22:45.040  INFO 80644 --- [       Thread-8] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=kafkaHisBackendConsumerGroup] (Re-)joining group</pre><pre>2020-01-14 19:22:45.270  INFO 80644 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path &#39;/actuator&#39;</pre><pre>2020-01-14 19:22:45.340  INFO 80644 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path &#39;&#39;</pre><pre>2020-01-14 19:22:45.342  INFO 80644 --- [  restartedMain] com.redhat.his.BoosterApplication        : Started BoosterApplication in 6.678 seconds (JVM running for 7.135)</pre><pre>2020-01-14 19:22:47.966  INFO 80644 --- [       Thread-8] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=kafkaHisBackendConsumerGroup] Successfully joined group with generation 102</pre><pre>2020-01-14 19:22:47.968  INFO 80644 --- [       Thread-8] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-1, groupId=kafkaHisBackendConsumerGroup] Setting newly assigned partitions [hl7-events-topic-0]</pre><p>Let’s run some tests, for instance let’s get all the patients in the dabase. Let’s remember that when run locally, default profile is used and H2 is the database, not PostgreSQL. Please run this command from a different terminal.</p><pre>$ curl http://localhost:8080/api/patients</pre><pre>[{&quot;patientId&quot;:1,&quot;personalId&quot;:&quot;0123456789Z&quot;,&quot;firstName&quot;:&quot;JOHN&quot;,&quot;lastName&quot;:&quot;SMITH&quot;,&quot;stage&quot;:&quot;idle&quot;},{&quot;patientId&quot;:2,&quot;personalId&quot;:&quot;9876543210W&quot;,&quot;firstName&quot;:&quot;PETER&quot;,&quot;lastName&quot;:&quot;JONES&quot;,&quot;stage&quot;:&quot;idle&quot;}]</pre><h4>The integration layer</h4><p>The integration layer comprises two Java classes implementing two Camel routes:</p><ul><li>HL7 to Events: which receives HL7 messages, translate them to human readable text and send them to a different topic</li><li>Events to Telegram Bot: which receives Events and pass them through to the Telegram Bot</li></ul><p>Theses are the relevant lines of code of class HL7ToEvents</p><blockquote><em>There is just one route </em><em>hl7-to-patient-info that</em></blockquote><blockquote>1. starts from a kafka topic: from(&quot;kafka:{{kafka.from.topic}}...&quot;)</blockquote><blockquote>2. then, sets some catches for exceptions: .onException(...)</blockquote><blockquote>3. later, it translates from HL7 messages using the good old <a href="https://hapifhir.github.io/hapi-hl7v2/">HAPI</a> libraries: .process(exchange -&gt; ...</blockquote><blockquote>4. finally after some convertion the human readable message is sent to another topic: .to(&quot;kafka:{{kafka.to.topic}}...&quot;)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f528af21e987bcb9cadcdd9fa247adc0/href">https://medium.com/media/f528af21e987bcb9cadcdd9fa247adc0/href</a></iframe><p>Next you can find the relevant lines of code of the second part of the integration layer, class EventsToTelegramBot.</p><blockquote><em>This integration comprises two routes, the 1st one </em><em>events-to-bot is even simpler:</em></blockquote><blockquote>1. Again it starts from a topic: from(&quot;kafka:{{kafka.from.topic}}...&quot;)</blockquote><blockquote>2. Then some exception handling: .onException(...)</blockquote><blockquote>3. Pass the message to the other route: .to(&quot;direct:send-event-to-bot&quot;)</blockquote><blockquote><em>The 2nd route </em><em>send-event-to-bot</em></blockquote><blockquote>1. Sets some header to configure the http component: .setHeader(...)</blockquote><blockquote>2. Send the message to the Telegram Bot using the http component: .to(&quot;http://{{telegram-bot.host}}:{{telegram-bot.port}}/new-message&quot;)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d34bac72878efe8fc533de80f8e09fb/href">https://medium.com/media/1d34bac72878efe8fc533de80f8e09fb/href</a></iframe><p>Let’s run our integrations in two different (additional) terminal windows:</p><ul><li>07a-run-integration.sh in charge of translating from HL7 to human readable text events</li><li>07b-run-integration.sh in charge of sending those events to the Telegram Bot</li></ul><p>So, please in a different terminal run:</p><pre>$ ./07a-run-integration.sh</pre><p>And yet in another terminal window, run:</p><pre>$ ./07b-run-integration.sh</pre><p>Let’s run a test that generates a change in the status of a patient:</p><blockquote><strong><em>NOTE:</em></strong><em> In order for this test to work you should have signed up the personalId. You should have done this before when testing the Telegram Bot.</em></blockquote><pre>curl -H &#39;Content-Type: application/json&#39; -X PUT \</pre><pre>-d &#39;{&quot;patientId&quot;:2,&quot;personalId&quot;:&quot;9876543210W&quot;,&quot;firstName&quot;:&quot;PETER&quot;,&quot;lastName&quot;:&quot;JONES&quot;,&quot;stage&quot;:&quot;admission&quot;}&#39; \</pre><pre>http://localhost:8080/api/patients/2</pre><p>If it all works properly no error should be received and a message should be sent to the Telegram App.</p><p>If in the desktop app you’ll see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*K4shWY7HVgGsZozZ.png" /></figure><p>Then in the Telegram App you’ll see the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IHuBAbISFrL95_8n.png" /></figure><p>So for now we have HIS Backend, running locally, both integrations running in OpenShift (although we see logs locally) and the Telegram Bot running also in OpenShift.</p><p>Next step is to run the frontend locally pointing to the backend running also locally.</p><h4>HIS Frontend</h4><p>This time we have to run a NodeJS application that contains the code of an Angular JS (with Material design) along with a proxy that sends all /api/patients requests to <a href="http://localhost:8080/api/patients.">http://localhost:8080/api/patients.</a></p><blockquote><strong><em>INFO:</em></strong><em> The trick is in the script </em><em>dev in </em><em>./frontend/package.json that runs in paralell </em><em>client and </em><em>server. </em><em>client uses </em><em>--proxy-config server.conf.js to set the proxy rules. Open and check the line </em><em>npm run dev.</em></blockquote><pre>./08-run-frontend.sh</pre><pre>&gt; frontend@0.0.0 dev /U.../state-machine-assistant/frontend</pre><pre>&gt; npx concurrently --kill-others &quot;npm run client&quot; &quot;npm run server&quot;</pre><pre>...</pre><p>Now open a browser and point to <a href="http://localhost:4200/">http://localhost:4200</a>. You should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cfyz1Xdkv5K0Fk19.png" /></figure><p>Now add a <em>Reason</em> and click on Next for <strong>Patient PETER JONES (9876543210W)</strong> This way you change the status from adminssion to triage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OCaQIxUNUo9KKvn3.png" /></figure><p>If you go to he backend terminal you would see something like:</p><pre>Record sent to partition 0 with offset 74</pre><p>On integration 7a:</p><pre>[2] 2020-01-15 11:49:40.131 INFO  [Camel (camel-k) thread #1 - KafkaConsumer[hl7-events-topic]] hl7-to-patient-info - body: TVNIfF5+XCZ8QURUMXxNQ018TEFCQURUfE1DTXwxOTg4MDgxODExMjZ8U0VDVVJJVFl8QURUXkEwOHxNU0cwMDAwMXxQfDIuNA1FVk58QTA4fDIwMDUwMTEwMDQ1NTAyfHx8fHwNUElEfHwyfDk4NzY1NDMyMTBXfHxKT05FU15QRVRFUnx8MTk2MTA2MTV8TXx8MjEwNi0zfDEyMDAgTiBFTE0gU1RSRUVUXl5HUkVFTlNCT1JPXk5DXjI3NDAxLTEwMjB8R0x8KDkxOSkzNzktMTIxMnwoOTE5KTI3MS0zNDM0fig5MTkpMjc3LTMxMTR8fFN8fDk4NzY1NDMyMTBXNTAwMV4yXk0xMHwxMjM0NTY3ODl8OS04NzY1NF5OQw1QVjF8MXxJfEVSXl5eXl5eQnxVfHx8MzdeTUFSVElORVpeSk9ITl5eXl5eXkFjY01ncl5eXl5DSXx8fDAxfHx8fDF8fHwzN15NQVJUSU5FWl5KT0hOXl5eXl5eQWNjTWdyXl5eXkNJfDJ8NDAwMDc3MTZeXl5BY2NNZ3JeVk58NHx8fHx8fHx8fHx8fHx8fHx8fHwxfHxHfHx8MjAwNTAxMTAwNDUyNTN8fHx8fHwNR1QxfDExMjJ8MTUxOXxKT0hOXkdBVEVTXkENSU4xfDAwMXxBMzU3fDEyMzR8QkNNRHx8fHx8MTMyOTg3DUlOMnxJRDE1NTEwMDF8U1NOMTIzNDU2NzgN<br>[2] Encoded Message TVNIfF5+XCZ8QURUMXxNQ018TEFCQURUfE1DTXwxOTg4MDgxODExMjZ8U0VDVVJJVFl8QURUXkEwOHxNU0cwMDAwMXxQfDIuNA1FVk58QTA4fDIwMDUwMTEwMDQ1NTAyfHx8fHwNUElEfHwyfDk4NzY1NDMyMTBXfHxKT05FU15QRVRFUnx8MTk2MTA2MTV8TXx8MjEwNi0zfDEyMDAgTiBFTE0gU1RSRUVUXl5HUkVFTlNCT1JPXk5DXjI3NDAxLTEwMjB8R0x8KDkxOSkzNzktMTIxMnwoOTE5KTI3MS0zNDM0fig5MTkpMjc3LTMxMTR8fFN8fDk4NzY1NDMyMTBXNTAwMV4yXk0xMHwxMjM0NTY3ODl8OS04NzY1NF5OQw1QVjF8MXxJfEVSXl5eXl5eQnxVfHx8MzdeTUFSVElORVpeSk9ITl5eXl5eXkFjY01ncl5eXl5DSXx8fDAxfHx8fDF8fHwzN15NQVJUSU5FWl5KT0hOXl5eXl5eQWNjTWdyXl5eXkNJfDJ8NDAwMDc3MTZeXl5BY2NNZ3JeVk58NHx8fHx8fHx8fHx8fHx8fHx8fHwxfHxHfHx8MjAwNTAxMTAwNDUyNTN8fHx8fHwNR1QxfDExMjJ8MTUxOXxKT0hOXkdBVEVTXkENSU4xfDAwMXxBMzU3fDEyMzR8QkNNRHx8fHx8MTMyOTg3DUlOMnxJRDE1NTEwMDF8U1NOMTIzNDU2NzgN<br>IN2|ID1551001|SSN12345678||132987^JOHN^^^^^^AccMgr^^^^CI|||01||||1|||37^MARTINEZ^JOHN^^^^^^AccMgr^^^^CI|2|40007716^^^AccMgr^VN|4|||||||||||||||||||1||G|||20050110045253||||||89|9-87654^NC<br>[2] sendingApplication ADT1<br>[2] &gt;&gt;&gt; HL7 code: ADT event: A08<br>...</pre><p>On integration 7b:</p><pre>[1] 2020-01-15 11:49:40.148 INFO [Camel (camel-k) thread #2 - KafkaConsumer[events-topic]] events-to-bot - Route started from Kafka Topic events-topic [1] 2020-01-15 11:49:40.148 INFO [Camel (camel-k) thread #2 - KafkaConsumer[events-topic]] events-to-bot - body: {&quot;personalId&quot;:&quot;9876543210W&quot;,&quot;patientId&quot;:&quot;2&quot;,&quot;message&quot;:&quot;Patient PETER JONES with ID(9876543210W) has been updated (A08) in Black Mountain&quot;} [1] 2020-01-15 11:49:40.148 INFO [Camel (camel-k) thread #2 - KafkaConsumer[events-topic]] events-to-bot - Sending message to telegram bot <a href="http://telegram-bot:tcp://172.30.247.180:8080/new-message:">http://telegram-bot:tcp://172.30.247.180:8080/new-message:</a> {&quot;personalId&quot;:&quot;9876543210W&quot;,&quot;patientId&quot;:&quot;2&quot;,&quot;message&quot;:&quot;Patient PETER JONES with ID(9876543210W) has been updated (A08) in Black Mountain&quot;}</pre><pre>...</pre><p>And hopefully you’ll see a notification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*AxSA_8h1BA7JRotk.png" /></figure><p>And the whole message as before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NXj_ZUhMfrShtbir.png" /></figure><p>So for now we have HIS Frontend and Backend, running locally, both integrations running in OpenShift (altough we see logs locally) and the Telegram Bot running also in OpenShift.</p><p>Next step is to run deploy HIS Frontend and Backend.</p><h3><strong>Deploy the remaining components to OpenShift</strong></h3><h4><strong>Deploying HIS Frontend and Backend</strong></h4><p>To deploy the frontend, as we did before for the Telegram Bot we’re going to use Nodeshift, on the other hand for the backend we cannot use Nodeshift because is a Java/Maven app... but no worries we have a similar tool called <a href="https://maven.fabric8.io/">Fabric8 Maven Plugin</a>.</p><p>For now just run this command:</p><pre>./09-deploy-frontend-and-backend.sh</pre><p>Eventually you’ll see in Projects-&gt;YOUR_PROJECT-&gt;Workloads something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0nSnhDNvGKMm3Zes.png" /></figure><h4><strong>Deploying Camel Integrations</strong></h4><p>If previously we have two script to run the integrations HL7 to Events and Events to Telegram Bot now we only have one ./10-deploy-integration.sh. The other difference is that we don&#39;t want to see the logs locally, so no need for the --dev flag any more.</p><blockquote><em>This is the relevant piece in our script:</em></blockquote><pre>/kamel run --configmap=hl7-to-events \ -d camel-gson -d mvn:ca.uhn.hapi:hapi-base:2.3 -d mvn:ca.uhn.hapi:hapi-structures-v24:2.3 \ ./integrations/HL7ToEvents.java ./kamel run --configmap=events-to-bot ./integrations/EventsToTelegramBot.java</pre><p>Now please run the script, your should receive an output like this:</p><pre>./10-deploy-integration.sh</pre><pre>integration &quot;hl7to-events&quot; created</pre><pre>integration &quot;events-to-telegram-bot&quot; created</pre><h3><strong>Final tests</strong></h3><p>Now that we have everything deployed in OpenShift, it’s time to do the final test.</p><p>We only need the route of our HIS Frontend application, you can get it by running this command:</p><blockquote><em>You can also use the web console and go to </em><em>Projects-&gt;YOUR_PROJECT-&gt;Workloads Click on </em><em>frontend then look for </em><em>Resources-&gt;Routes</em></blockquote><pre>oc get route/frontend -n $PROJECT_NAME</pre><p>Open a browser and change the status of PETER JONES at will, you should expect the same results as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and </strong><a href="https://instagram.com/fauncommunity/"><strong>Instagram</strong></a><strong> </strong>📷 <strong>and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook</strong></a><strong> and </strong><a href="https://www.linkedin.com/company/faundev"><strong>Linkedin</strong></a><strong> Groups </strong>💬<strong>.</strong></p><p><strong>To join our community Slack team chat </strong>🗣️ <strong>read our weekly Faun topics </strong>🗞️,<strong> and connect with the community </strong>📣<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6P3WpLjGv5v1ucm5dgkucg.png" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d60c94f3f33" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/develop-an-event-driven-application-based-on-kafka-camel-k-and-a-telegram-bot-on-openshift-step-2d60c94f3f33">Develop an Event Driven Application based on Kafka, Camel K and a Telegram Bot on OpenShift step…</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Could a Kubernetes Operator become the guardian of your ConfigMaps]]></title>
            <link>https://faun.pub/could-a-kubernetes-operator-become-the-guardian-of-your-configmaps-1b11b9b45734?source=rss-15c32cd806ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b11b9b45734</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[gitops]]></category>
            <dc:creator><![CDATA[Carlos Vicens]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 21:38:56 GMT</pubDate>
            <atom:updated>2019-07-19T17:20:53.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*L1ha3ec2dADbTpZwsNY4Sw.png" /></figure><h4>A GitOps-oriented approach</h4><p>All this started as a by-product of a meeting I had recently with a customer and also from a conversation I had with a partner. Both events triggered the need of managing configuration in a kubernetes namespace, and because I have been invo…</p><p>Just to give you a bit of context…</p><p>The meeting with the customer was focused on new Openshift features around Ops, and most of the time was spent on <a href="https://operatorhub.io/what-is-an-operator">Kubernetes Operators</a>, why, how, etc. In fact it was conducted as a lab where we used the <a href="https://github.com/coreos/prometheus-operator">Prometheus Operator</a>, I’m referring to <a href="https://medium.com/devopslinks/using-the-operator-lifecycle-manager-to-deploy-prometheus-on-openshift-cd2f3abb3511">this short lab</a>. What is curious is that the relevant outcome of the meeting came from a side conversation about their CI/CD pipelines and specifically about configuration management… at that moment I thought what if we use an operator to ensure that configuration is as defined in the git repository.</p><p>The conversation with the partner happened around the same week… again a side conversation (how important is wandering around every now and then ;-) this time it was about creating some kind of archetype to speed up the first moves of a new project forced me to develop the operator. The key concept of the side conversation was <a href="https://www.weave.works/technologies/gitops/">GitOps</a>, a new concept for me that fitted perfectly with the previous conversation about configuration management.</p><p>So I decided to prove that this all made sense… and here’s the result.</p><h4><strong>TL;DR</strong></h4><p>I have developed a <a href="https://operatorhub.io/what-is-an-operator">Kubernetes Operator</a> that ensures that ConfigMaps in a namespace are exactly as defined in the correspending Git repo and branch. By corresponding I mean as defined in a <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/">Custom Resource</a> like the next one.</p><p>Sample Custom Resource</p><blockquote><em>As you can see next Custom Resource of kind </em><em>Repository points to a git repo and branch where the operator will look for ConfigMaps to later make the namespace the operator is running in match them.</em></blockquote><pre>apiVersion: cloudnative.redhat.com/v1alpha1<br>kind: Repository<br>metadata:<br>  name: example-repository<br>spec:<br>  # Add fields here<br>  gitUrl: &quot;https://github.com/cvicens/archetype-operator-customer-service.git&quot;<br>  gitRef: &quot;master&quot;</pre><p>Keep reading to see how you can quickly create your own GitOps-inspired operator by taking mine as a starting point.</p><h3>Prerequisites</h3><p>You need to install the Operator SDK, instructions <a href="https://github.com/operator-framework/operator-sdk">here</a>, section ‘Prerequisites’</p><ul><li><a href="https://golang.github.io/dep/docs/installation.html">dep</a> version v0.5.0+</li><li><a href="https://git-scm.com/downloads">git</a></li><li><a href="https://golang.org/dl/">go</a> version v1.10+</li><li><a href="https://docs.docker.com/install/">docker</a> version 17.03+</li><li><a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">kubectl</a> version v1.11.3+ or <a href="https://docs.okd.io/latest/cli_reference/get_started_cli.html#installing-the-cli">oc</a> version 3.11+</li><li>Access to a Kubernetes v1.11.3+ or Openshift 3.11+ cluster</li></ul><p>Because we’re going to use Ansible and the k8s module to develop our operator you’ll also need, Ansible and the <a href="https://github.com/openshift/openshift-restclient-python">Openshift Python Restclient</a></p><ul><li>pip install ansible (you may need to run this with sudo)</li><li>pip install openshift</li></ul><blockquote><em>IMPORTANT: To run some of the tasks in this document you should be cluster-admin so maybe using </em><a href="https://www.okd.io/minishift/"><em>minishift</em></a><em> will be easier than convincing someone with super powers let you join their club ;-)</em></blockquote><h3>Before we get our hands dirty. What’s an Operator?</h3><p>Because… I love getting my hands dirty (with code usually) but I want to know what I’m going to get them dirty with.</p><p><em>An operator is, at its lowest level, a pod that will watch changes to Custom Resources that define a desired state and execute tasks accordingly to ensure that the actual state matches the defined state.</em></p><p>When a pod is created it specifies a service account (or uses the default service account) and is allowed to use that service account’s API credentials and referenced secrets, find more information <a href="https://docs.openshift.com/container-platform/3.11/dev_guide/service_accounts.html#using-a-service-accounts-credentials-inside-a-container">here</a></p><p>Ok, now we can get our hands dirty.</p><h3>Creating the scaffold project</h3><p>Now let’s use the Operator SDK it to create a project for our operator as follows.</p><blockquote><em>Our operator’s scope (the default) is limited to a namespace, hence it is a </em><em>namespace-scoped operator, and will watch and manage resources in a single namespace. Add </em><em>--cluster-scoped if the scope of your operator should be cluster-wide.</em></blockquote><pre>$ operator-sdk new archetype-operator --api-version=cloudnative.redhat.com/v1alpha1 --kind=Repository --type=ansible<br>INFO[0000] Creating new Ansible operator &#39;archetype-operator&#39;. <br>...<br>INFO[0000] Project creation complete.</pre><p>Next we show the different artifacts generated in our new project folder. <em>Excerpt from the </em><a href="https://github.com/operator-framework/operator-sdk/blob/master/doc/ansible/project_layout.md"><em>operator sdk documentation</em></a><em>.</em></p><ul><li><strong>deploy/</strong> Contains a generic set of Kubernetes manifests for deploying this operator on a Kubernetes cluster.</li><li><strong>roles/</strong> Contains an Ansible Role initialized using <a href="https://docs.ansible.com/ansible/latest/reference_appendices/galaxy.html">Ansible Galaxy</a></li><li><strong>build/</strong> Contains scripts that the operator-sdk uses for build and initialization.</li><li><strong>watches.yaml</strong> Contains Group, Version, Kind, and Ansible invocation method.</li></ul><p>Some interesting elements I’d like to highlight in folder <strong>./deploy</strong></p><ul><li><strong>operator.yaml</strong> minimal kubernetes deployment descriptor, it needs to be modified be usable, little but important changes.</li><li><strong>service_account.yaml</strong> definition of the service account our pod will use</li><li><strong>role.yaml</strong> kubernetes role definition granting basic permissions over typical kubernetes objects, we won&#39;t change anything here because this role already provides the permissions needed regarding ConfigMaps</li><li><strong>role_binding.yaml</strong> links role and service account</li><li><strong>crds/</strong> this folder contain the definition of the Custom Resource Definition (CRD) and an example of Custom Resource (CR). Take a CR as an instance of a CRD.</li></ul><h3>Create a namespace to deploy our operator</h3><p>In order to deploy our operator we need an Openshift project, so let’s create one.</p><blockquote><em>‘-master’ is just a naming convention to refer to the git repo branch we want to sinc up ConfigMaps with. Presumably there could be other namespaces ‘-test’, ‘-prod’, right?</em></blockquote><pre>$ oc new-project archetype-master<br>or<br>$ kubectl new-namespace archetype-master</pre><h3>Deploying basic artifacts</h3><p>Prior to running our operator, we need to deploy some basic elements in folder <strong>./deploy</strong></p><blockquote><em>WARNING: In order to be able to </em><em>apply both </em><em>deploy/role.yaml and </em><em>deploy/crds/cloudnative_v1alpha1_repository_crd.yaml you need to be cluster admin. The next command shows how to become cluster admin in an Openshift cluster</em></blockquote><blockquote><em>$ oc adm policy add-cluster-role-to-user cluster-admin &lt;user&gt;</em></blockquote><p>Be sure you are in the project folder…</p><pre>$ cd archetype-operator</pre><p>Let’s deploy the definition of our Custom Resource or CRD.</p><pre>$ oc apply -f deploy/crds/cloudnative_v1alpha1_repository_crd.yaml<br>or<br>$ kubectl apply -f deploy/crds/cloudnative_v1alpha1_repository_crd.yaml</pre><p>Let’s deploy the role we’re going to grant to the operator service account and the service account itself.</p><pre>$ oc apply -n archetype-master -f deploy/role.yaml <br>or<br>$ kubectl apply -n archetype-master -f deploy/role.yaml </pre><pre>$ oc apply -n archetype-master -f deploy/service_account.yaml <br>or<br>$ kubectl apply -n archetype-master -f deploy/service_account.yaml</pre><p>Finally let’s link service account with role through the role binding.</p><pre>$ oc apply -n archetype-master -f deploy/role_binding.yaml <br>or<br>$ kubectl apply -n archetype-master -f deploy/role_binding.yaml</pre><blockquote>Maybe you’ve noticed we haven’t applied ./deploy/cloudnative_v1alpha1_repository_cr.yaml. This is becase we haven&#39;t decided yet which properties should form the spec of our Custom Resource, we&#39;ll do that later.</blockquote><h3>Adding actual code to our ansible role</h3><p>Please go to folder ./roles/repository and open tasks/main.yml, then substitute it&#39;s contents with this.</p><pre>---<br># tasks file for repository</pre><pre>- name: Get a list of all ConfigMap objects in namespace {{ meta.namespace }}<br>  k8s_facts:<br>    api_version: v1<br>    kind: ConfigMap<br>    namespace: &#39;{{ meta.namespace }}&#39;<br>  register: configmap_list</pre><pre>- name: configmap_list<br>  debug: <br>    msg: &quot;{{ configmap_list }}&quot;</pre><pre>- name: List of configmap names in namespace {{ meta.namespace }}<br>  set_fact:<br>    configmap_names_list: &quot;{{ configmap_list | json_query(&#39;resources[?metadata.name!=`archetype-operator-lock`].metadata.name&#39;) }}&quot;</pre><pre>- name: configmap_names_list<br>  debug: <br>    msg: &quot;{{ configmap_names_list }}&quot;</pre><pre>- name: Checking out config folder from {{ git_url }}/{{ git_ref }}<br>  git:<br>    repo: &#39;{{ git_url }}&#39;<br>    dest: ./tmp<br>    version: &#39;{{ git_ref }}&#39;</pre><pre>- name: Find &#39;*-configmap&#39; files in ./k8s folder<br>  find:<br>    paths: ./tmp/k8s<br>    patterns: &#39;*-configmap.yaml&#39;<br>  register: git_configmap_file_list</pre><pre>- name: List of configmap file paths<br>  set_fact:<br>    git_configmap_file_paths: &quot;{{ git_configmap_file_list | json_query(&#39;files[*].path&#39;) }}&quot;</pre><pre>- name: git_configmap_file_paths<br>  debug: <br>    msg: &quot;{{ git_configmap_file_paths }}&quot;</pre><pre>- name: Get configmap content from git files<br>  set_fact:<br>    git_configmap_list: &quot;{{ git_configmap_list | default([]) + [ item | from_yaml ] }}&quot;<br>  with_file: &quot;{{ git_configmap_file_paths }}&quot;</pre><pre>- name: git_configmap_list<br>  debug:<br>    msg: &quot;{{ git_configmap_list }}&quot;</pre><pre>- name: List of configmap names from git<br>  set_fact:<br>    git_configmap_names_list: &quot;{{ git_configmap_list | json_query(&#39;[*].metadata.name&#39;) }}&quot;</pre><pre>- name: git_configmap_names_list<br>  debug: <br>    msg: &quot;{{ git_configmap_names_list }}&quot;</pre><pre>- name: List of configmap names to delete<br>  set_fact:<br>    configmap_names_to_delete_list: &quot;{{ configmap_names_list | difference(git_configmap_names_list) }}&quot;</pre><pre>- name: configmap_names_to_delete_list<br>  debug: <br>    msg: &quot;{{ configmap_names_to_delete_list }}&quot;</pre><pre>- name: Create configmaps from git in namespace {{ meta.namespace }}<br>  k8s:<br>    state: &quot;{{ state }}&quot;<br>    namespace: &#39;{{ meta.namespace }}&#39;<br>    definition: &quot;{{ item }}&quot;<br>    force: yes<br>  with_items: &quot;{{ git_configmap_list }}&quot;<br>  when: git_configmap_list is defined</pre><pre>- name: Delete &#39;to-be-deleted&#39; configmaps from namespace {{ meta.namespace }}<br>  k8s:<br>    state: absent<br>    api_version: v1<br>    kind: ConfigMap<br>    namespace: &#39;{{ meta.namespace }}&#39;<br>    name: &quot;{{ item }}&quot;<br>  with_items: &quot;{{ configmap_names_to_delete_list }}&quot;<br>  when: configmap_names_to_delete_list is defined</pre><p>What this code does is:</p><ul><li>Getting the a list of all ConfigMap objects in the operator’s namespace and their names</li><li>Checking out the git repo pointed by variablegit_url</li><li>Looking for ‘*-configmap’ files in ./k8s folder in the cloned repo</li><li>Creating all the ConfigMaps from the git repo in the operator’s namespace</li><li>Deleting all the ConfigMaps that shouldn’t be in our namespace</li></ul><blockquote><em>Deleting should be optional, specially in a development branch… I’ll add a new variable to the Custom Resource and change the code accordingly soon</em></blockquote><h3>Wait a little change to the image is needed!</h3><p>As you have seen our Ansible role clones a git repo… so it needs git binary installed… so we need to install it in the image of our container. I almost forgot, we also need a python package ‘jmespath’ for the json_query filters.</p><p>To do this please open ./build/Dockerfile compare it&#39;s contents and substitute them with this.</p><pre>FROM quay.io/operator-framework/ansible-operator:v0.5.0</pre><pre>USER root<br>RUN yum -y install git &amp;&amp; pip install jmespath</pre><pre>USER ${USER_UID}<br>COPY roles/ ${HOME}/roles/<br>COPY watches.yaml ${HOME}/watches.yaml</pre><h3>Build the image, tag it and push it</h3><p>Now that the code and the Dockerfile are ready we can build the image and push it to an image registry like quay.io or docker.io.</p><blockquote><em>You can always use my image </em><em>quay.io/cvicensa/archetype-operator if you don&#39;t have an account in a registry at hand or don&#39;t want to use it but honestly that would take all the fun... so go and get an account somewhere, </em><a href="https://quay.io/"><em>quay.io</em></a><em>is a nice option</em></blockquote><p>Let’s build the image.</p><blockquote><em>Remember! You should be inside the project folder</em></blockquote><pre>$ operator-sdk build archetype-operator<br>INFO[0000] Building Docker image archetype-operator     <br>Sending build context to Docker daemon  149.8MB<br>Step 1/6 : FROM quay.io/operator-framework/ansible-operator:v0.5.0<br> ---&gt; 1e857f3522b5<br>Step 2/6 : USER root<br> ---&gt; Using cache<br> ---&gt; 0e054a4cc239<br>Step 3/6 : RUN yum -y install git &amp;&amp; pip install jmespath<br> ---&gt; Using cache<br> ---&gt; d5d37138b29b<br>Step 4/6 : USER ${USER_UID}<br> ---&gt; Running in 0ed62d3fab78<br>Removing intermediate container 0ed62d3fab78<br> ---&gt; fc792ae1cca8<br>Step 5/6 : COPY roles/ ${HOME}/roles/<br> ---&gt; 0e764654ddbc<br>Step 6/6 : COPY watches.yaml ${HOME}/watches.yaml<br> ---&gt; d52330d57277<br>Successfully built d52330d57277<br>Successfully tagged archetype-operator:latest<br>INFO[0010] Operator build complete.</pre><p>Let’s tag the image so that we can push it later to the registry.</p><blockquote><em>If docker.io is your registry remember that tagging should be: </em><em>docker tag archetype-operator &lt;userid&gt;/archetype-operator</em></blockquote><pre>$ docker tag archetype-operator quay.io/&lt;userid&gt;/archetype-operator</pre><p>Finally let’s push the image to the registry.</p><blockquote><em>Again if docker.io </em><em>docker push &lt;userid&gt;/archetype-operator</em></blockquote><pre>$ docker push quay.io/&lt;userid&gt;/archetype-operator</pre><h3>Modifying the sample Custom Resource definition</h3><p>As I pointed out before, we haven’t applied ./deploy/cloudnative_v1alpha1_repository_cr.yaml yet mostly because we haven&#39;t added any meaningful properties ;-) let&#39;s fix that.</p><blockquote>Remember that we create CRs to define a desired state… so we need properties to define that state</blockquote><p>In our code we’re expecting some variables: {{ state }}, {{ git_url }} and {{ git_ref }}.</p><p>Let’s create a Custom Resource that matches the variables our role expects. Please open ./deploy/crds/cloudnative_v1alpha1_repository_cr.yaml and replace section spec with this.</p><pre>spec:<br>  gitUrl: &quot;https://github.com/cvicens/archetype-operator-customer-service.git&quot;<br>  gitRef: &quot;master&quot;</pre><blockquote><strong><em>TIP:</em></strong><em> It’s worth mentioning that variables in yaml (camel case) are translated to snake case, so </em><em>spec→gitUrltranslates to </em><em>git_url</em></blockquote><p>We should give some default values to these variables in our role, so please open file ./roles/repository/defaults/main.yml and add these variables.</p><pre>---<br># defaults file for repository<br>state: present<br>git_url: &quot;https://github.com/cvicens/archetype-operator-customer-service.git&quot;<br>git_ref: &quot;master&quot;</pre><h3>Prepare the operator deployment descriptor</h3><p>Please open file ./deploy/operator.yaml and make the next changes:</p><ul><li>{{ REPLACE_IMAGE }} changes to quay.io/&lt;userid&gt;/archetype-operator</li><li>{{ pull_policy|default(&#39;Always&#39;) }} changes to Always</li></ul><blockquote><em>Please, take into account that </em><em>image should point to YOUR image ;-)</em></blockquote><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: archetype-operator<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      name: archetype-operator<br>  template:<br>    metadata:<br>      labels:<br>        name: archetype-operator<br>    spec:<br>      serviceAccountName: archetype-operator<br>      containers:<br>        - name: archetype-operator<br>          # Replace this with the built image name<br>          image: &quot;{{ REPLACE_IMAGE }}&quot;<br>          imagePullPolicy: &quot;{{ pull_policy|default(&#39;Always&#39;) }}&quot;<br>          env:<br>            - name: WATCH_NAMESPACE<br>              valueFrom:<br>                fieldRef:<br>                  fieldPath: metadata.namespace<br>            - name: POD_NAME<br>              valueFrom:<br>                fieldRef:<br>                  fieldPath: metadata.name<br>            - name: OPERATOR_NAME<br>              value: &quot;archetype-operator&quot;</pre><p>Now we can deploy our operator… excited?</p><h3>Deploying our operator…</h3><p>As I have already explained… <strong>operator == pod</strong> so we need a Deployment descriptor to actually deploy it and apply it in our namespace.</p><pre>$ oc apply -f ./deploy/operator.yaml<br>or<br>$ kubectl apply -f ./deploy/operator.yaml</pre><h3>Let’s deploy our Custom Resource</h3><p>Let’s create our Custom Resource in the same namespace where we have deployed all the other resources.</p><pre>$ oc apply -f ./deploy/crds/cloudnative_v1alpha1_repository_cr.yaml -n archetype-master<br>repository.cloudnative.redhat.com/example-repository created<br>or<br>$ kubectl apply -f ./deploy/crds/cloudnative_v1alpha1_repository_cr.yaml -n archetype-master<br>repository.cloudnative.redhat.com/example-repository created</pre><p>Now let’s have a look to the logs of our operator, but first let’s locate our pod.</p><pre>$ oc get pod<br>NAME                           READY  STATUS    RESTARTS   AGE<br>archetype-operator-...-w5f6m   1/1    Running   0          3m<br>or<br>$ kubectl get pod<br>NAME                           READY  STATUS    RESTARTS   AGE<br>archetype-operator-...-w5f6m   1/1    Running   0          3m</pre><p>Now let’s see if it all worked out properly.</p><pre>$ oc logs archetype-operator-f6b778d55-w5f6m -n archetype-master<br>...<br>{&quot;level&quot;:&quot;info&quot;,&quot;logger&quot;:&quot;runner&quot;,&quot;msg&quot;:&quot;Ansible-runner exited successfully&quot;,&quot;job&quot;:&quot;5100060361862015308&quot;,&quot;name&quot;:&quot;example-repository&quot;,&quot;namespace&quot;:&quot;archetype-master&quot;}</pre><p>Hopefully you saw a Ansible-runner exited successfully so if the operator works properly there should be some ConfigMaps that weren&#39;t there before, right?</p><pre>$ oc get configmap -n archetype-master<br>NAME                            DATA      AGE<br>archetype-operator-lock         0         11m<br>customer-repository-configmap   3         11m<br>example-repository-configmap    3         11m</pre><p>If you clone this repo https://github.com/cvicens/archetype-operator-customer-service.git (the one we point to from our Custom Resource) and have a look to the contents of folder k8s you&#39;ll see two files that match exactly the two ConfigMaps created by the operator.</p><blockquote><em>Why don’t you fork this repo and change the Custom Resource to point to your own repo, then change the contents of the ConfigMaps and see what happens…</em></blockquote><p>So it works… I could stop here… but I thought it would be worth explaining how a developed locally, tested, failed and eventually made it work.</p><h3>Local testing</h3><p>There are at least two ways to test our operator locally (or outside the cluster).</p><p>The first one, supported and (potentially) easier, is explained <a href="https://github.com/operator-framework/operator-sdk/blob/master/doc/ansible/user-guide.md">here</a> in topic Run outside the cluster. Just be sure you meet the prerequisites, change to your project folder and run operator-sdk up local.</p><p>If for some reason this approach doesn’t work for you (id didn’t to me) here’s what I did:</p><ul><li>log in as your operator service account to your cluster</li><li>create a test playbook that invokes our role</li><li>run your test playbook</li></ul><h3>The Operator runs as a service account</h3><p>Let me remind you that an operator runs as a pod (in a container) where it invokes the Kubernetes/Openshift API as a certain service account. The name of this service account is set in spec-&gt;template-&gt;spec-&gt;serviceAccount, if not set it will be set as default. A file containing an API token for the pod’s service account is automatically mounted at /var/run/secrets/kubernetes.io/serviceaccount/token.</p><p>Next command shows that in this case the name of the service account is set to archetype-operator.</p><blockquote><strong><em>Note:</em></strong><em> along with the name of the service account a token is injected to a certain mount point </em><em>/var/run/secrets/kubernetes.io/serviceaccount/token</em></blockquote><pre>$ oc get deployment archetype-operator -o yaml -n archetype-master<br>apiVersion: extensions/v1beta1<br>kind: Deployment<br>metadata:<br>  name: archetype-operator<br>...<br>spec:<br>  ...<br>  template:<br>  ...<br>    spec:<br>      ...<br>      serviceAccount: archetype-operator</pre><p>Alright, so we have the name of the service account we want to use, but before we can log in as this service account we need to get the token that is injected to the pod. Next command shows that there is a mountable secret which is also referred to as a token: archetype-operator-token-5flc6 this is the one we need to use.</p><pre>oc describe sa/archetype-operator<br>Name:         archetype-operator<br>Namespace:    archetype-master<br>Labels:       &lt;none&gt;<br>Annotations:  kubectl.kubernetes.io/last-applied-configuration={&quot;apiVersion&quot;:&quot;v1&quot;,&quot;kind&quot;:&quot;ServiceAccount&quot;,&quot;metadata&quot;:{&quot;annotations&quot;:{},&quot;name&quot;:&quot;archetype-operator&quot;,&quot;namespace&quot;:&quot;archetype-master&quot;}}</pre><pre>Image pull secrets:  archetype-operator-dockercfg-kgmm4<br>Mountable secrets:   archetype-operator-dockercfg-kgmm4<br>                     archetype-operator-token-5flc6<br>Tokens:              archetype-operator-token-5flc6<br>                     archetype-operator-token-mpsjz<br>Events:              &lt;none&gt;</pre><p>Let’s get the token value and log in with it.</p><blockquote><em>Substitute with the correct secret name this should be a Token and Mountable secret</em></blockquote><pre>$ export SA_TOKEN=$(oc get secret archetype-operator-token-5flc6 -o json | jq -r .data.token | base64 -D)<br>$ oc login &lt;master_url&gt; --token ${SA_TOKEN}<br>Logged into &quot;https://master.serverless-d68e.openshiftworkshop.com:443&quot; as &quot;system:serviceaccount:archetype-master:archetype-operator&quot; using the token provided.</pre><pre>You have one project on this server: &quot;archetype-master&quot;</pre><pre>Using project &quot;archetype-master&quot;.</pre><blockquote><em>You can check you’re now logged in as the operator service account with this command.</em></blockquote><blockquote><em>$ oc whoami system:serviceaccount:archetype-master:archetype-operator</em></blockquote><h3>Setting up a Python virtual environment</h3><p>I’m using macOS and I found that in order to meet the requirements to run my role I needed to update Python to a level macOS didn’t like… so I googled my problem and hit <a href="https://sourabhbajaj.com/mac-setup/Python/virtualenv.html">this</a> gem.</p><p>So the idea is to create a virtual python environment… bear with me and run this commands inside the project folder.</p><pre>$ sudo pip install virtualenv<br>$ virtualenv venv<br>$ echo &quot;venv/&quot; &gt;&gt; .gitignore<br>$ source venv/bin/activate<br>(venv) $ pip install ansible ansible-runner ansible-runner-http openshift jmespath</pre><p>To leave the virtual env just deactivate it…</p><pre>$ deactivate</pre><h3>Running our role in vacuum?</h3><p>Obviously no, we need a Playbook to run our role and check if everything is alright or not. So please, create a new file call it playbook.yaml copy the next content in it and place it in the project folder.</p><pre>-<br>  name: Execute your roles<br>  hosts: localhost<br>  roles:<br>  - role: repository<br>    vars:<br>      meta:<br>        name: example-repository-2<br>        namespace: archetype-master<br>      git_url: &quot;https://github.com/cvicens/archetype-operator-customer-service.git&quot;<br>      git_ref: master</pre><p>As you can see we have added a vars section to our role, this is to feed the role as the operator itself does when running in the pod. Now let&#39;s test it!</p><pre>$ ansible-playbook -i myhosts playbook.yaml<br>...</pre><pre>TASK [repository : Delete &#39;to-be-deleted&#39; configmaps from namespace archetype-master] ********************************************************************</pre><pre>PLAY RECAP ********************************************************************<br>localhost           : ok=16   changed=1    unreachable=0    failed=0</pre><blockquote><em>Remember we’re running our role with a playbook run by Ansible locally using the current logged in user (a service account) to our cluster</em></blockquote><h3>Wrap up</h3><p>So… we started talking about how to manage and maintain configuration in a kubernetes namespace and we ended up with an Ansible role running in a pod in the shape of an operator. Not bad!</p><p>For me the biggest take away is not being afraid to create my own Ansible Operators I hope you think the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>💬<strong>.</strong></p><p><strong>To join our community Slack </strong>🗣️ <strong>and read our weekly Faun topics </strong>🗞️,<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b11b9b45734" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/could-a-kubernetes-operator-become-the-guardian-of-your-configmaps-1b11b9b45734">Could a Kubernetes Operator become the guardian of your ConfigMaps</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Operator Lifecycle Manager to deploy Prometheus on OpenShift]]></title>
            <link>https://faun.pub/using-the-operator-lifecycle-manager-to-deploy-prometheus-on-openshift-cd2f3abb3511?source=rss-15c32cd806ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd2f3abb3511</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Carlos Vicens]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 16:55:05 GMT</pubDate>
            <atom:updated>2019-07-19T15:37:47.047Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Qk535YvcDIRgM2mojZllmw.png" /><figcaption>Icons from <a href="https://www.flaticon.com/authors/photo3idea-studio">photo3idea-studio</a>, <a href="https://www.flaticon.com/authors/surang">surang</a>, <a href="https://www.freepik.com/">freepik</a>, <a href="https://commons.wikimedia.org/">commons-wikimedia</a> and <a href="https://github.com/operator-framework">operator-framework</a></figcaption></figure><p>Have you ever needed to install Prometheus or other piece of software on Kubernetes or OpenShift? In general is not a very difficult thing, right? You just process a template, run an image… (At least to a certain extend). The real problems usually surface after what we call day-1… Day-2 operations are not obvious on day-1 but you can imagine some: upgrades, changes in size or even morphology of the deployment, etc.</p><p>In this article, I explain step by step how to deploy the Prometheus Operator and how to monitor applications which are in a different namespace.</p><p><strong>TL;DR</strong></p><p>I provide with a step by step guide to deploy Prometheus on OpenShift using the Operator Lifecycle Manager (currently in Tech Preview in OpenShift).</p><p>I stress on how to check if your configuration is ok and also how to set the operator to monitor application across namespaces.</p><h4>What is the Prometheus Operator?</h4><p>Operators were introduced by CoreOS as a class of software that operates other software, putting operational knowledge collected by humans into software. For further information around the Operator Framework please go <a href="https://github.com/operator-framework/getting-started">here</a>.</p><p>The Prometheus Operator serves to make running Prometheus on top of Kubernetes as easy as possible, while preserving Kubernetes-native configuration options.</p><h4>The Operator Lifecycle Manager</h4><p>The Operator Framework (currently in Technology Preview phase) installs the Operator Lifecycle Manager (OLM), which aids cluster administrators in installing, upgrading, and granting access to Operators running on their OpenShift Container Platform cluster.</p><p>The OpenShift Container Platform web console has been is also updated for cluster administrators to install Operators, as well as grant specific projects access to use the catalog of Operators available on the cluster.</p><p>One of the Red Hat Supported Operators is the one we need for this lab, this means you don’t need to install the operator itself but to use it. As any other operator there are a set of objects (CRDs) we need to create to tell the operator how we want to install and operate Prometheus.</p><p>These are the objects we’ll need to create:</p><ul><li>Prometheus</li><li>ServiceMonitor</li><li>AlertManager (we want use it in this lab)</li></ul><p>The next image shows how they’re related. For further details please go <a href="https://coreos.com/operators/prometheus/docs/latest/user-guides/getting-started.html">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7cnpxuu-vWYkq7ciAPA_w.png" /><figcaption>Image borrowed from <a href="https://coreos.com/operators/prometheus/docs/latest/user-guides/getting-started.html">the getting started guide</a></figcaption></figure><h4>Prerequisites</h4><p>In order to follow this lab you’ll need:</p><ul><li>Have an OpenShift cluster to play with</li><li>A user who has been granted the cluster-admin role</li></ul><p>The next command lines show how to grant a user the cluster-admin role and create a project where we’ll install Prometheus.</p><pre>oc adm policy add-cluster-role-to-user cluster-admin &lt;user_name&gt;<br>oc new-project monitoring</pre><h4>End result of the lab</h4><p>The aim of this lab is to deploy the following architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwGOLNqfP4F8bYlK6TuQqQ.png" /><figcaption>Objects as YAML descriptors</figcaption></figure><ul><li>As you can see we need to define a <strong>Prometheus</strong> server ‘linked’ to a set of <strong>ServiceMonitors</strong> through a serviceMonitorSelector rule, in this case we’re interested on ServiceMonitors containing label k8s-app no matter which value it contains.</li><li>Additionally we’ll define a <strong>ServiceMonitor</strong> containg the required label k8s-app which in its turn we’ll trigger the scanning of Services according to the rule defined in the selector section (matches label <strong>team</strong>with value <strong>backend</strong>).</li><li>Finally <strong>port</strong> property in section endpoints of our <strong>ServiceMonitor</strong> should match the <strong>port</strong> name defined in our target <strong>Service</strong> objects.</li></ul><h4>Create a Prometheus subscription</h4><p>Please go to the OpenShift Web console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVzNJU9bjlkuJxEyalkxhg.png" /></figure><p>Then go to the Cluster Console and open the Operators➡Catalog Resources menu on the left. There we’ll create a Subscription which the way we manage the Prometheus Operator itself, not the servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VEGhSKU56ZLZ3tONMykXQ.png" /></figure><p>Make sure that the monitoring project we created before is selected before proceeding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DtcBntXkONFEW8uSPYQvA.png" /></figure><p>Now it’s time to create the Prometheus Operator subscription. Please, scroll down and click on the Create Subscription button close to the Prometheus Operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBjsbMEfOkLV-PsJHXu_Lg.png" /></figure><p>Now you should be presented with a default/example subscription descriptor, pay attention to the namespace, it should be monitoring. Once checked the namespace please click on Create</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwVDxjjsBc0_BagE-hl8Ig.png" /></figure><p>Example subscription:</p><pre>apiVersion: operators.coreos.com/v1alpha1<br>kind: Subscription<br>metadata:<br>  generateName: prometheus-<br>  namespace: monitoring<br>spec:<br>  source: rh-operators<br>  name: prometheus<br>  startingCSV: prometheusoperator.0.22.2<br>  channel: preview</pre><p>If everything goes as expected you should see something similar to this. You should see the upgrade status as Up to date, if that is the case click on the link pointed by the arrow which should take you to the Cluster Service Versions area (menu on the left).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQIxTYdsb0NUVPD5exw_TA.png" /></figure><p>You should be able to see the description and links to documentation of the Prometheus Operator along with a set of Create New commands, signaled with a red arrow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2a2NGoLbsFiQ7QQJCS1VvQ.png" /></figure><p>Good job, you have deployed the operator in project monitoring, in fact if you go to the OpenShift Application Console to project monitor you should see one instance of the prometeus-operator as in the next picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJAZnH7i5MfV_IAJdrw5lw.png" /></figure><p>Now let’s proceed with the deployment of the Prometheus server.</p><p><strong>Deployment of the Prometheus Server</strong></p><p>Go back to the Cluster Console and click on the Create New button and choose Prometheus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3YLtxw7685ljkvHh7qALA.png" /></figure><p>Next screen shows an example descriptor of a Prometheus server, go ahead and change metadata-➡name to server as in the image and click Create.</p><p><em>Pay attention to section </em><em>spec➡serviceMonitorSelector. There is where we define the match expression to select which Service Monitors we’re interested in. In this case we want Service Monitors with a label called </em><em>key. Also pay attention to </em><em>spec➡replicas, if you go to the OpenShift Application Console you’ll find a StatefulSet called prometheus</em><strong><em>-server</em></strong><em> with exactly 2 replicas</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_-_RwwsCLCgvPF3cSwVfg.png" /></figure><pre>apiVersion: monitoring.coreos.com/v1<br>kind: Prometheus<br>metadata:<br>  name: server<br>  labels:<br>    prometheus: k8s<br>  namespace: monitoring<br>spec:<br>  replicas: 2<br>  version: v2.3.2<br>  serviceAccountName: prometheus-k8s<br>  securityContext: {}<br>  serviceMonitorSelector:<br>    matchExpressions:<br>      - key: k8s-app<br>        operator: Exists<br>  ruleSelector:<br>    matchLabels:<br>      role: prometheus-rulefiles<br>      prometheus: k8s<br>  alerting:<br>    alertmanagers:<br>      - namespace: monitoring<br>        name: alertmanager-main<br>        port: web</pre><p><strong>Deploying a test application with monitoring enabled</strong></p><p>We’ve borrowed the following example from the <a href="https://coreos.com/operators/prometheus/docs/latest/user-guides/getting-started.html"><strong>Getting Started Guide</strong></a> of the <strong>Prometheus Operator</strong></p><p>Please follow the next steps to deploy a test application (3 pods) that exposes Prometheus metrics along with a Service that balances requests to the pods.</p><p>Let’s create a project for our application.</p><pre>oc new-project monitored-apps</pre><p>Let’s deploy the test application.</p><pre>$ cat &lt;&lt; EOF | oc create -n &quot;monitored-apps&quot; -f -<br>apiVersion: extensions/v1beta1<br>kind: Deployment<br>metadata:<br>  name: example-app<br>spec:<br>  replicas: 3<br>  template:<br>    metadata:<br>      labels:<br>        app: example-app<br>    spec:<br>      containers:<br>      - name: example-app<br>        image: fabxc/instrumented_app<br>        ports:<br>        - name: web<br>          containerPort: 8080<br>EOF</pre><p>Let’s check the status of those 3 pods.</p><pre>$ oc get pod -n &quot;monitored-apps&quot;<br>NAME                        READY     STATUS    RESTARTS   AGE<br>example-app-94c8bc8-jq5cr   1/1       Running   0          30s<br>example-app-94c8bc8-phfrv   1/1       Running   0          30s<br>example-app-94c8bc8-vfgr7   1/1       Running   0          30s</pre><p>Now let’s create a Service object to balance to these pods.</p><p><em>Pay attention to </em><em>spec➡port➡name as we explained before should match the value of </em><em>metadata➡endpoints➡port in the ServiceMonitor</em></p><pre>$ cat &lt;&lt; EOF | oc create -n &quot;monitored-apps&quot; -f -<br>kind: Service<br>apiVersion: v1<br>metadata:<br>  name: example-app<br>  labels:<br>    app: example-app<br>    team: backend<br>spec:<br>  selector:<br>    app: example-app<br>  ports:<br>  - name: web<br>    port: 8080<br>EOF</pre><h4>Let’s create a ServiceMonitor to scan our test Service</h4><p>Please go to the Cluster Console to the Operators➡Cluster Service Versions area. And click on Create Newand select Service Monitor.</p><p><strong><em>Remember</em></strong><em> that project should be </em><em>monitoring</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXhjUEdyAVZj9Zn3ZZ5y5Q.png" /></figure><p>The next descriptor will deploy a ServiceMonitor which is compliant with the rule we defined in our Prometheus object, namely: having a label named k8s-app</p><p><strong><em>Attention:</em></strong><em> we are creating the </em><strong><em>ServiceMonitor</em></strong><em> </em>in the same namespace<em> of the </em><strong><em>Prometheus</em></strong><em> object.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-6WkEV-froW6N3JAKPiRQ.png" /></figure><pre>apiVersion: monitoring.coreos.com/v1<br>kind: ServiceMonitor<br>metadata:<br>  name: backend-monitor<br>  labels:<br>    k8s-app: backend-monitor<br>  namespace: monitoring<br>spec:<br>  namespaceSelector:<br>    any: true<br>  selector:<br>    matchLabels:<br>      team: backend<br>  endpoints:<br>    - interval: 30s<br>      port: web</pre><p><strong><em>TIP: namespaceSelector</em></strong><em> could also define exactly which namespaces you want to discovered targets from</em></p><pre>spec:<br>  namespaceSelector:<br>    matchNames:<br>      - monitored-apps</pre><p><strong><em>UPDATED</em></strong></p><p>I’ve come across several people asking me to add a ServiceMonitor to collect metrics from Spring Boot 2 apps. Well here it is a sample descriptor.</p><p>Take into account that this ServiceMonitor watches Services with a label team: spring-boot-actuator. Also pay attention to the port 8080-tcp this could very likely be different in your case.</p><pre>apiVersion: monitoring.coreos.com/v1<br>kind: ServiceMonitor<br>metadata:<br>  labels:<br>    k8s-app: spring-boot-actuator-monitor<br>  name: spring-boot-actuator-monitor<br>  namespace: monitoring<br>spec:<br>  endpoints:<br>    - interval: 30s<br>      path: /actuator/prometheus<br>      port: 8080-tcp<br>  namespaceSelector:<br>    any: true<br>  selector:<br>    matchLabels:<br>      team: spring-boot-actuator</pre><h4>Checking configuration</h4><p>So far we have created a Prometheus server and a ServiceMonitor that points to a Service. Now we should check if everything is fine or not.</p><p>We can do this by checking Prometheus server logs, but before we do that we need to locate one of the pods, the next command will help us here.</p><pre>$ oc get pods -n monitoring<br>NAME                                   READY     STATUS    RESTARTS   AGE<br>prometheus-operator-7fccbd7c74-48m6v   1/1       Running   0          16h<br>prometheus-server-0                    3/3       Running   1          3h<br>prometheus-server-1                    3/3       Running   1          3h</pre><p>Now that we know the name of the pods we’re looking for we can read the logs. Next command gets us the logs of container prometheus in one of the target pods.</p><pre>$ oc logs prometheus-server-0 -c prometheus -n monitoring<br>...<br>level=error ts=2019-02-12T10:57:12.739199828Z caller=main.go:218 component=k8s_client_runtime err=&quot;github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go:289: Failed to list *v1.Pod: pods is forbidden: User \&quot;system:serviceaccount:monitoring:prometheus-k8s\&quot; cannot list pods in the namespace \&quot;monitored-apps\&quot;: no RBAC policy matched&quot;<br>level=error ts=2019-02-12T10:57:12.739190937Z caller=main.go:218 component=k8s_client_runtime err=&quot;github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go:288: Failed to list *v1.Service: services is forbidden: User \&quot;system:serviceaccount:monitoring:prometheus-k8s\&quot; cannot list services in the namespace \&quot;monitored-apps\&quot;: no RBAC policy matched&quot;<br>level=error ts=2019-02-12T10:57:12.73929972Z caller=main.go:218 component=k8s_client_runtime err=&quot;github.com/prometheus/prometheus/discovery/kubernetes/kubernetes.go:287: Failed to list *v1.Endpoints: endpoints is forbidden: User \&quot;system:serviceaccount:monitoring:prometheus-k8s\&quot; cannot list endpoints in the namespace \&quot;monitored-apps\&quot;: no RBAC policy matched&quot;</pre><p>Well… something is not ok… apparently the problem has to do with permissions over namespace monitored-apps.</p><blockquote><strong><em>system:serviceaccount:monitoring:prometheus-k8s</em></strong><em> cannot list endpoints in the namespace </em><strong><em>“monitored-apps”</em></strong></blockquote><p>So what we have to do is grant those required permissions (view) to the Service Account created by the operator and used by Prometheus.</p><p>We could grant a cluster-role to the service account, this way it can monitor any namespace, as in the next command.</p><pre>oc adm policy add-cluster-role-to-user view system:serviceaccount:monitoring:prometheus-k8s</pre><p>Or we can add permissions in a namespace basis as in the next one.</p><pre>oc adm policy add-role-to-user view system:serviceaccount:monitoring:prometheus-k8s -n monitored-apps</pre><p>Once you run one of the two versions, errors should stop appearing.</p><p>Further checking… would involve using the Prometheus console… in order to do so we need first expose the Service as in the next command.</p><pre>$ oc get svc -n monitoring<br>NAME                  TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE<br>prometheus-operated   ClusterIP   None         &lt;none&gt;        9090/TCP   13h<br>$ oc expose svc/prometheus-operated -n monitoring<br>route.route.openshift.io/prometheus-operated exposed</pre><p>Now please open the url returned by the next command and navigate to Status➡Targets</p><pre>$ oc get route -n monitoring<br>NAME                  HOST/PORT                                                                   PATH      SERVICES              PORT      TERMINATION   WILDCARD<br>prometheus-operated   prometheus-operated-monitoring.apps.serverless-8d48.openshiftworkshop.com             prometheus-operated   web                     None</pre><p>You should see something like this. There are three targets, one per pod.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJ1hWlPM47tdHRLQ9QMM0A.png" /></figure><p>Now if you navigate to Status➡Configuration you should be able to see that there’s a scrape_config entry per ServiceMonitor object, in our case we only have one, called backnd-monitor, the generated scrape-config name monitoring/backend-monitor/0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZgW6aDkt1UYmZQ_XfN0Hw.png" /></figure><h4>See it in action</h4><p>Now that we’re sure that our target service is being monitored we could go and see some graphs. To do so, navigate to Graph and start typing codelab in the Expression... textfield. Then choose one of the available metrics, for instance codelab_api_http_requests_in_progress …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqumPrxkMvLYu4AAOeApOA.png" /></figure><p>…and click on tab Graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3svPG-1iPC8OaSrtDxoSQ.png" /></figure><p>Congratulations, you’ve deployed Prometheus using the Operator Lifecycle Manager, deployed a service in a different namespace, tracked down a configuration error, fixed it and finally checked everything works… hopefully ;-)</p><p><strong>Wrap up</strong></p><p>This simple guide doesn’t go deep into the configuration of Prometheus, but shows how easy it is to set up Prometheus using the Operator Lifecycle Manager… but remember the real payoff starts on day-2 operations, so what’s easy today should be easy tomorrow too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*Piks8Tu6xUYpF4DU" /></figure><p><strong>Follow us on </strong><a href="https://twitter.com/joinfaun"><strong>Twitter</strong></a><strong> </strong>🐦<strong> and </strong><a href="https://www.facebook.com/faun.dev/"><strong>Facebook</strong></a><strong> </strong>👥<strong> and join our </strong><a href="https://www.facebook.com/groups/364904580892967/"><strong>Facebook Group</strong></a><strong> </strong>💬<strong>.</strong></p><p><strong>To join our community Slack </strong>🗣️ <strong>and read our weekly Faun topics </strong>🗞️,<strong> click here⬇</strong></p><figure><a href="https://www.faun.dev/join/?utm_source=medium.com%2Ffaun&amp;utm_medium=medium&amp;utm_campaign=faunmediumbanner"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSdFkACJxs5iy1oR" /></a></figure><h4>If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd2f3abb3511" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/using-the-operator-lifecycle-manager-to-deploy-prometheus-on-openshift-cd2f3abb3511">Using the Operator Lifecycle Manager to deploy Prometheus on OpenShift</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Open API to .Net Core on Openshift]]></title>
            <link>https://medium.com/@carlos.vicens.alonso/from-open-api-to-net-core-on-openshift-7d94b4fe52bd?source=rss-15c32cd806ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d94b4fe52bd</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[open-api]]></category>
            <dc:creator><![CDATA[Carlos Vicens]]></dc:creator>
            <pubDate>Fri, 11 Jan 2019 11:12:11 GMT</pubDate>
            <atom:updated>2019-01-11T11:12:11.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jS_4pdEsc-eX4hGqCKQLdg.jpeg" /></figure><h3>From Open API to .Net Core on Openshift</h3><h4>Using Apicurio Studio to design a sample inventory API</h4><p>This is part 1 of a 2-part story about how to move from designing an Open API specification to deploy the sample .Net Core code generated on Red Hat’s Kubernetes platform Openshift.</p><p>This 2-part story not a .Net Core tutorial, and I’m not a .Net Core/C# expert… what is even better to show how easy it is to create .Net Core microservices to run on Openshift taking an API first approach.</p><p><strong>TL;DR</strong></p><p>First of I’ll show you how to design an API for a simple inventory service using <a href="https://www.apicur.io/">Apicurio Studio</a>. In the next part I’ll show how to generate the code using OpenAPI Generator and how to deploy the code on Openshift.</p><p><strong>Tools</strong></p><p>In order to design our API we’re going to use <a href="https://www.apicur.io/">API Curio</a>, an online API designer supporting Open API 3.x and Swagger (Open API 2.x)</p><p>Please go to <a href="https://www.apicur.io/">API Curio</a> and login (you can user your github/google account to login)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nc0mPsS9LsUUnKhI87bWSQ.png" /></figure><p><strong>Designing the API</strong></p><p>After a successful login you should land in the dashboard area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fl5t1qlH1cUJw_h6DYRHfw.png" /></figure><p>Please, click on APIs (left side), there you should be able to see your APIs, none if it’s the first time you use it. Click on Create New API to start designing our Inventory API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X64yUqpr5VJzE7QK7xwxYQ.png" /></figure><p>Now give to your API Name, Description, select version Open API 3.0.2 and finally select Blank API as the starting point, as in the next picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8wIElgUrHaH_-0iDPL71Q.png" /></figure><p>At this point we have an empty API, so let’s start actually editing the API by clicking on Edit API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lzYRxMOuqj96yAYilrbNQ.png" /></figure><p>Click on Add a data Type or the plus sign next to Data Types.</p><p>The first thing we’re going to do is to create the InventoryItem type, so click on Add a data Type or the plus sign next to Data Types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aAWwn1qD8B8NmfQGQx6og.png" /></figure><p>In order to create our data type we have to provide a Name a Description and a sample JSON object (although optional we’re are going to use this feature to make the editing somewhat easier). After entering the following data please click on Save.</p><ul><li><strong>Name:</strong> InventoryItem</li><li><strong>Description:</strong> The root of the InventoryItem type&#39;s schema.</li><li><strong>Sample JSON object:</strong></li></ul><p>{&quot;itemId&quot;:&quot;329299&quot;,&quot;quantity&quot;:35}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AklWdD-RfDR4K7pAciGmnA.png" /></figure><p>Now that we have our InventoryItem data type, it’s time to define the API. Defining the API consist on defining paths like:</p><ul><li><strong>/api/inventory</strong> to get all the items in the inventory</li><li><strong>/api/inventory/{itemId}</strong> to get a specific item</li></ul><p>Let’s create our first path, click on `Add a Path`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ik1fOJYrPMhzWgtHyPQdg.png" /></figure><p>Please type /api/inventory and click on Add.</p><p>As you can see there are no operations defined yet. As the Inventory API should return all the items with a simple GET with no parameters. To do so let’s define a GET operation by selecting GET first and clicking on Add Operation afterwards.</p><blockquote><strong><em>GET</em></strong><em> should be selected (blue underlining) by default, if that’s not the case, please make sure it is.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1ME1nrSApjFM1RxoNcCLw.png" /></figure><p>Let’s edit the description and type something like: <strong>“Should return all elements as an array of InventoryItems or an empty array if there are none.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0lOv4FNSoqWjx-BL-EfuQ.png" /></figure><p>Now if you scroll down a little, you’ll see a warning sign underneath the Responses area. Click on Add a response to add an HTTP 200 response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVCC__jmi52BIQwUAIjE_w.png" /></figure><p>Click on Add (200 should be selected by default).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8kCkFNVyfTH--qMumZ0fw.png" /></figure><p>Add a description to the response, for instance: <strong>“Should return an array of InventoryItems”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVH_wNYQ3Vt8kRxylxRzwg.png" /></figure><p>Click on No response media types defined and then on Add media type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWXBD_SSXQjQ3xjjnIphcA.png" /></figure><p>Now, choose application/json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Er12dTSzpmbEeu_wBtD8qw.png" /></figure><p>The answer should be an Array (of JSON objects) of type InventoryItem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjSsq-UQjhppAR3ZiGN-ag.png" /></figure><p>Once you have chosen the proper type, please click on Add Example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0tsNU_H-FPPA5VM-M3uRw.png" /></figure><p>Copy and paste the following example and click on Add.</p><pre>[{&quot;itemId&quot;:&quot;329299&quot;,&quot;quantity&quot;:35},{&quot;itemId&quot;:&quot;329199&quot;,&quot;quantity&quot;:12},<br>{&quot;itemId&quot;:&quot;165613&quot;,&quot;quantity&quot;:45},{&quot;itemId&quot;:&quot;165614&quot;,&quot;quantity&quot;:87},<br>{&quot;itemId&quot;:&quot;165954&quot;,&quot;quantity&quot;:43},{&quot;itemId&quot;:&quot;444434&quot;,&quot;quantity&quot;:32},<br>{&quot;itemId&quot;:&quot;444435&quot;,&quot;quantity&quot;:53}]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jRLSmxgP_2l8waSzv4JfQ.png" /></figure><p>That’s all needed related to the first path, let’s do the same for the second. Remember click on the plus sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*cLJ4i5J9PTMDG_EGIGJJ-Q.png" /></figure><p>This time we need a path parameter to search for a specific, like this one: /api/inventory/{itemId}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9HDH1xGzZAtWAqB867hbQ.png" /></figure><p>Following up with the path parameter, scroll down to Path Parameters you’ll find that there is one already created (inferred from the path you typed in before). Click on Create to actually create it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eStAgCWS1PtV-PMtrc4WQ.png" /></figure><p>Then set the type of the parameter to String.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYqhQTV-VHRRLjqGuAQEmw.png" /></figure><p>We’re all set with regards to parameters, now it’s time to create an operation, again is a GET operation. So click on the Add operation button (make sure GET is selected).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2DllQOGxlY2KZSSCZL99g.png" /></figure><p>Again, let’s add a description to the action, something like: <strong>Returns the item for the id provided or an error</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VrFezI284Ahsp_nlT_12SQ.png" /></figure><p>Once again we have a warning in the Responses area we have to take care of. Please click on Add Response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfU7I_FZtR2nd2f-zdc60g.png" /></figure><p>Choose 200 (default) and click Add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtdaFHmDcLrg22g7P9_Tqw.png" /></figure><p>Let’s add a description, something like this: <strong>Should return the item for the id provided</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPle6or-UB-aQSv8-jTJWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXKhN2SRP4pYdW02XHKidQ.png" /></figure><p>As we did before, we have to add a media type application/json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVnD0Y6kdZPTtpNwv4U_AA.png" /></figure><p>Don’t forget to click on Add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPisIiWY3U2mpYabnS7krw.png" /></figure><p>This operation should return an inventory item, so please choose InventoryItem as the response type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzu78d8t0XsMq2u7FZOZUA.png" /></figure><p>As previously, let’s add an example, named OneItem</p><pre>{&quot;itemId&quot;:&quot;329299&quot;,&quot;quantity&quot;:35}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JeVgQo9cZXL5SeHCRGlOw.png" /></figure><p>We have to add another response for the case when we cannot find the item id provided. But before we do, we’re going to add a new type to encode the error as a JSON object. Click on the plus sign to create a new Data Type.</p><p>Create a new data type with the following values.</p><ul><li><strong>Name:</strong> GenericError</li><li><strong>Description:</strong> Generic Error Object.</li><li><strong>Sample JSON object:</strong></li></ul><p>{ &quot;code&quot; : &quot;404&quot;, &quot;message&quot; : &quot;Item 53 was not found&quot; }</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b55IivFDby_18kUBI6YOkQ.png" /></figure><p>Now let’s add a new response. This time the Status Code needs to be 404.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZEvdm9oRuBBEZvCc4RjnA.png" /></figure><p>Add a description as in the next pictures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilP2hkQYTrUlA8kdaUJHLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwBdcOu7K18F_v_Ul81F6w.png" /></figure><p>And as usual a new media type of type application/json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*it6m28MOPCHoMuXa5VtP9g.png" /></figure><p>This time we have to choose GenericError as the response type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wyiu0XLyOTmc4PSA494EA.png" /></figure><p>Finally let’s add a sample JSON object named NotFoundError.</p><pre>{<br>   &quot;code&quot; : &quot;404&quot;,<br>   &quot;message&quot; : &quot;Item 53 was not found&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*paeeq3O2GnPgO2Z6CVhzMA.png" /></figure><p>And that’s it, we have designed a pretty basic inventory API, including examples, documentations, etc. using Open API 3.x</p><p>Now you can export the specification as YAML, JSON, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFBb8EGUK6Ch7zsORPZO2w.png" /></figure><p><strong>Next steps</strong></p><p>In part 2 you’ll create .Net Core server stubs and deploy your generated code on Openshift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d94b4fe52bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going serverless on Openshift with OpenWhisk]]></title>
            <link>https://medium.com/@carlos.vicens.alonso/going-serverless-on-openshift-with-openwhisk-dafe49ddd861?source=rss-15c32cd806ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/dafe49ddd861</guid>
            <category><![CDATA[red-hat]]></category>
            <category><![CDATA[openwhisk]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[faa]]></category>
            <dc:creator><![CDATA[Carlos Vicens]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 12:16:01 GMT</pubDate>
            <atom:updated>2018-12-12T12:16:01.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kA-ZWl_Jl0-hVmy0yqLR5Q.jpeg" /><figcaption>Look ma no server!</figcaption></figure><h4>Set of ‘look ma no server’ demos to enjoy OpenWhisk</h4><p>A while ago I was proposed to run a tech lab around the ‘serverless’ buzzword. By then I was already aware of the concept (I tried AWS Lambda back in 2015) and actually liked it, but to be honest since those experiments I had had very little contact with serverless tech, until Red Hat released some interesting labs (more on this later) and I started again to feel the rush of pushing code and run it live. So… if you haven’t tried it, you should!</p><p><strong>TL;DR</strong></p><p>I’ll introduce you to a set of explained simple demos of increasing complexity.<br>I also give some hints to make sense of ‘serverless’ and ‘function as a service’ in the real world.<br>This is part 1 of (maybe) 3, other parts (code is already included in folder ./node) will include an Alexa Skill and an integration with AHOI API</p><p><strong>Pre-requisites</strong></p><p>In order to run these demos you need either an accessible [Openshift](<a href="https://www.openshift.com/learn/what-is-openshift/">https://www.openshift.com/learn/what-is-openshift/</a>) environment with around 5GB RAM / 50GB disk / 3 vCPU or a computer at hand with minishift installed and those free resources.</p><pre>$ minishift version<br>minishift v1.26.1+1e20f27</pre><p>Go <a href="https://docs.okd.io/latest/minishift/getting-started/preparing-to-install.html">here</a> for instructions to install minishift.</p><p>You’ll also need the Openshift CLI, go <a href="https://docs.openshift.com/container-platform/latest/cli_reference/get_started_cli.html">here</a> for instructions to install it.</p><p><strong>Where’s the code?</strong></p><p>In order to follow the guide my suggestion is to clone, fork, download the code. The repo is <a href="https://github.com/cvicens/openwhisk-demo">here</a>.</p><pre>$ git clone <a href="https://github.com/cvicens/openwhisk-demo">https://github.com/cvicens/openwhisk-demo</a><br>$ cd openwhisk-demo</pre><p>By default I’ll assume you’re in folder `openwhisk-demo` unless otherwise advised.</p><p><strong>Setting up the minishift environment</strong></p><blockquote>If you already have an Openshift environment you can skip this. You could also skip this if you want to use the learning area <a href="https://learn.openshift.com/serverless">here</a> (maybe you need to make slight changes… honestly I haven’t tried but it should work well)</blockquote><p>In order to set up our demo, we need to run ./01-setup-minishift.sh. Please have a look to ./00-environment.sh to confirm the default values for the minishift profile we’re going to create.</p><blockquote>Pay special attention to variables <strong>MINISHIFT_VM_DRIVER</strong> and <strong>PLATFORM</strong> to make then match your environment!</blockquote><pre>$ ./01-setup-minishift.sh</pre><p>After a while should get messages like these…</p><pre>$ ./01-setup-minishift.sh <br>Profile ‘openwhisk’ set as active profile.<br>No Minishift instance exists. New ‘memory’ setting will be applied on next ‘minishift start’<br>No Minishift instance exists. New ‘cpus’ setting will be applied on next ‘minishift start’<br>No Minishift instance exists. New ‘vm-driver’ setting will be applied on next ‘minishift start’<br>No Minishift instance exists. New ‘disk-size’ setting will be applied on next ‘minishift start’<br>Add-on ‘admin-user’ enabled<br>Add-on ‘anyuid’ enabled<br> — Starting profile ‘openwhisk’<br> — Check if deprecated options are used … OK<br> — Checking if <a href="https://github.com/">https://github.com</a> is reachable … OK<br> — Checking if requested OpenShift version ‘v3.11.0’ is valid … OK<br>…</pre><p>Now please log in to your minishift with the next script.</p><pre>$ ./02-login-minishift.sh</pre><p><strong>Deploying OpenWhisk on Openshift</strong></p><blockquote>If you have your own OpenShift environment, don’t forget to login in using the oc tool… otherwise you’ll get this message: You need to log in your Openshift cluster first…</blockquote><p>Deploying OpenWhisk on OpenShift means basically applying a template, a one-liner like this.</p><pre>oc process -f <a href="https://git.io/openwhisk-template">https://git.io/openwhisk-template</a> | oc create -f -</pre><p>To make it a little easier (I hope) I’ve prepared a script that creates a project/namespace (by default openwhisk-demo), deploys OpenWhisk in it, and downloads and sets up the OpenWhisk CLI wsk in ./bin</p><p>So let’s do this, please run the script as follows.</p><blockquote><strong>Please ignore this error if hit:</strong> unable to recognize no matches for kind “CronJob” in version “batch/v2alpha1”</blockquote><blockquote><strong>You can also use a local version of the template</strong> I fixed, to do so, look for ‘# Deploying OpenWhisk, choose the remote (default) or local template’</blockquote><pre>$ ./03-deploy-opewhisk.sh<br>Now using project “openwhisk-demo” on server “<a href="https://master.serverless-e442.openshiftworkshop.com/">https://master.serverless-e442.openshiftworkshop.com:443</a>&quot;.<br>…<br>to build a new example application in Ruby.<br>configmap/whisk.config created<br>…<br>alarmprovider-7755754445-hp2hc 0/1 Init:0/2 0 3s<br>controller-0 0/1 Init:0/2 0 5s<br>couchdb-0 0/1 ContainerCreating 0 4s<br>install-catalog-5jfjv 0/1 Init:0/1 0 5s<br>invoker-0 0/1 Init:0/2 0 4s<br>nginx-85697b95cf-zkgzl 0/1 Init:0/1 0 3s<br>…</pre><p>Finally you should see something like this, it’s a list of items you get by invoking wsk list. It means everything is set up correctly.</p><blockquote>Beware that commands are run like this ./bin/wsk -i because wsk is not in your PATH, -i is needed because we assume you don’t have an OpenShift environment using certificates signed by a recognized CA.</blockquote><pre> ./bin/wsk -i list<br>Entities in namespace: default<br>packages<br>/whisk.system/combinators shared<br>…<br>actions<br>/whisk.system/samples/curl private nodejs:6<br>…<br>triggers<br>rules</pre><p><strong>Running the demos</strong></p><p>There are several Javascript and Java examples, in general demos are divided into two scripts:</p><ul><li>one to deploy the function</li><li>and another one to run it</li></ul><p>Let’s start with the basics.</p><p><strong>NodeJS greeter.js demo</strong></p><p>The idea is to deploy a function like this one below, file ./node/greeter.js.</p><pre>function main(params) {<br> var name = params.name || ‘Guest’;<br> var place = params.place || ‘OpenShift Cloud Functions’;<br> return {payload: ‘Welcome to ‘ + place + ‘, ‘ + name};<br>}</pre><p>To deploy the function you only need to to this.</p><blockquote>Pay attention to the--web flag, this means we can invoke this action using HTTP</blockquote><pre>$ ./bin/wsk -i action update — web=true greeter ./node/greeter.js<br>ok: updated action greeter</pre><blockquote>The provided script 04-node-action-deploy.sh makes sure wsk is set up properly but it’s not mandatory to use it</blockquote><p>There are several way to run our function, using wsk synchronously/asynchronously, HTTP GET/POST, …</p><p>Calling our function synchronously, --result instructs to wait for the result.</p><pre>$ ./bin/wsk -i action invoke — result greeter -p name ‘Carlos’ -p place ‘Lisbon’<br>{<br> “payload”: “Welcome to Lisbon, Carlos”<br>}</pre><p>Same call, but this time in an asynchronous way</p><pre>$ ./bin/wsk -i action invoke greeter -p name ‘Carlos’ -p place ‘Lisbon’<br>ok: invoked /_/greeter with id 6c64b7206b5e483fa4b7206b5e483fad</pre><p>Now to get the result we do as follows.</p><pre>$ ./bin/wsk -i activation result 6c64b7206b5e483fa4b7206b5e483fad<br>{<br> “payload”: “Welcome to Lisbon, Carlos”<br>}</pre><p>If we want to use HTTP, first we need the URL.</p><pre>$ ./bin/wsk -i action get greeter — url | awk ‘FNR==2{print $1}’<br><a href="https://openwhisk-openwhisk-demo.apps.serverless-e442.openshiftworkshop.com/api/v1/web/whisk.system/default/greeter">https://openwhisk-openwhisk-demo.apps.example.com/api/v1/web/whisk.system/default/greeter</a></pre><p>If we store the result in a variable, we can then use `curl` for testing.</p><blockquote>&gt; **Pay attention!** You need to add ‘.json’ to the URL for the action to return JSON. ‘.text’ would return text, etc. Go [here](<a href="https://medium.com/openwhisk/serverless-http-handlers-with-openwhisk-90a986cc7cdd">https://medium.com/openwhisk/serverless-http-handlers-with-openwhisk-90a986cc7cdd</a>) for nice article mentioning web actions and other content types.</blockquote><pre>$ export WEB_URL=`./bin/wsk -i action get greeter — url | awk ‘FNR==2{print $1}’`<br>$ curl -k — silent -X GET ${WEB_URL}.json?name=Carlos\&amp;place=Madrid<br>{<br> “payload”: “Welcome to Madrid, Carlos”<br>}<br>$ curl -k — silent -d ‘{“name”:”Carlos”, “place”:”Barcelona”}’ -H “Content-Type: application/json” -X POST $WEB_URL.json<br>{<br> “payload”: “Welcome to Barcelona, Carlos”<br>}</pre><p>You can run all these calls with 05-node-action-run.sh</p><p><strong>Java simple demo</strong></p><p>The OpenWhisk Java runtime needs your function to have this exact signature.</p><pre>public static com.google.gson.JsonObject main(com.google.gson.JsonObject);</pre><p>Although it’s not necessary, as we just said the only requirement is to have a Java class including a method as specified, in this example we’re going to use a Maven archetype.</p><p><em>Our first task is to install the archetype</em></p><p>This can also be done by running the script ./06-maven-install-archetype.sh</p><pre>$ git clone <a href="https://github.com/apache/incubator-openwhisk-devtools">https://github.com/apache/incubator-openwhisk-devtools</a> ./tmp/incubator-openwhisk-devtools<br>$ cd ./tmp/incubator-openwhisk-devtools/java-action-archetype<br>$ mvn -DskipTests=true -Dmaven.javadoc.skip=true -B -V clean install</pre><p><em>Let’s create and deploy a Java function using the archetype as follows</em></p><blockquote>You can use the script 07-maven-action-deploy.sh to do this task or you can also adapt it to your needs, java package name, artifact ID, etc.</blockquote><pre>$ export ARTIFACT_ID=”demo-function”<br>$ mvn archetype:generate \<br> -DinteractiveMode=false \<br> -DarchetypeGroupId=org.apache.openwhisk.java \<br> -DarchetypeArtifactId=java-action-archetype \<br> -DarchetypeVersion=1.0-SNAPSHOT \<br> -DgroupId=com.redhat.serverless \<br> -DartifactId=${ARTIFACT_ID}<br> <br>$ cd ${ARTIFACT_ID}<br>$ mvn clean package</pre><p>After generating and packaging the sample function a jar file should have been generated at ./${ARTIFACT_ID}/target/${ARTIFACT_ID}.jar</p><p>Next step is to deploy our function in OpenWhisk, to do so we need the name of the action (in the next example is `demo`) the path to the jar file and the fully qualified name of the class that contains our function.</p><blockquote>By default when using the archetype -DgroupId=com.redhat.serverless means --main com.redhat.serverless.FunctionApp</blockquote><pre>./bin/wsk -i action update demo ./${ARTIFACT_ID}/target/${ARTIFACT_ID}.jar — main com.redhat.serverless.FunctionApp</pre><p><em>Running the action</em></p><p>Running the action is as easy as before.</p><blockquote>Again you can use this script 08-maven-action-run.sh</blockquote><pre>./bin/wsk -i action invoke demo — result</pre><p><strong>Java QR generator demo</strong></p><p>I’ve taken the code by Philippe Suter and used it in a Java class generated using the archetype I introduced before.</p><blockquote>The code of the QR generator class is original from Philippe Suter, and can be found <a href="https://github.com/psuter/openwhisk-java-gradle">here</a>.</blockquote><p>The mechanics are the same as before, the only change is the code of the function itself.</p><p>To deploy the function run the deploy script.</p><pre>$ ./09-maven-action-qr-gen-deploy.sh<br>…<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>[INFO] BUILD SUCCESS<br>[INFO] — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>[INFO] Total time: 3.288 s<br>[INFO] Finished at: 2018–12–11T19:09:11+01:00<br>[INFO] Final Memory: 22M/210M<br>[INFO] — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>ok: whisk auth set. Run ‘wsk property get — auth’ to see the new value.<br>ok: whisk API host set to openwhisk-openwhisk-demo.apps.example.com<br>ok: updated action qr</pre><p>To run the action you can either call the action like this…</p><blockquote>By adding | jq -r ‘.qr’ | base64 — decode &gt; qr.png you can decode the base64 into a proper PNG</blockquote><pre>$ ./bin/wsk -i action invoke -br qr -p text ‘Hola mundo!’ <br>{<br> “qr”: “iVBORw0KGgoAAAANSUhEUgAAASwAAAEsAQAAAABRBrPYAAABGklEQVR42u3aOxLCIBCAYag8BkdNjsoRLK1A3hBNokWA0fkpHBI+q51lYSfCfjPuAgaDwWCwn2IPkYaKM2nX9ELCxrH4ZFflZumnXYANYmsIkWr+EGIHm8J8ntxgc1l5hM1gNVEWHYJ1vr/BOrBaxHP5+FDrYdezZpi6eHbuhV3PfKKEiCnHQspYfTN7MYV1Za50B1EW8xYGG8akj44rGsnmC4aAjWSpWCw6nqeMzyB52OiA9WFyc7su2fKeMrB+rI5YSNJRKsQONorVA60/SsUr3VGVgXVjbdPPapEiZvVJ6xXWgW3aTSZly87+BhvAauzyO9gEZmKwSr8PNpI1Tb8wjbsXbCR7afoVcd56hV3K+BwCBoPBYH/DntCZZzz1A5uaAAAAAElFTkSuQmCC”<br>}</pre><p>…or run this script (again includes several ways to invoke the same action)</p><pre>./10-maven-action-qr-gen-run.sh</pre><p><strong>Want to try some of this live?</strong></p><p>Then go <a href="https://learn.openshift.com/serverless/">here</a> and enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dafe49ddd861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Flutter App that fits in with your micro-services strategy]]></title>
            <link>https://medium.com/@carlos.vicens.alonso/building-a-flutter-app-that-fits-in-with-your-micro-services-strategy-417a72e81732?source=rss-15c32cd806ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/417a72e81732</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[red-hat]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Carlos Vicens]]></dc:creator>
            <pubDate>Mon, 14 May 2018 20:03:57 GMT</pubDate>
            <atom:updated>2018-05-15T06:51:03.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReEFXTuFmqx9snKGl4oujQ.png" /></figure><h4>A story in three acts</h4><p>Have you ever waked up at night feeling uneasy and sweaty wondering if your mobile app is a monolith? I have, which makes sense because I spend most of my time fostering container based architectures that help you breaking the monolith in the back-end and the rest of my time building and helping others to build mobile apps.<br>To illustrate this I’ve create a sample live events app (the horrible monolith) to then add a timeline functionality as a module to show a log of comments during the live show.</p><p>Code samples should work straight away in Red Hat Mobile Application Platform, but could be adapted to run somewhere else.</p><h4><strong>Repos Cast</strong></h4><ul><li>Flutter App <a href="https://github.com/cvicens/flutter-gramola">here</a></li><li>Flutter Timeline Module <a href="https://github.com/cvicens/flutter-gramola-timeline">here</a></li><li>API (as a Red Hat Mobile Cloud App) <a href="https://github.com/cvicens/gramola-cloud-app">here</a></li></ul><h3>TL;DR</h3><p>I’ll show how to add functionalities to a Flutter App in a modular way using packages and explain why it fits quite well with a micro-services strategy.</p><h3>Act 1 — Falling in love</h3><p>So, one of those days I was helping customers to follow the Zombieland rules applied to innovation I talked to a friend about Flutter, I just brought up the subject because we use React Native at that event but I had heard about Flutter for quite some time and I wanted to know his opinion. I started saying I wasn’t convinced at all, a new language Dart, no signs of Javascript around… I was in love with RN I couldn’t help it… He replied that Dart wasn’t that different to Javascript and it was a strong typed language, so I ended up promising myself to give it a try. And I did.<br>I was really excited… It took me minutes to understand how to create a Flutter Plugin and run the sample code (I can tell that with React Native it took me way longer) so I had a crash, I couldn’t stop typing… Dart, to be honest at the beginning I didn’t even notice it was Dart… it just feels normal after Java, Javascript and Typescript. End result? I spent 2 days to create the first version of an SDK for our mobile services that run on Openshift.<br>You don’t believe me <a href="https://flutter.io/get-started/install/">install Flutter</a> and just do as follows and see it with your own eyes. More info <a href="https://flutter.io/developing-packages/#plugin">here</a>.</p><pre>flutter create — org com.example — template=plugin hello</pre><p>So as a proof of true love I created a Flutter App where you can login and see present and future live events. Not very useful to be honest, but enough to get the idea.<br>This App uses data it gets invoking a REST API ‘events’, see diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLbaWX4gIjl1Mls0KmOxzw.png" /></figure><p>Relevant elements, I’m using <a href="https://pub.dartlang.org/packages/fluro">Fluro</a> for routing and <a href="https://pub.dartlang.org/packages/flutter_flux">Flutter Flux</a> as a redux library.</p><p>If you have a look to the code you’ll find a pretty straightforward structure I spent some time looking out there for a nice structure and finally I took Sergi’s <a href="https://github.com/sergiandreplace/planets-flutter">planets</a> app as a reference, I also scavenged some nice pieces of code as well ;-)</p><p>The code is divided into config, model and components.</p><ul><li><strong>config</strong>: where routes, redux store, constants, etc. are defined</li><li><strong>components</strong>: basically where screens are</li><li><strong>model</strong>: where business object are</li></ul><h3>Act 2 — Recurrent nightmare</h3><p>So I was in love with Flutter, I could create nice looking and responsive apps for iOS and Android very fast, my life was full… but I kept having this recurrent nightmare at night (you know the ‘Pennywise the Clown’ saying: boo, your App is a monolith! kind of nightmare).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*nW00FKLAAPTK9X1mCZRz7A.jpeg" /></figure><h4>Was my app really a monolith?</h4><p>Yes, it’s was a binary (actually two, iOS and Android) right? Adding new features means adding code to the base code, adding tests, … so yes, pretty much a monolith at this point.</p><h4>Is it possible to ‘break it’?</h4><p>Yes and no, the truth is that in order to truly break this monolith I would need to be able not only to take it apart into pieces (mini-apps, modules) but to deliver those parts independently, potentially over the air (no need for a full app update).</p><p><strong>Those modules should be able to work independently and have a sole purpose.</strong> A good in-depth explanation about modularization can be found <a href="https://medium.com/@alexmngn/why-react-developers-should-modularize-their-applications-d26d381854c1">here</a><br> <br>Long story short, with Flutter you can create modules for your App that can be used also independently (the first part of breaking the monolith) but as of today you cannot deliver those modules independently.</p><p>In any case, although you cannot comply with the second part of the deal (as far as I know and as of today, May 2018), it’s way better to use a modularized approach than none at all.</p><h4>Creating a new feature as a module</h4><p>I remembered that the Flutter ‘create’ command had a type flag with three options, create and App, create a Plugin and <a href="https://flutter.io/developing-packages/#step-1-create-the-package">create a Package</a>... So next day I decided to modify my app to add a module (package) and test if I could give that module a completely separated and autonomous lifecycle. My idea was simple, I wanted to have a separate Git repo for this module including an example App to test it (something usual in Flutter packages, as you can see <a href="https://pub.dartlang.org/packages/image_picker">here</a> (tab ‘Example’). This way I could add this module to my App (or others) while maintaining a separate line of development, testing, etc.</p><p>Something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReEFXTuFmqx9snKGl4oujQ.png" /></figure><p>As you can see I wanted to ‘use’ a module called ‘timeline’ which sole purpose was request timeline entries for a specific user and event, as in the next picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*IlTi8wn7KiJqv1nBwFPfYQ.png" /></figure><p>To achieve this I had to create a module (Flutter package) as follows. For those eager to see code, the repo is <a href="https://github.com/cvicens/flutter-gramola-timeline">here</a>.</p><pre>flutter create -org com.redhat -t package gramola_timeline</pre><p>Then I created a Flutter App inside the package.</p><pre>cd gramola_timeline<br>flutter create — org com.redhat example</pre><p>Then I added the following dependency to the ‘pubspec.yaml’ of our ‘example’ project. As you can see the example project points to the module package ‘gramola_timeline’ using a relative path.</p><pre> gramola_timeline:<br>   path: ../</pre><p>The entry point for our Flutter package is ‘./lib/&lt;package-name&gt;.dart’, in our case ‘./lib/gramola_timeline.dart’.</p><p>After minimally testing the example project could use the sample class Calculator (sample code generated with ‘flutter create -t package’) in ‘gramola_timeline/lib/gramola_timeline.dart’ it was time to develop the component that I actually needed, a timeline.</p><p>With that purpose in mind I created a Widget called <a href="https://github.com/cvicens/flutter-gramola-timeline/blob/master/lib/gramola_timeline.dart">EventTimelineComponent</a> that you can use easily as in the following snippet.</p><pre>Navigator.push(<br> context,<br> new MaterialPageRoute(<br> builder: (context) =&gt; new EventTimelineComponent(<br> new TimelineConfiguration(<br> eventId: _eventIdFieldController.text, <br> userId: _userIdFieldController.text, <br> imagesBaseUrl: ‘’<br> )<br> )<br> ),<br>);</pre><p>In the snippet above I create the timeline component by providing an eventId and userId, (the imageBaseUrl is for a future update); then I push the Timeline component as a route in the navigator.</p><p>Once instantiated the component will look for a specific API, invoke it and render the results if any. Results should have the following shape.</p><pre>{<br> “id”: “0002”,<br> “eventId”: “0001”,<br> “userId”: “trever”,<br> “title”: “About to start ;-)”,<br> “date”: “2018–04–27”,<br> “time”: “18:30”,<br> “description”: “Presumably epic… let’s see!”,<br> “image”: “”<br>}</pre><p>As you can check our timeline widget is stateful and uses ‘<a href="https://pub.dartlang.org/packages/flutter_flux">flutter_flux</a><a href="https://github.com/google/flutter_flux)&#39;">&#39;</a> to manage the component state, if you haven’t exposed yourself to the Flux pattern you could start <a href="https://facebook.github.io/flux/docs/in-depth-overview.html#content">here</a> for an introduction.</p><p>I’d like to highlight that at the time of writing I couldn’t find a timeline component to show the timeline entries as I wanted, so I coded a CustomPainter for that. Go to ‘./lib/timeline_entry_row.dart’ and look for LinePainter. Needless to say how useful was the hot-reload to fine tune the LinePainter :-)</p><p>After all the coding this was the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FczM0eUAMEsdT8pnhVEKNA.png" /></figure><h3>Act 3 — Defeating Pennywise the Clown</h3><p>The idea is simple, our app should use the component in the same fashion as the example app, the only difference is that instead of defining the dependency of the ‘gramola_timeline’ package using a relative path, we want to depend of a certain version. To do so you could:</p><ul><li>publish your package in <a href="https://pub.dartlang.org/">https://pub.dartlang.org</a> and consume it as any other package</li><li>publish your package to your own package server</li><li>or just point to a git repo</li></ul><p>For simplicity I used the latter approach as in the following snippet.</p><pre> # Gramola timeline <br> gramola_timeline:<br>   git:<br>     url: <a href="https://github.com/cvicens/flutter-gramola-timeline">https://github.com/cvicens/flutter-gramola-timeline</a><br>     ref: v0.0.6</pre><p>Finally, let me show you how I use the timeline component in Gramola, our horrible monolith, now not that monolithic any more.</p><p>Because I’m using ‘fluro’, you have to go first to file <a href="https://github.com/cvicens/flutter-gramola/blob/master/lib/components/events/events_row_component.dart">events_row_component.dart</a> and look for function ‘_navigateToTimeline()’. There you’ll see I use a query like URL syntax to navigate to the timeline module providing values to query like variables ‘eventId’ and ‘userId’.</p><pre> _navigateToTimeline(context, String eventId, String userId) {<br> Navigator.pushNamed(context, ‘/timeline?eventId=$eventId&amp;userId=$userId’);<br> }</pre><p>So where’s the actual use of our timeline component? To find the answer you have to take a look at ‘<a href="https://github.com/cvicens/flutter-gramola/blob/master/lib/config/routes.dart">routes.dart</a>’ specifically where ‘/timeline’ route is defined and attached to ‘timelineRouteHandler’.</p><pre>static void configureRoutes(Router router) {<br> …<br> router.define(“/timeline”, handler: timelineRouteHandler);<br> …<br> }</pre><p>Finally have a look below to ‘timelineRouteHandler’, defined in file ‘<a href="https://github.com/cvicens/flutter-gramola/blob/master/lib/config/route_handlers.dart">route_handlers</a>’, as you can see this handler expects two parameters, ‘eventId’ and ‘userId’ to create our timeline component.</p><pre>…<br>var timelineRouteHandler = new Handler(handlerFunc: (BuildContext context, Map&lt;String, List&lt;String&gt;&gt; params) {<br> String eventId = params[“eventId”]?.first;<br> String userId = params[“userId”]?.first;<br> return new EventTimelineComponent(<br> new TimelineConfiguration(<br> eventId: eventId,<br> userId: userId,<br> imagesBaseUrl: ‘’<br> )<br> );<br>});<br>…</pre><p>So, in the end I have defined a navigation rule to navigate to the component defined in a module which has it’s own lifecycle, navigation, assets, widgets, etc.</p><p>Let me show you an image that illustrates a possible lifecycle of our app including yet another feature ‘ticketing’, just to give you a view of the whole repos scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Yqc8UE61nYKiM2CdrS0dw.png" /></figure><p>Let’s see the result, note that colors are different because the theme is different, so our module is Theme aware, not a bad thing to do by the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjirS1kEhRO8jGsBUEXrlg.png" /></figure><h3>Before the curtain falls</h3><p>[Voiceover]</p><p>Let me go back to my previous love, RN, remember? Well, with React Native by using ‘npm’ modules and ‘Code Push’ it’s possible to inject new modules without deploying a new binary (unless new native libraries are involved), basically it is possible to provide a tradeoff solution to the second part of the ‘breaking the monolith’ deal.<br> For a thorough insight into mini-apps it could be worth to have a look to <a href="https://medium.com/@prashantramnyc/microservices-architecture-for-mobile-application-development-part-i-20b4f4089a24">this article</a>, there Prashant Ram speaks explains the Walmart Labs approach to breaking the mobile app monolith by using React Native and an OTA server to push new mini-apps to a core app.<br> <br>Having said that and spent quality time with both Flutter and React Native it’s difficult to rule out one of them, in fact I think both are really good multi-platform frameworks that can help you create applications in a modular fashion while having a common (mostly) code base.</p><p>I hope these ideas will hopefully help you creating mobile apps that can keep the pace of innovation of your micro-services based back-end ;-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417a72e81732" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>