<?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[Zolo Engineering - Medium]]></title>
        <description><![CDATA[Technology, Design and Product @ Zolo - Medium]]></description>
        <link>https://medium.com/zolo-engineering?source=rss----2c3ca3d17328---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Zolo Engineering - Medium</title>
            <link>https://medium.com/zolo-engineering?source=rss----2c3ca3d17328---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:20:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/zolo-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Right Way to implement a Serverless Node.js application on AWS (Part 1)]]></title>
            <link>https://medium.com/zolo-engineering/right-way-to-implement-a-serverless-node-js-application-on-aws-part-1-c91185c54007?source=rss----2c3ca3d17328---4</link>
            <guid isPermaLink="false">https://medium.com/p/c91185c54007</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Ocean Balodiya]]></dc:creator>
            <pubDate>Fri, 10 Apr 2020 13:36:00 GMT</pubDate>
            <atom:updated>2020-04-10T13:35:59.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXWnUUgctnStgyHQp_TohQ.png" /><figcaption>We’ll nail that Lambda!</figcaption></figure><p>Serverless has become one of the red hot topics within the software development community and why not so, it relieves developers from server management, allows them to focus on the core project, offers greater scalability, and much more. One such framework which helps in building serverless apps with radically less overhead and the cost is <a href="https://serverless.com/">Serverless Framework</a>.</p><p>We, at Zolo, have many microservices some of which often don’t get used as much as others owing to their specific use cases. These services add to the server cost and the time required to manage and maintain them. This was a perfect opportunity for us to try out Serverless. Now we have 2 serverless services up and running in production.</p><p>In this article, we will gloss over the process of making a Node.js app serverless and deploying it in production via Jenkins pipeline. This will be more of a hands-on tutorial/guide and we will divide this whole process into the following sub-tasks:</p><ol><li>Creating your Node.js app serverless</li><li>Using Custom domain to access your serverless app</li><li>Restricting IAM Permissions that we give to Serverless Framework</li><li>Creating a CI/CD Pipeline for deployment</li></ol><h3><strong>1. Creating your Node.js app serverless</strong></h3><p>If you are totally new to the serverless realm, we would suggest you read <a href="https://hackernoon.com/a-crash-course-on-serverless-with-node-js-632b37d58b44">this</a> article before continuing, though we will go through with the basic steps of installing serverless without going into details.</p><p><strong>i. Installing Serverless</strong></p><pre>$ npm install -g serverless</pre><p><strong>ii. Giving Serverless AWS’ Programmatic access</strong></p><p>Create a user in AWS with full access ( Administrative Access ) for now. We will restrict its permissions in step 3.</p><pre>$ serverless config credentials --provider aws --key &lt;ACCESS_KEY&gt;   --secret &lt;SECRET_KEY&gt;</pre><p><strong>iii. Create a Node.js Template in Your Working Directory</strong></p><pre>$ serverless create --template aws-nodejs --path hello-world-service</pre><p><em>Folder structure:</em></p><pre>&lt; Your working directory &gt;<br>|<br>├── hello-world-service<br>   ├── .gitignore<br>   ├── handler.js<br>   ├── serverless.yml</pre><p><strong>iv. Copying your app directory inside the service folder</strong></p><p>As specified, copy your whole app directory inside the folder ( hello-world-service ) which was just created.</p><p><em>Folder structure after copying your app:</em></p><pre>&lt; Your working directory &gt;<br>|<br>├── hello-world-service<br>   ├── .gitignore<br>   ├── handler.js<br>   ├── serverless.yml<br>   ├── <strong>app.js</strong>       // main entry, *<strong>other files/folders can differ*<br>   </strong>├── <strong>package.json</strong> // packages info, *<strong>other things can differ*<br></strong>   ├── config       // The configuration of my applications<br>   ├── models       // The model data (e.g. Mongoose model)<br>   ├── node_modules // modules required by the app<br>   ├── routes       // Routes of my app (client-side code)<br>   ├── controllers  // The route definitions and implementations<br>   ├── services     // The standalone services (Database service)<br>   ├── repositories // repositories used by services<br>   ├── Dockerfile   // For Building Docker images<br>   └── Jenkinsfile  // For CI/CD deployment using Jenkins</pre><blockquote>NOTE: It’s not mandatory that your app’s folder structure should look like this, this is just for reference. You should at least have a <strong>package.json</strong> file and an <strong><em>app.js</em></strong> file. We require <strong>package.json</strong> file as it holds various metadata relevant to the project. The point below explains the importance of app.js file.</blockquote><p><strong>v. Making changes in the app.js file</strong></p><p>Before any changes, your app.js file will look something like <a href="https://gist.github.com/Ocean-Balodiya/735ec8704da980b0183cc22854e953d7">this</a>. You need to install <strong>serverless-http </strong>and<strong> </strong>import it in your app.js file at the starting. After this, you need to export serverless(app) at the end, as shown.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37050c029b747f90e85677b378658804/href">https://medium.com/media/37050c029b747f90e85677b378658804/href</a></iframe><blockquote>NOTE: Make sure you include this package in <a href="https://gist.github.com/Ocean-Balodiya/76647b5b893d0c7a0fb10c39f8504e34">package.json file</a> in dependencies.</blockquote><p><strong>vi. Configuring serverless.yml</strong></p><p>Open up the serverless.yml file and copy-paste the following file. Make sure to read the comments which I have written to understand what each and every line of the file is doing and how you can configure it according to your needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0fa5389d7f05f537cbfa402e3f1a0b3/href">https://medium.com/media/d0fa5389d7f05f537cbfa402e3f1a0b3/href</a></iframe><blockquote>NOTE: Follow <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-console.html">this link</a> to add parameters in Parameter store in System Manager in AWS. As is advisable not to store sensitive information and secrets in git repo, <a href="https://aws.amazon.com/blogs/mt/the-right-way-to-store-secrets-using-parameter-store/">we are using Parameter store</a>.</blockquote><p><strong>vii. Spinning up serverless-offline</strong></p><p>Install serverless-offline to test your app locally without having to deploy it in AWS.</p><pre>$ npm install serverless-offline --save-dev<br>$ serverless offline start</pre><p>Your Lambda is now running on your localhost. The default port is 3000. Feel free to open up a browser and check it out. For example, hitting the endpoint http://localhost:3000/api/v1/foo will send back “ Say yayy to Serverless !” to your browser.</p><p>If you want to stop here and deploy your function in AWS. Use the following command to do that. This command translates all syntax in serverless.yml to a single AWS CloudFormation template.</p><pre>$ serverless deploy -v</pre><p>You will get some weird looking logs which is basically logging the steps which serverless is doing and what all changes it is making to your AWS account. In the end, you can find the API endpoints which you can use to hit your serverless app. It will look something like this: https://c0844479234s8.execute-api.ap-south-1.amazonaws.com/production/</p><p>Append the routes of your app at the end of this and see the magic work. This will look something like this, obviously, your API endpoint will be different.</p><p><a href="https://c0844479234s8.execute-api.ap-south-1.amazonaws.com/production/">https://c0844479234s8.execute-api.ap-south-1.amazonaws.com/production/</a>api/v1/foo</p><h3>2. Using Custom domain to access your serverless app</h3><p>We have now deployed our serverless app but using AWS API Gateway results in odd hostnames for our endpoints. Further, to add to our misery, these names are not permanent and can change if we remove or redeploy.</p><p>First of all, you’ll need to have a certificate issued for your domain. If you have that go on, but if you don’t, read the first section of <a href="https://serverless.com/blog/serverless-api-gateway-domain/">this link</a>.</p><p>Add the following block to your serverless.yml file, so that serverless can configure the custom domain on our behalf. Read the comments and edit this block according to your needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa46a012d3ee0cd8bee36de0bb49cbca/href">https://medium.com/media/aa46a012d3ee0cd8bee36de0bb49cbca/href</a></iframe><p>The new file will look like <a href="https://gist.github.com/Ocean-Balodiya/523d3c7485e7d2bc76765e637549e5b8">this</a>. Now, run the following commands.</p><pre>$ npm install serverless-domain-manager<br>$ sls create_domain<br>$ serverless deploy -v</pre><p>The above 2 commands install serverless-domain-manager and will create the domain ( sls is short for serverless, you can use this as well ). Then, the 3rd one will deploy our application again.</p><h3>3. Restricting IAM Permissions that we give to Serverless Framework</h3><p>Up till now, we have given Serverless Framework Administrative Access to our AWS account, with that it can basically create or delete anything. This is not an ideal practice and we should restrict access to only the services it is using and only those resources which it has created or will create so that it doesn’t mess with other services and resources which are not relevant to it.</p><p>There is a <a href="https://github.com/dancrumb/generator-serverless-policy">plugin recommended</a> by Serverless Framework themselves <a href="https://serverless.com/blog/abcs-of-iam-permissions/">here</a>. But the thing is that this plugin doesn’t always knit the perfect fit for you. Inspired by the <a href="https://github.com/serverless/serverless/issues/1439#issuecomment-231428957">ghost’s answer</a> to <a href="https://github.com/serverless/serverless/issues/1439">this discussion</a>, we have created our perfect fit. We will go through each and every policy so that you can also do the same.</p><blockquote>NOTE: We have written the policies such that you will have to edit the parameters enclosed in &lt; ……….. &gt; according to your need, such as you should replace <strong>&lt;REGION_NAME&gt;</strong> with <strong>ap-south-1 </strong>(without the brackets) if that’s your region and <strong>&lt;ACCOUNT_KEY&gt;</strong> with the account key associated with your AWS account and <strong>&lt;NAME_OF_SERVICE&gt;-&lt;NAME_OF_STAGE&gt;</strong> with service and stage name mentioned in your serverless.yml file, here, it will be replaced by <strong>hello-world-service-production</strong></blockquote><p><strong>i. </strong><a href="https://gist.github.com/Ocean-Balodiya/98e7078054245263bc15fb9c956412f8#file-serverless_basepolicy-json"><strong>Serverless_BasePolicy.json</strong></a></p><p>Read-only permissions generally required by serverless deployments and relatively harmless via their read-only limitation. These permissions don’t require any change as they are read-only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6329a30ce415676b25ba359bab23073/href">https://medium.com/media/e6329a30ce415676b25ba359bab23073/href</a></iframe><p><strong>ii. </strong><a href="https://gist.github.com/Ocean-Balodiya/5fc977b985ddb55102f138578a52fe0b#file-serverless_customdomainpolicy-json"><strong>Serverless_CustomDomainPolicy.json</strong></a></p><p>These are the permissions that are required for making a custom domain. If you are not planning on having a custom domain then you can skip this policy. This only requires region change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29c3c4e22f7b8e8821d3561c2719d610/href">https://medium.com/media/29c3c4e22f7b8e8821d3561c2719d610/href</a></iframe><p><strong>iii. </strong><a href="https://gist.github.com/Ocean-Balodiya/e5266d89cfe644e55d4ca780f9bf909d#file-serverless_endpointpolicy-json"><strong>Serverless_EndpointPolicy.json</strong></a></p><p>These are the permissions required to write i.e. update, delete actions, etc. required by — <em>sls endpoint deploy. </em>This only requires region change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1843dc16c2b43c334183e4462c388847/href">https://medium.com/media/1843dc16c2b43c334183e4462c388847/href</a></iframe><p><strong>iv. </strong><a href="https://gist.github.com/Ocean-Balodiya/3e91e5555441b9a71d44e9fe58e91d6a#file-serverless_eventpolicy-json"><strong>Serverless_EventPolicy.json</strong></a></p><p>Write Permissions required by — <em>sls event deploy.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19b89b7b43dc05cbbf5734d744026d88/href">https://medium.com/media/19b89b7b43dc05cbbf5734d744026d88/href</a></iframe><p><strong>v. </strong><a href="https://gist.github.com/Ocean-Balodiya/e12159856a9e0af09fbc55c34d2f0962#file-serverless_functionpolicy-json"><strong>Serverless_FunctionPolicy.json</strong></a></p><p>Write permissions required by — <em>sls function deploy</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2260ed8b86dff4a20ae50462e6d1fd8/href">https://medium.com/media/c2260ed8b86dff4a20ae50462e6d1fd8/href</a></iframe><p><strong>vi. </strong><a href="https://gist.github.com/Ocean-Balodiya/24a38977b8816530d3d06edc1505a09c#file-serverless_resourcepolicy-json"><strong>Serverless_ResourcePolicy.json</strong></a></p><p>Write permissions required by — <em>sls</em> resources deploy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a301dc33d9e1298a37344b4731d7cff6/href">https://medium.com/media/a301dc33d9e1298a37344b4731d7cff6/href</a></iframe><p>Create these policies in your AWS account and assign them to the user which you have created earlier. Remove the AdministrativeAccess policy which we have assigned earlier. Deploy the app again, using new permissions to check whether everything is working fine or not.</p><p>If you are not able to deploy using these permissions set an environment variable SLS_DEBUG=* using the following command.</p><pre>$ export SLS_DEBUG=*<br>$ serverless deploy -v</pre><p>This will give you all the logs, through which we can find out the exact problem. Another way that we used to debug this was, we used the CloudFormation service offered by AWS. You can click on the stack name, it will follow the pattern <strong>&lt;NAME_OF_SERVICE&gt;-&lt;NAME_OF_STAGE&gt;, </strong>and then you can go to the <strong>Events</strong> tab present beside <strong>Stack info </strong>tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKyyuat2ZkY7JjhUdEmPhg.png" /><figcaption>CloudFormation Console</figcaption></figure><p>This article doesn’t include the last point on how to make a CI/CD deployment pipeline using Jenkins. That will be covered in an upcoming article which I will link here. Then we will be able to deploy the application, with a matter of few clicks, instead of writing these commands every time from our local machine. With this knowledge and tools mentioned, we have more or less everything we need to create awesome, scalable, and reliable serverless Node.js applications.</p><p><em>PS:</em> <em>If you are into Serverless, Node.js and find terms like these exciting as much as we do, then drop us a line at </em><a href="/service/mailto:join-tech@zolostays.com"><em>join-tech@zolostays.com</em></a><em>. We would love to take you out for a Coffee ☕ to discuss the possibility of you working with us.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c91185c54007" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zolo-engineering/right-way-to-implement-a-serverless-node-js-application-on-aws-part-1-c91185c54007">Right Way to implement a Serverless Node.js application on AWS (Part 1)</a> was originally published in <a href="https://medium.com/zolo-engineering">Zolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Active-MQ in a Kubernetes cluster]]></title>
            <link>https://medium.com/zolo-engineering/deploying-active-mq-in-a-kubernetes-cluster-3674f4fd6210?source=rss----2c3ca3d17328---4</link>
            <guid isPermaLink="false">https://medium.com/p/3674f4fd6210</guid>
            <category><![CDATA[queue-management]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[activemq]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Vologue]]></dc:creator>
            <pubDate>Mon, 06 Apr 2020 09:01:36 GMT</pubDate>
            <atom:updated>2020-04-06T09:01:36.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*Zq2W9XGGFXLHNuY7yMl8uQ.png" /><figcaption>Active-MQ and K8s</figcaption></figure><p><a href="https://activemq.apache.org/"><strong>Active-MQ</strong></a> or apache-amq is a convenient little program/service which is used to temporarily store and send messages. It is written in Java and comes with JMS (Java Message Service). In essence, it is a message broker which can work with multiple protocols and hence can cater to a larger selection of devices.</p><p>It is used to integrate multi-platform applications using the ubiquitous AMQP protocol, exchange messages between web applications using STOMP over web-sockets etc.</p><p>Amazon web services (AWS) offers AmazonMQ as a service. Though this is reliable, it is also very costly.</p><p><strong>For example</strong>- It costs <strong>$0.576</strong> per hour (for an mq.m5.large in the US East (N. Virginia) region)</p><p>Then for a month-<br> <strong>744</strong>(number of hours in a month)*<strong>0.576</strong> = <strong>$428.54</strong>.</p><p>Which is quite expensive. So we decided to shift our AmazonMQ message broker to our Kubernetes cluster. While we were reading up for this we couldn’t find many articles and those which we did find were incomplete. So we decided to write a how-to article (This is that article).</p><p>In this article, we will be setting up a deployment for Active-MQ. we will also mount the dashboard credentials as a secret (because duh). we will also be creating a service and ingress.</p><h3>Step 1: Building the image with docker</h3><p>For the purpose of this article, lets use <a href="https://hub.docker.com/_/openjdk"><strong><em>“openjdk:8-jre-alpine”</em></strong></a> as the base image.</p><p><strong>OpenJDK</strong> — because active-mq requires java and this saves us the extra step of installing it in ubuntu or alpine base image.</p><p><strong>8-jre-alpine</strong> — because of its small size. Alpine images are very small and bare-bone which makes them light and fast.</p><p>The docker file looks like:</p><pre><em>FROM openjdk:8-jre-alpine<br>WORKDIR /home/alpine<br>RUN apk update &amp;&amp; apk add wget<br>RUN wget -O amq.tar.gz http://apachemirror.wuchna.com//activemq/5.15.10/apache-activemq-5.15.10-bin.tar.gz &amp;&amp; tar -xvf amq.tar.gz<br>EXPOSE 8161 61616 5672 61613 1833<br>CMD [&quot;/bin/sh&quot;,&quot;apache-activemq-5.15.10/bin/activemq&quot;,&quot;console&quot;]</em></pre><p>Okay, let us go through this line by line</p><p><strong><em>FROM</em></strong> — sets the base image (will pull if not present while building)</p><p><strong><em>WORKDIR</em></strong> — This sets the working directory in the container. Here the working directory is set to /home/alpine</p><p><strong><em>RUN</em></strong> — Runs a shell command. Here RUN is used to install wget, which is then used to download AMQ (a tar file) and tar is used to extract it.</p><p><strong><em>EXPOSE</em></strong> — This allows incoming and outgoing connections to the container at the specified ports. Basically “exposes” the port. Each port specified here is used by a different protocol. A comprehensive list can be found in active-mq’s <a href="https://activemq.apache.org/protocols">documentation</a>.</p><p><strong><em>CMD</em></strong> — This directive is used to execute something when the container is initialized. Here it is being used to start the server.</p><p>Once the docker file is created, open a terminal and run the following command to build the image.</p><pre><em>docker build -t [name of the image to be created] [path to the dicretory containing the dockerfile]</em></pre><p>Now to push it to a registry from where Kubernetes can pull the image to create a pod.</p><pre><em>$docker push [name of the image]</em></pre><h3>Step 2: Creating namespaces and secrets</h3><p>It is a good practice to have every new application in a different namespace as it reduces clutter and often helps in isolating a problem. <br>To create a namespace just run the following:</p><pre><em>kubectl create namespace active-mq</em></pre><p>Now that a namespace has been created, we need to add the credentials required to access the dashboard to the Kubernetes cluster as secrets. There are multiple methods to create secrets all of which are documented in <a href="https://kubernetes.io/docs/concepts/configuration/secret/">k8s’s documentation</a>. Here we will be creating it using kubectl.</p><p>Create a file “<em>jetty-realm.properties</em>”. This is the file which stores user credentials and their roles in active-mq. We are gonna populate this file with custom usernames and passwords and replace the file present by default inside the container.</p><p>To the file add the following content:</p><pre># username: password ,[role-name]<br>admin_username: admin_pass, admin<br>guest-user: guest-pass, guest</pre><p>To create the secret run:</p><pre><em>kubectl create secret generic creds --from-file=jetty-realm.properties -n active-mq</em></pre><p>This will create a secret called “creds” in the namespace active-mq.</p><h4>Step 3: Creating the deployment and service objects in Kubernetes</h4><h4>Deployment</h4><p>This step is pretty straight forward. Only we need to take care while mounting the secret. It is necessary to provide the ‘subPath’ otherwise the rest of the configuration files will be overwritten and the server won’t start. My yaml file looks a little bit like this:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: active-mq<br>  labels:<br>    app: active-mq<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: active-mq<br>  template:<br>    metadata:<br>      labels:<br>        app: active-mq<br>    spec:<br>      containers:<br>        - image: [name-of-my-image-from-docker-hub]<br>          name: active-mq<br>          imagePullPolicy: Always<br>          resources:<br>            requests:<br>              memory: 500Mi<br>              cpu: 200m<br>            limits:<br>              memory: 1000Mi<br>              cpu: 400m<br>          volumeMounts:<br>          - name: active-creds<br>            mountPath: /home/alpine/apache-activemq-5.15.10/conf/jetty-realm.properties<br>            subPath: jetty-realm.properties<br>      volumes:<br>      - name: active-creds<br>        secret:<br>          secretName: creds<br>      restartPolicy: Always</pre><p>This will create a deployment with one pod with custom credentials.</p><pre><em>kubectl create -f deployment.yaml -n active-mq</em></pre><h4>Service</h4><p>In this step, we will be creating the yaml for active-mq service and deploying it. In the service.yaml file we must be careful while declaring the ports and only open ports which are being used and name them accordingly. My yaml file looks a little like:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: active-mq<br>  namespace: active-mq<br>  labels:<br>    app: active-mq<br>spec:<br>  selector:<br>    app: active-mq<br>  ports:<br>  - name: dashboard<br>    port: 8161<br>    targetPort: 8161<br>    protocol: TCP<br>  - name: openwire<br>    port: 61616<br>    targetPort: 61616<br>    protocol: TCP<br>  - name: amqp<br>    port: 5672<br>    targetPort: 5672<br>    protocol: TCP<br>  - name: stomp<br>    port: 61613<br>    targetPort: 61613<br>    protocol: TCP<br>  - name: mqtt<br>    port: 1883<br>    targetPort: 1883<br>    protocol: TCP<br>  type: LoadBalancer<br></pre><p>To deploy the service to Kubernetes cluster:</p><pre><em>kubectl create -f service.yaml -n active-mq</em></pre><figure><img alt="Kubernetes Dashboard" src="https://cdn-images-1.medium.com/max/1024/1*Y6Z8orDODmMFn4-Zvxt0qw.png" /><figcaption>Kubernetes Dashboard</figcaption></figure><p>This will deploy the service. Since the service is of the type <em>load-balancer</em>, this will expose it to the public at the host-name of the load-balancer set up by your cloud provider. The dashboard and the rest api is exposed on the port 8161. dashboard at ‘/’ and rest api at ‘/api/message’ for more information read the <a href="https://activemq.apache.org/rest">official documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wssynLKulupX3ddfDetvPA.png" /><figcaption>Active-MQ dashboard</figcaption></figure><p>If in case you don’t want the service to be exposed on a separate load-balancer, then you can set the type to ClusterIP and create an ingress to route the traffic accordingly. However, you can access the dashboard using the port-forward command.</p><pre><em>kubectl port-forward svc/active-mq 8161:8161 -n active-mq</em></pre><p>Now the dashboard will be available at <a href="http://localhost:8161/">http://localhost:8161</a>.</p><h3>Clean-up</h3><p>To delete the deployment simply delete the namespace. This will remove everything in that namespace (along with Active-mq deployment)</p><pre><em>kubectl delete namespace active-mq</em></pre><p><em>If you are into DevOps or Fullstack and find terms like ServiceMesh, Infrastructure Automation, Event Loop and Micro-Frontends exciting as much as we do, then drop us a line at </em><a href="/service/mailto:join-tech@zolostays.com"><em>join-tech@zolostays.com</em></a><em>. We would love to take you out for a Coffee ☕ to discuss the possibility of you working with us.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3674f4fd6210" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zolo-engineering/deploying-active-mq-in-a-kubernetes-cluster-3674f4fd6210">Deploying Active-MQ in a Kubernetes cluster</a> was originally published in <a href="https://medium.com/zolo-engineering">Zolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Automation Testing at Zolostays]]></title>
            <link>https://medium.com/zolo-engineering/our-journey-to-automated-front-end-testing-2a7009e85e1b?source=rss----2c3ca3d17328---4</link>
            <guid isPermaLink="false">https://medium.com/p/2a7009e85e1b</guid>
            <category><![CDATA[zalenium]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[nightwatchjs]]></category>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Kushagra Mangal]]></dc:creator>
            <pubDate>Mon, 06 Apr 2020 09:00:02 GMT</pubDate>
            <atom:updated>2020-04-06T10:31:33.859Z</atom:updated>
            <content:encoded><![CDATA[<p><em>As many of us have already heard “With great power comes greater responsibilities”. Similarly, when you build software that is going to be used by customers, you need to tread carefully to ensure that your customer gets the best experience from your product. This is where testing comes into the picture.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75RcsaZW-k0J65oaGpkaxw.png" /></figure><p><strong>At Zolo initially, our development pipeline was -</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jtK21EBfWJAXXqy27V4RA.png" /><figcaption>Old pipeline</figcaption></figure><ol><li>Get feedback to create a feature</li><li>Develop the feature</li><li>Deploy to QA servers</li><li>Wait for days to get QA sign-off</li><li>Fix any bugs found by QA</li><li>Finally after QA sign-off deploy to production.</li></ol><p><strong>This process had the following issues:</strong></p><ol><li>Wait for QA to completely test the product to find all the bugs in mobile and web in all the browsers is going to be a lengthy cycle.</li><li>As its a manual process there is a high probability that some tests will be missed</li><li>The feedback loop between deployment and bugs reported to developers is not quick</li><li>Each test needs to run in an isolated testing flow, but this is difficult to maintain in manual testing.</li></ol><p><em>Due to these reasons and after some regressed bugs that got released to production, we needed to ensure this never happens again.</em></p><h3><strong><em>Our journey to automated testing</em></strong></h3><blockquote><strong>Listing out the necessities</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*vnBdg4zwPiHv6zsnJAdGmQ.jpeg" /></figure><p>Before starting with the research process we needed to have bare minimum objectives that we are intending to achieve:</p><p><strong>1. Test flows to be written in javascript</strong></p><p><em>A most common question asked by among our team was — “Why do you need test flows in javascript?”</em></p><p>The idea behind this ideology is to improve the capability of front-end developers to support testing and writing test cases. As they can drive testing and keeping that approach in mind ensure that whatever they build, is highly testable.</p><p><strong>2. Scalable and Cross-Platform System</strong></p><p>We wanted this framework to be capable of testing in multiple browsers and as the number of tests increases so should its ability to scale with that.</p><p><strong>3. Minimize feedback loop time between deployment and report of bugs to developers</strong></p><p>We needed this framework to be integrated with the deployment pipeline to run all the tests automatically as soon as a product is being tried in development servers to ensure, a better quality product reaches QA servers.</p><p>This gave us a clear view of how we want our new pipeline to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5FXl6_2wW9hscxItVvCwg.png" /><figcaption>Proposed System</figcaption></figure><p>By the end of this implementation, we have improved our deployment pipeline according to the proposed system:</p><ol><li>A requirement for a new feature arises and developers build it as soon as possible.</li><li>Code is pushed to development server — (It’s tested if no bugs found then deployed to QA servers else developer gets an immediate email with bugs)</li><li>QA validates the report and gives a quick signoff</li><li>Code is ready for production, So it&#39;s first deployed on Pre-Prod Environment(Another rerun of tests) and then deployment to Production.</li></ol><blockquote><strong>Research and Proof Of Concepts</strong></blockquote><p>So the different approaches that we tried out as POC were:</p><p><strong><em>1. Selenium with Java</em><br></strong>This was started by our QA team to try to implement an automated testing mechanism in their local systems</p><p>It was a good approach in terms of customizability and community but had certain issues that lead us to different systems.</p><ol><li>As it was in java, it was difficult for frontend developers who worked in React and javascript.</li><li>Manually needed to handle the problems caused by the Selenium initialization process, it’s waiting and retry mechanisms.</li><li>With being more customizable, it was more complex to implement.</li><li>Building time with maven.</li></ol><p>Still, it could have worked, but we wanted to try different approaches so we tried next with Cypress.</p><p><strong><em>2. Cypress</em></strong></p><p>This was a framework that was built in javascript and natively worked on browsers. It was like a dream come true to prevent any kind of flaky tests.</p><p>This was a lot simpler setup process, with npm, and then writing test cases in mocha architecture.</p><p>So we checked out different best practices to work with this and started building some flows, helper plugins, and base testing code. Which due to its simplicity allowed us to get most of the basic setup and flows being written in a matter of 3 to 4 days. It was looking like a great system for us.</p><p>We built a docker image for it and tried to integrate it with our Jenkins pipeline. This docker image was self-reliant i.e. it included the necessary browsers and tests to run.</p><p>Then we started facing issues that brought us back to “<em>Nothing can be perfect</em>”, i.e. “It was too good to be true”.</p><p>So following were the issues we faced:</p><ol><li><strong>It supported only chrome at the moment </strong>— It was still an acceptable tradeoff for all the internal products that we have as it was a lot more stable testing than selenium.</li><li><strong>Headless browser support only for Electron — </strong>This was a deal-breaker as electron was still with Chromium 73 when chrome was at version 78, Also it&#39;s working with test cases were coming differently than chrome.</li><li><strong>Huge docker image — </strong>Still an acceptable tradeoff</li><li><strong>Tests used to hang when running in docker — </strong>This was a fixable issue, which I will add here for anyone else who got into this problem. <br>This was fixed with following code in plugin.js file (though the exhaustive test was not done to ensure if it fixed the issue completely)</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17f077a3b41063602c8d36e6a2524362/href">https://medium.com/media/17f077a3b41063602c8d36e6a2524362/href</a></iframe><p>5. <strong>Issues with frames — </strong>This was a major blocker as it prevented us to run any payment flows.</p><p>These issues which were mostly acceptable for internal products but not customer-facing products made it an alternative we could think of for our internal products.</p><p><strong><em>3. Nightwatch</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBtVVNSqgmiS0XWGCOrwuw.png" /></figure><p>Again back to selenium, with javascript, we had two choices. Either go with <a href="https://webdriver.io/"><strong><em>Webdriver.io</em></strong></a><strong><em> </em></strong>or <a href="https://nightwatchjs.org/"><strong><em>Nightwatch</em></strong></a><strong><em>.</em></strong></p><p>Both of these frameworks were good, but Nightwatch had managed selenium drivers handling that lead us to try Nightwatch.</p><p>We first tested and ensured this didn’t have the issues we faced with cypress than came up with file structure for the framework.</p><pre>.<br>├── application                # Name of application being tested<br>  ├── commands                 # Command helper for nightwatch<br>  ├── configurations           # Configuration folder<br>    ├── config.js              # Contains some config functions<br>    ├── globals.js             # Nightwatch globals file<br>  ├── dataset                  # Datasets used for test cases<br>  ├── helpers                  # Helper flows from CRM <br>  ├── pages                    # Page Objects for different pages<br>  ├── reports                  # Reports folder<br>  ├── tests                    # Tests folder<br>     ├── desktop               # Desktop tests<br>     ├── mobile                # Mobile tests<br>  ├── nightwatch.json          # Base configuration for nightwatch<br>  ├── nightwatch.local.js      # Local configuration for nightwatch<br>  ├── nightwatch.server.js     # Remote testing configuration<br>  ├── Dockerfile               # Dockerfile for the test suite<br>  ├── package.json             # Dependency list<br>├── Jenkinsfile                 # Jenkins pipeline file<br>└── README.md</pre><p>We wrote a few of our major testing flows, which included similar flow but different test cases for desktop and mobile as our website was adaptive and served content according to the device. And we stuck with it as it solved our objectives. You can read about our adaptive web implementation here:</p><p><a href="https://medium.com/zolo-engineering/adaptive-web-applications-with-react-redux-d3dfcdf2cee8">Adaptive Web Applications with React, Redux</a></p><blockquote><strong>Nightwatch and Zalenium — POC</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*zraCDFlabEjHL1Kviz2VFQ.png" /></figure><p>With Nightwatch, we build some of the base tests flow for mobile and desktop using page objects, and common commands. Had commands for our reusable flows, had a JSON dataset(As this was a POC we just wanted to deep dive with dataset), few utilities with default reporting supported by Nightwatch.</p><p>Now as our POC framework was working fine locally, we needed to integrate this with our CI/CD (Jenkins) with tests running in remote servers.</p><p>To have a remote testing format, we needed to have a grid of browsers running which would be able to run these tests and give us reports on them. To implement this selenium grid was the best option that was available, but to have improved scalability in the selenium grid on our Kubernetes cluster we preferred Zalenium.</p><p>So we set-up zalenium in our Kubernetes cluster, with its docker containers running chrome and firefox.</p><p>With this our automation process POC was looking good, as we created a docker image with our test cases which were integratable in our CI/CD Jenkins pipeline and brought our POC to a success. Our architecture looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qt6p6cE0CXtphuissdtsmg.png" /><figcaption>Testing architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKBDPxc-GRR3Yo6turvZpQ.png" /><figcaption>Deployment flow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOiyOa7VUleLIB7JRXL2Tw.png" /><figcaption>Testing Flow</figcaption></figure><blockquote><strong>POC is fine, what about actual implementation?</strong></blockquote><p>So after POC, we needed to add certain things to our framework for it to be used with production systems:</p><ol><li>Support for different environment testing</li><li>Three browsers testing — Safari, Firefox, and Chrome</li><li>A better reporting for test</li><li>More controlled deployments</li></ol><p><strong>1. Support for different environment testing</strong></p><p>We added configurable environments to our service. This would enable testing our product running in different environments without changing any code.</p><p><strong>2. Three browsers testing — Safari, Firefox, and Chrome</strong></p><p>With Safari into the picture, a lot of issues needed to be handled as it has certain different requirements regarding how it acts and works.</p><p>Also with respect to Zalenium docker images that we were using, we needed to decide if we were going to add MAC OS physical machines to the grid or use cloud testing tools like lambdatest or browserstack, so based on our requirements we decided to connect lambdatest with our zalenium hub. As it had native integrations this process was simple, but what was going to be a problem was how the safari browser is different in functionality than the rest of the browsers.</p><p>So these were the main issues we faced with Safari browser:</p><ol><li>In Safari 13 performing click via selenium-driver was messed up, due to which any selenium click commands didn’t work on Safari</li><li>Safari had issues with how it worked with frames</li><li>Safari didn’t have configurations to be run in a mobile environment as with chrome and firefox.</li></ol><p>So for these, we wrote customClick commands, used appium for mobile testing and made changes to our framework so that tests can remain the same for all the browsers.</p><p><strong>3. A better reporting for test</strong></p><p>This was an important aspect, as the reports generated by Nightwatch by default were not that good. As we were using allure reports initially, we decided to create an npm package that could be used as a reporter with Nightwatch. It can be found at the following URL:</p><p><a href="https://www.npmjs.com/package/nightwatch-allure">nightwatch-allure</a></p><p>This allowed us to get the reports in a structure where we will be able to see which browser was used for which test, what was its functioning in each step. If it had an error and screenshot was taken for it, then embedding that in the report.</p><p>Still, there are certain features that remain to be added to this package including browser console logs, custom tagging of tests, etc.</p><p><strong>4. More controlled deployments</strong></p><p>This required changes in our Jenkins pipeline to have a stage of testing that validates for any failed test cases, lighthouse score reductions and only if all’s well, then do the deployment.</p><p>This also included emailing the testing reports with Jenkins&#39;s link to the concerned teams.</p><p>This article didn’t include much of the actual implementation steps to deploy zalenium or code of how to use Nightwatch. For that, I will be writing another article with a complete walkthrough on all the steps that need to be done to complete this setup. I will update it here on completion. Thanks and keep testing :)</p><p><em>PS:</em> <em>If you are into Automation and find terms like Infrastructure Automation, CI/CD exciting as much as we do, then drop us a line at </em><a href="/service/mailto:join-tech@zolostays.com"><em>join-tech@zolostays.com</em></a><em>. We would love to take you out for a Coffee ☕ to discuss the possibility of you working with us.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a7009e85e1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zolo-engineering/our-journey-to-automated-front-end-testing-2a7009e85e1b">Setting up Automation Testing at Zolostays</a> was originally published in <a href="https://medium.com/zolo-engineering">Zolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Prometheus-operator helm chart with AWS EKS(Part-2): Monitoring of external services]]></title>
            <link>https://medium.com/zolo-engineering/configuring-prometheus-operator-helm-chart-with-aws-eks-part-2-monitoring-of-external-services-342e352d85f0?source=rss----2c3ca3d17328---4</link>
            <guid isPermaLink="false">https://medium.com/p/342e352d85f0</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Vishesh Kumar Singh]]></dc:creator>
            <pubDate>Tue, 31 Mar 2020 06:08:02 GMT</pubDate>
            <atom:updated>2020-03-31T06:08:01.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*E2L4kLZEWDNlkrnrp5hmZQ.jpeg" /></figure><p>This is the second article in the series about configuring prometheus-operator helm chart with AWS EKS. If you have not read the first article yet, I suggest you give that a read before you continue.</p><p><a href="https://medium.com/zolo-engineering/configuring-prometheus-operator-helm-chart-with-aws-eks-c12fac3b671a">Configuring prometheus-operator helm chart with AWS EKS</a></p><p>In this, we will look at how to add an external service to the Prometheus targets list and monitor them. We will be covering the following concepts:</p><ul><li>Basic prometheus-operator architecture</li><li>Role of servicemonitor</li><li>How prometheus-operator uses node-exporter to fetch the metrics by default</li><li>Working examples by monitoring <strong>Elasticsearch </strong>and adding <strong>Grafana Dashboard</strong> for visualizing</li><li>Monitoring different database services like<strong> MySQL</strong>, <strong>MongoDB,</strong> and <strong>Redis</strong> in k8s cluster</li></ul><p>The prometheus-operator is simple to install with a single command and enables users to configure and manage instances of Prometheus using the simple declarative configuration that will, in response, create, configure, and manage Prometheus monitoring instances. It does not support <strong>annotation-based discovery</strong> of services as <strong>Prometheus</strong> does(<a href="https://github.com/helm/charts/tree/master/stable/prometheus">https://github.com/helm/charts/tree/master/stable/prometheus</a>), using the serviceMonitor CRD is its place as it provides far more configuration options.</p><p><strong>What do we mean by annotation-based discovery?</strong></p><p>It is the default configuration that causes <strong>Prometheus</strong> to scrape a variety of Kubernetes resource types, provided they have the correct annotations as mentioned below.</p><p>In order to get Prometheus to scrape pods, you must add annotations to the pods as below:</p><pre>metadata:<br> annotations:<br>  prometheus.io/scrape: &quot;true&quot;<br>  prometheus.io/path: /metrics #based on the URL serves metrics from<br>  prometheus.io/port: &quot;8080&quot; <br>spec:<br>...</pre><p>Instead of this, prometheus-operator uses servicemonitor to monitor the same.</p><p>Once installed the prometheus-operator provides the following features:</p><ul><li>Create/Destroy: Easily launch a Prometheus instance for your Kubernetes namespace, a specific application or team easily using the Operator.</li><li>Simple Configuration: Configure the fundamentals of Prometheus like versions, persistence, retention policies, and replicas from a native Kubernetes resource.</li><li>Target Services via Labels: Automatically generate monitoring target configurations based on familiar Kubernetes label queries; no need to learn a Prometheus specific configuration language.</li></ul><p>Till now, our configuration look likes:</p><ul><li>Installed prometheus-operator helm chart in our cluster with namespace <strong>monitoring</strong> and includes Prometheus, Alertmanager and Grafana with default specifications.</li></ul><h4>How does it work?</h4><p>The Basic Operator Architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*qh7st4vsESDkvPzW-SBDig.png" /></figure><p>After we successfully deployed prometheus-operator we should see a new CRDS(Custom Resource Definition)</p><blockquote>kubectl get crds -n monitoring</blockquote><ul><li>alertmanagers — defines installation for Alertmanager</li><li>podmonitors — determines which pods should be monitored</li><li>prometheuses — defines installation for Prometheus</li><li>prometheusrules — defines rules for alert manager</li><li>servicemonitors — determines which services should be monitored. The operator automatically generates Prometheus scrape configuration based on the definition.</li></ul><p><strong>ServiceMonitor</strong></p><blockquote>kubectl get servicemonitors -n monitoring</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*Wv4YMuyftZYTFSqORfcDeQ.png" /></figure><p>This displays, the list of all service monitors, which is set up by default by the operator, which Prometheus shows in the target.</p><p>Let&#39;s take an example, for how Prometheus gets to know about <strong>node-exporters </strong>and how it uses its service monitor to identify its target and then we will make our own service monitor fetch the ElasticSearch metrics, which behaves as our external service to monitor.</p><p>Scraping an exporter or separate metrics port requires a service that targets the Pod(s) of the exporter or application.</p><blockquote><em>kubectl get svc prometheus-operator-prometheus-node-exporter -n monitoring -o yaml</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/469bca5a622a6a3f28fd5a42cd35e5b2/href">https://medium.com/media/469bca5a622a6a3f28fd5a42cd35e5b2/href</a></iframe><blockquote><em>kubectl get servicemonitors prometheus-operator-node-exporter -n monitoring -o yaml</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb12b7698f45b56068172427258fe7e7/href">https://medium.com/media/cb12b7698f45b56068172427258fe7e7/href</a></iframe><p>So, the important part here is the labels:</p><ul><li><strong>app: prometheus-node-exporter</strong> (comes from the service, which Prometheus will monitor)</li><li><strong>release: prometheus-operator</strong> (this name comes from the name of helm chart)</li></ul><p>Also, we need to specify the <strong>endpoint</strong>, where to get metrics from in the service monitor, taking the name of the port from the service file.</p><ul><li><strong>port: metrics</strong>(defined in service, the port where metrics are exposed to)</li></ul><p>So, now we have seen how Prometheus-operator monitors its services, we are good to go for making our own service monitor keep check for our external services which we are deploying in our k8s cluster such as databases, queue service, log services, etc.</p><h4><strong>Example1: </strong>Monitoring ElasticSearch Cluster via ElasticSearch Exporter Helm Chart</h4><p><strong>Exporter Helm Chart: </strong><a href="https://github.com/helm/charts/tree/master/stable/elasticsearch-exporter">https://github.com/helm/charts/tree/master/stable/elasticsearch-exporter</a></p><pre>helm install --name es-exporter -f values.yml stable/elasticsearch-exporter --namespace kube-logging</pre><p>This lets us install an elastic search exporter in Kube-logging namespace, where our ES clusters reside(we need to add Address(host and port) of the Elasticsearch node we should connect to in our <strong>values</strong> file)</p><pre>kubectl get svc es-exporter-elasticsearch-exporter -n kube-logging -o yaml</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c78acfcaefef109718ae9f44a80d087/href">https://medium.com/media/6c78acfcaefef109718ae9f44a80d087/href</a></iframe><p>This is the ES exporter service file, which gets created by deploying the ES exporter helm chart, as mentioned earlier.</p><p>Now, we will make a service monitor<strong> </strong>for this ES service, so that our Prometheus gets to know about our ES cluster and scrape the metrics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03a01f72029721da36aace1ad9fdc1c9/href">https://medium.com/media/03a01f72029721da36aace1ad9fdc1c9/href</a></iframe><p><strong>How the service monitor discovers?</strong></p><ul><li>labels</li><li>namespaceSelector</li></ul><p>So, after creating our service monitor, we will be able to get our metrics on Prometheus and monitor our ES cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BgovPSXbxhy47S05bXoixA.png" /></figure><p>While ServiceMonitors must live in the same namespace as the Prometheus resource, discovered targets may come from any namespace(here Kube-logging). This allows for cross-namespace monitoring use cases. Use the namespaceSelector of the ServiceMonitorSpec to restrict the namespaces from which Endpoints objects may be discovered.</p><p>Now, we are able to get metrics in Prometheus as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*KbSPZiXDTgVfGKDYPtmaCw.png" /></figure><p>We can add the <strong>Grafana</strong> dashboard for the same for visualization.</p><p>Steps to follow:</p><ul><li>Go on to the grafana dashboard set-up by prometheus-operator with the credentials given in YAML file</li><li>Select import dashboard from the sidebar options</li><li>There are dashboards which are made, we only need to import the dashboards and edit it, if changes are required(<a href="https://grafana.com/grafana/dashboards/6483">https://grafana.com/grafana/dashboards/6483</a>)</li><li>Copy the code ID given(6483, in this case)</li><li>Paste on your Grafana dashboard, and select Prometheus as Datasource</li><li>Our Elasticsearch dashboard is ready</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfTVR2PvppF2SoBXg2GQ-A.png" /></figure><h4>Example2: Monitoring MySQL Cluster</h4><p><strong>MySQL Helm Chart: </strong><a href="https://github.com/helm/charts/tree/master/stable/mysql">https://github.com/helm/charts/tree/master/stable/mysql</a></p><pre>helm install --name mysql-8-0-19 stable/mysql --values values.yaml --namespace mysql</pre><p>This will let you have MySQL ready in our k8s cluster. Ensure to make these changes and keep this highlighted as this will give the pathway to monitor your MySQL cluster</p><pre>metrics:<br>enabled: true<br>image: prom/mysqld-exporter<br>imageTag: v0.10.0<br>imagePullPolicy: IfNotPresent<br>resources: {}<br>annotations:<br>prometheus.io/scrape: &quot;true&quot;<br>prometheus.io/port: &quot;9104&quot;<br>livenessProbe:<br>initialDelaySeconds: 15<br>timeoutSeconds: 5<br>readinessProbe:<br>initialDelaySeconds: 5<br>timeoutSeconds: 1</pre><p>From the above section, we get to know that we are enabling metrics options(Start a side-car Prometheus exporter) and our metrics are exposed on port <strong>9104</strong>, and after deploying in the cluster we can get more information by its service.</p><pre>kubectl get svc mysql-8-0-19 -n mysql -o yaml</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1364f1b9dd9881a09d13ec747bb5d14a/href">https://medium.com/media/1364f1b9dd9881a09d13ec747bb5d14a/href</a></iframe><p>From the above file, we can check that the port name is <strong>metrics</strong> by default and labels from the same and then add them in our service monitor so that Prometheus can discover our targets.</p><pre>vim service_monitor_mysql.yaml</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1fbe53ca78eb5d5c1e676e2c98f369d/href">https://medium.com/media/c1fbe53ca78eb5d5c1e676e2c98f369d/href</a></iframe><pre>kubectl create -f service_monitor_mysql.yml -n monitoring</pre><p>Deploying this to our cluster, will let Prometheus discover MySQL and monitor it, which can be seen under the targets section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*DMoFy41vfbc_QlIP" /></figure><h4><strong>Example3: Monitoring MongoDB Cluster</strong></h4><p><strong>MongoDB Helm Chart: </strong><a href="https://github.com/helm/charts/tree/master/stable/mongodb-replicaset">https://github.com/helm/charts/tree/master/stable/mongodb-replicaset</a></p><pre>helm install — name mongodb-replicaset -f values.yaml stable/mongodb-replicaset — namespace mongodb-replica</pre><p>This will let you have MongoDB ready in our k8s cluster.</p><p>So, the same configuration can be seen for MongoDB also, the port name declared is <strong>metrics</strong> and it exposes metrics on port <strong>9216</strong>.</p><pre>vim service_monitor_mongodb.yaml</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4102b62073b5695d40297420b8cf0b9/href">https://medium.com/media/d4102b62073b5695d40297420b8cf0b9/href</a></iframe><pre>kubectl create -f service_monitor_mongo.yml -n monitoring</pre><p>So, after creating the service monitor for the same, it will let Prometheus discover MongoDB and monitor it, which can be seen under the targets section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ls-raPWj84wJ0wXW" /></figure><h4><strong>Example4: Monitoring Redis Cluster</strong></h4><p><strong>Redis Helm Chart:</strong><a href="https://github.com/helm/charts/tree/master/stable/redis">https://github.com/helm/charts/tree/master/stable/redis</a></p><pre>helm install stable/redis --values values.yaml --namespace redis --name redis-cluster</pre><p>This will let you have Redis ready in our k8s cluster. After deploying it successfully, you will get the metrics at port 9121. This can be verified by using the <strong>kubectl port-forward</strong> and can be checked on your localhost. Now, since metrics are exposed by making a service monitor, Prometheus will discover the target and we will able to get all Redis metrics in Prometheus.</p><pre>vim service_monitor_redis.yaml</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e43d14c466eec9419188a59279e57d24/href">https://medium.com/media/e43d14c466eec9419188a59279e57d24/href</a></iframe><pre>kubectl create -f service_monitor_redis.yml -n monitoring</pre><p>Deploying this to our cluster in monitoring namespace, will let Prometheus discover Redis and monitor it, which can be seen under the targets section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ivje8h1sgjPaP05ILalYQ.png" /></figure><h4>Cleaning Up:</h4><p>Say you made a mistake and want to purge the whole deployment and restart for any cluster say Redis, you would have to run the following command,</p><pre><strong>#!/usr/bin/env bash<br></strong><em>helm </em>delete --purge redis-cluster<br>kubectl delete -f service_monitor_redis.yaml<br><em>kubectl </em>delete namespace redis #if something goes wrong with cluster<br></pre><p><em>If you are into DevOps or Fullstack and find terms like ServiceMesh, Infrastructure Automation, Event Loop and Micro-Frontends exciting as much as we do, then drop us a line at </em><a href="/service/mailto:join-tech@zolostays.com"><em>join-tech@zolostays.com</em></a><em>. We would love to take you out for a Coffee ☕ to discuss the possibility of you working with us.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342e352d85f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zolo-engineering/configuring-prometheus-operator-helm-chart-with-aws-eks-part-2-monitoring-of-external-services-342e352d85f0">Configuring Prometheus-operator helm chart with AWS EKS(Part-2): Monitoring of external services</a> was originally published in <a href="https://medium.com/zolo-engineering">Zolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring prometheus-operator helm chart with AWS EKS]]></title>
            <link>https://medium.com/zolo-engineering/configuring-prometheus-operator-helm-chart-with-aws-eks-c12fac3b671a?source=rss----2c3ca3d17328---4</link>
            <guid isPermaLink="false">https://medium.com/p/c12fac3b671a</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ek]]></category>
            <dc:creator><![CDATA[Abhay Kumar]]></dc:creator>
            <pubDate>Thu, 30 Jan 2020 03:35:10 GMT</pubDate>
            <atom:updated>2020-03-31T06:26:55.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Prometheus is a popular open-source monitoring and alerting tool, especially used in the Kubernetes environment. There are a lot of articles out there that explain the amazing features of Prometheus so the objective of this article would be to help everyone figure out how to configure the prometheus-operator helm chart which seems to have rather complex documentation for beginners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*oNBsE9SM_4aV3FTx.jpg" /></figure><p>First of all, you can find the prometheus-operator helm chart here.,<br><a href="https://github.com/helm/charts/tree/master/stable/prometheus-operator">https://github.com/helm/charts/tree/master/stable/prometheus-operator</a></p><p>For the past few weeks, the maintainers of the Github repo kept improving the documentation. These improvements include some of the hard-learned ways of configuring the helm chart as well as few more tricks which we had to work very hard to figure out. Even after you figure out a way to configure it, EKS has weird issues with this specific helm chart which requires an additional custom configuration.</p><p>In order to install the helm chart to your cluster,</p><pre><em>helm </em>install stable/prometheus-operator --name prometheus-operator --namespace monitoring</pre><p>This will create a namespace monitoring in your cluster and install the following.,</p><ol><li>Prometheus</li><li>Grafana</li><li>Alertmanager</li></ol><p>This also adds node exporters that track data from your worker nodes and send them to Prometheus.</p><p>However, the story doesn’t end here. The config provided by default would be very basic. For example, the data stored in Prometheus is not persistent and ingress is not defined, to begin with. You would have to proxy the dashboards to access them.</p><p>When you search on the internet for how to configure the helm chart, you will find out that <strong>values.yaml</strong> file needs to be edited with the desired configuration.</p><p>The file can be found here.,<br><a href="https://github.com/helm/charts/blob/master/stable/prometheus-operator/values.yaml">https://github.com/helm/charts/blob/master/stable/prometheus-operator/values.yaml</a></p><p>Here are some of the things we configured which you might find useful.,</p><h3>Alertmanager Config:</h3><p>Alertmanager is used to forward the alerts triggered by Prometheus to alerting tools like Pagerduty. We at Zolo use Zenduty. If you don’t want to associate with any paid rules, you can always integrate with Slack. Find the Alertmanager configuration directives block in the values.yaml file and update it in the following fashion.</p><pre><em>## Alertmanager configuration directives<br>## ref: </em><a href="https://prometheus.io/docs/alerting/configuration/#configuration-file"><em>https://prometheus.io/docs/alerting/configuration/#configuration-file</em></a><em><br>##      </em><a href="https://prometheus.io/webtools/alerting/routing-tree-editor/"><em>https://prometheus.io/webtools/alerting/routing-tree-editor/</em></a><em><br>##<br></em>config:<br>  global:<br>    resolve_timeout: 5m<br>  route:<br>    group_by: [&#39;alertname&#39;]<br>    group_wait: 10s<br>    group_interval: 10s<br>    repeat_interval: 1h<br>    receiver: &#39;devops&#39;<br>    routes:<br>    <em># suppress<br>    </em>- match:<br>        alertname: Watchdog<br>      receiver: &#39;null&#39;<em><br>    </em>- match:<br>        deployment: &#39;backend&#39;<br>      receiver: &#39;backend&#39;<br>    - match_re:<br>        pod: &#39;(backend.*)&#39;<br>      receiver: &#39;backend&#39;<br>    - match:<br>        deployment: &#39;frontend&#39;<br>      receiver: &#39;frontend&#39;<br>    - match_re:<br>        pod: &#39;(frontend.*)&#39;<br>      receiver: &#39;frontend&#39;<br>  receivers:<br>    <em># suppress<br>    </em>- name: &#39;null&#39;<br>    <em># devops<br>    </em>- name: &#39;devops&#39;<br>      webhook_configs:<br>        - url: &#39;https://www.zenduty.com/api/integration/prometheus/&lt;key&gt;/&#39;<br>    <em># backend<br>    </em>- name: &#39;backend&#39;<br>      webhook_configs:<br>        - url: &#39;https://www.zenduty.com/api/integration/prometheus/&lt;key&gt;/&#39;<br>    <em># frontend<br>    </em>- name: &#39;frontend&#39;<br>      webhook_configs:<br>        - url: &#39;https://www.zenduty.com/api/integration/prometheus/&lt;key&gt;/&#39;<br>  inhibit_rules:<br>    - source_match:<br>        severity: &#39;critical&#39;<br>      target_match:<br>        severity: &#39;warning&#39;<br>      equal: [&#39;alertname&#39;, &#39;dev&#39;, &#39;instance&#39;]</pre><p>All alerts by default go to DevOps receiver. Only frontend pod alerts go to frontend receiver, just like backend pod alerts go to backend receiver. Each receiver is configured with a unique webhook. These webhooks trigger SMS and a phone call to the concerned on-call developer based on the configuration provided. These alerting tools are pretty intuitive with great support and configuring them with escalation policies is a piece of cake.</p><h3>Alertmanager Ingress:</h3><p>If you don’t want to proxy the Alertmanager dashboard over localhost every time, you can configure ingress like below.,</p><pre>ingress:<br>  enabled: true</pre><pre>  annotations: {<br>    kubernetes.io/ingress.class: &quot;nginx&quot;,<br>    nginx.ingress.kubernetes.io/whitelist-source-range: &quot;<em>172.16.254.1</em>&quot;<br>  }</pre><pre>  labels: {}</pre><pre>  <em>## Hosts must be provided if Ingress is enabled.<br>  ##<br>  </em>hosts:<br>   - alertmanager.example.com</pre><pre>  <em>## Paths to use for ingress rules - one path should match the alertmanagerSpec.routePrefix<br>  ##<br>  </em>paths:<br>   - /</pre><p>This ensures the domain alertmanager.example.com is only available at the given IP addresses. This is necessary as there is no inherent authentication mechanism in place. The ingress for this follows standard Nginx based Kubernetes Ingress.</p><h3>Additional Prometheus Rules:</h3><p>Prometheus by default comes with a lot of useful rules which basically trigger alerts when those rules are breached. But these are a bare minimum. After researching a few SRE articles on the web, I found the following links extremely useful.,</p><ul><li><a href="https://awesome-prometheus-alerts.grep.to/rules.html">Awesome Prometheus alerts</a></li><li><a href="https://landing.google.com/sre/sre-book/chapters/monitoring-distributed-systems/">Google - Site Reliability Engineering</a></li><li><a href="https://sysdig.com/blog/golden-signals-kubernetes/">How to monitor Golden signals in Kubernetes. | Sysdig</a></li></ul><p>In order to add the custom rules to the existing Prometheus configuration, make the changes in the <strong>additionalPrometheusRules</strong> block.</p><pre><em>## Provide custom recording or alerting rules to be deployed into the cluster.<br>##<br></em>additionalPrometheusRules:<br>  - name: custom-rules-file<br>    groups:<br>      - name: custom-node-exporter-rules<br>        rules:<br>          - alert: PhysicalComponentTooHot<br>            expr: node_hwmon_temp_celsius &gt; 75<br>            for: 5m<br>            labels:<br>              severity: warning<br>            annotations:<br>              summary: &quot;Physical component too hot (instance {{ $labels.instance }})&quot;<br>              description: &quot;Physical hardware component too hot\n  VALUE = {{ $value }}\n  LABELS: {{ $labels }}&quot;<br>          - alert: NodeOvertemperatureAlarm<br>            expr: node_hwmon_temp_alarm == 1<br>            for: 5m<br>            labels:<br>              severity: critical<br>            annotations:<br>              summary: &quot;Node overtemperature alarm (instance {{ $labels.instance }})&quot;<br>              description: &quot;Physical node temperature alarm triggered\n  VALUE = {{ $value }}\n  LABELS: {{ $labels }}&quot;</pre><p>For example, the above block fires the alerts when physical components get too hot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxxovXMpsmEjHVHTWahi8A.png" /><figcaption>Alerts configured above as displayed in Prometheus dashboard</figcaption></figure><h3>Grafana Ingress:</h3><p>Grafana is an open-source monitoring and analytics solution. This has deep integration with Prometheus and provides predefined dashboards which are really helpful.</p><p>To access Grafana over custom domain update the ingress config.,</p><pre>ingress:<br>  <em>## If true, Grafana Ingress will be created<br>  ##<br>  </em>enabled: true</pre><pre>  <em>## Annotations for Grafana Ingress<br>  ##<br>  </em>annotations: {<br>    kubernetes.io/ingress.class: &quot;nginx&quot;,<br>    nginx.ingress.kubernetes.io/whitelist-source-range: &quot;<em>172.16.254.1</em>&quot;<br>  }<br>    <em># kubernetes.io/ingress.class: nginx<br>  # kubernetes.io/tls-acme: &quot;true&quot;</em></pre><pre><em>  ## Labels to be added to the Ingress<br>  ##<br>  </em>labels: {}</pre><pre>  <em>## Hostnames.<br>  ## Must be provided if Ingress is enable.<br>  ##<br>  # hosts:<br>  #   - grafana.domain.com<br>  </em>hosts:<br>    - grafana.example.com</pre><pre>  <em>## Path for grafana ingress<br>  </em>path: /</pre><p>According to the above config, the Grafana dashboard will be accessible through grafana.example.com through the mentioned IP addresses. Grafana has an authentication system, so you can choose to make it public.</p><h3>Prometheus Ingress:</h3><p>Just like Alertmanager and Grafana, the Prometheus dashboard can also be accessed through a custom domain.,</p><pre>ingress:<br>  enabled: true<br>  annotations: {<br>    kubernetes.io/ingress.class: &quot;nginx&quot;,<br>    nginx.ingress.kubernetes.io/whitelist-source-range: &quot;<em>172.16.254.1</em>&quot;<br>  }<br>  labels: {}</pre><pre>  <em>## Hostnames.<br>  ## Must be provided if Ingress is enabled.<br>  ##<br>  # hosts:<br>  #   - prometheus.domain.com<br>  </em>hosts:<br>    - prometheus.example.com</pre><pre>  <em>## Paths to use for ingress rules - one path should match the prometheusSpec.routePr<br>  ##<br>  </em>paths:<br>    - /</pre><h3>Scrape &amp; Evaluation Interval:</h3><p>You can update the scrape and evaluation interval by updating the <strong>prometheusSpec</strong> block.,</p><pre><em>## Settings affecting prometheusSpec<br>## ref: </em><a href="https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#prometheusspec"><em>https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#prometheusspec</em></a><em><br>##<br></em>prometheusSpec:</pre><pre>  <em>## Interval between consecutive scrapes.<br>  ##<br>  </em>scrapeInterval: 15s</pre><pre>  <em>## Interval between consecutive evaluations.<br>  ##<br>  </em>evaluationInterval: 15s</pre><h3>Persistent Volume for Prometheus:</h3><p>By default, Prometheus uses the volume provided by the worker nodes to store the data. But we can configure it to use persistent volume to ensure data is not lost even when Prometheus goes down or restarts.,</p><pre><em>## Prometheus StorageSpec for persistent data<br>## ref: </em><a href="https://github.com/coreos/prometheus-operator/blob/master/Documentation/user-guides/storage.md"><em>https://github.com/coreos/prometheus-operator/blob/master/Documentation/user-guides/storage.md</em></a><em><br>##<br></em>storageSpec:<br>  volumeClaimTemplate:<br>    spec:<br>      storageClassName: gp2<br>      accessModes: [&quot;ReadWriteOnce&quot;]<br>      resources:<br>        requests:<br>          storage: 50Gi</pre><p>Since we are using AWS, gp2 would be the storageClassName. Request the storage size as per your need.</p><h3>EKS Specific Changes:</h3><p>When you set up Prometheus using the default config, you will see a lot of alerts firing unnecessarily. For example, KubeScheduler is not down, KubeController is not responding, etc., This happens because the Prometheus Node Exporters are unable to get metrics from the services which are running on the control plane.</p><p>Here are the few alerts which we can disable in the <strong>values.yaml</strong> file.,</p><pre><em>## Component scraping the kube controller manager<br>##<br></em>kubeControllerManager:<br>  enabled: false</pre><pre><em>## Component scraping kube scheduler<br>##<br></em>kubeScheduler:<br>  enabled: false</pre><pre><em>## Component scraping kube proxy<br>##<br></em>kubeProxy:<br>  enabled: false</pre><p>Finally, in order to update the helm deployment, we run the following command.,</p><pre><em>helm </em>upgrade -f values.yaml prometheus-operator stable/prometheus-operator</pre><p>If you are running the helm chart for the first time, you can also run the following command.,</p><pre>helm install stable/prometheus-operator \<br> — name prometheus-operator \<br> — namespace monitoring -f values.yaml</pre><p>These commands ensure the helm chart is configured with the custom changes added in the <strong>values.yaml</strong> file.</p><h3>Cleaning Up:</h3><p>Say you made a mistake and want to purge the whole deployment and restart, you would have to run the following command.,</p><pre><strong>#!/usr/bin/env bash<br></strong><em>helm </em>delete --purge prometheus-operator<br><em>kubectl </em>delete namespace monitoring<br><em>kubectl </em>delete crd alertmanagers.monitoring.coreos.com<br><em>kubectl </em>delete crd podmonitors.monitoring.coreos.com<br><em>kubectl </em>delete crd prometheuses.monitoring.coreos.com<br><em>kubectl </em>delete crd prometheusrules.monitoring.coreos.com<br><em>kubectl </em>delete crd servicemonitors.monitoring.coreos.com</pre><p>As you can see, we are deleting a lot of CustomResourceDefinations. These should be deleted separately though they are created during the deployment of the helm chart.</p><p>We have published part 2 for this article on how to capture custom metrics and visualize them using the prometheus-operator helm chart.<br><a href="https://medium.com/zolo-engineering/configuring-prometheus-operator-helm-chart-with-aws-eks-part-2-monitoring-of-external-services-342e352d85f0">https://medium.com/zolo-engineering/configuring-prometheus-operator-helm-chart-with-aws-eks-part-2-monitoring-of-external-services-342e352d85f0</a></p><p><em>If you are into DevOps or Fullstack and find terms like ServiceMesh, Infrastructure Automation, Event Loop and Micro-Frontends exciting as much as we do, then drop us a line at </em><a href="/service/mailto:join-tech@zolostays.com"><em>join-tech@zolostays.com</em></a><em>. We would love to take you out for a Coffee ☕ to discuss the possibility of you working with us.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12fac3b671a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zolo-engineering/configuring-prometheus-operator-helm-chart-with-aws-eks-c12fac3b671a">Configuring prometheus-operator helm chart with AWS EKS</a> was originally published in <a href="https://medium.com/zolo-engineering">Zolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Take control of your APIs by implementing API Governance — Using RAML & Node.js]]></title>
            <link>https://medium.com/zolo-engineering/take-control-of-your-apis-by-implementing-api-governance-using-raml-node-js-47b99a04d483?source=rss----2c3ca3d17328---4</link>
            <guid isPermaLink="false">https://medium.com/p/47b99a04d483</guid>
            <category><![CDATA[raml]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[api-governance]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Abhay Kumar]]></dc:creator>
            <pubDate>Fri, 06 Dec 2019 05:55:31 GMT</pubDate>
            <atom:updated>2019-12-06T07:40:05.803Z</atom:updated>
            <content:encoded><![CDATA[<h3>Take control of your APIs by implementing API Governance — Using RAML &amp; Node.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OrbBPBHALTOKmurK.jpeg" /></figure><p>tl;dr: We have close to 50 developers working on 20+ microservices. Most of the APIs developed were inconsistent, lacked REST conventions and sometimes had security vulnerabilities. The API review process was manual and time taking. Therefore our Frontend developers had to wait until the backend code get’s deployed to start the development process. To solve this, we implemented API Governance. We automated the whole process to ensure review and validation are done in realtime.</p><blockquote>API governance helps save time and money because it enables consistency across APIs, allows components to be reused, and ensures that APIs are built proactively to achieve specific goals and bring value to the business.</blockquote><h3>What should API Governance include?</h3><ol><li><strong>Centralization</strong>: A central point where policies are created and enforced.</li><li><strong>Reusability</strong>: Standardizing API design not only ensures that APIs are consistent across an organization but also contains reusable components.</li><li><strong>Automation</strong>: API contracts, documentation, and tracking are processes that can be automated and should be part of overall API governance</li><li><strong>Versioning</strong>: Helps developers keep track of and maintain different versions of APIs.</li><li><strong>Deprecation Policy</strong>: Versioning effectively helps make deprecating APIs much easier.</li><li><strong>Tracking</strong>: Track where APIs are deployed, who are using the APIs, how the APIs are being used, routing information, and other elements of the API lifecycle.</li><li><strong>API Discovery</strong>: As the number of APIs and governance tooling grows, it is necessary to provide a means to easily search for and discover deployed APIs and the tooling currently in use.</li></ol><p>There are lots of tools out there that help you achieve this. <a href="https://swagger.io/tools/swaggerhub/">Swagger Hub</a> being popular than others. Swagger Hub supports OpenAPI specification (formerly knows as Swagger) as well as older swagger versions. We at Zolostays Engineering Team chose to go ahead with RAML instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*Fv_gPFWNxD1NqoBW" /></figure><blockquote>RESTful API Modeling Language (RAML) makes it easy to manage the whole API lifecycle from design to sharing. It’s concise — you only write what you need to define — and reusable. It is machine readable API design that is actually human friendly.</blockquote><p>The whole idea of API Governance is to achieve better design and reusability. RAML supports reusable design patterns. It’s a bit difficult to learn but once you get the hang of things, writing API Specs feel natural. Unlike Swagger, you just need to maintain a single specification. One single raml file for your entire service.</p><p>A sample RAML file looks like this.,</p><pre>#%RAML 1.0<br>title: Demo API<br>baseUri: <a href="http://localhost:5000/api/%7Bversion">http://localhost:3000/api/{version</a>}<br>version: v1<br>protocols: [HTTP]<br>types:<br>  Message:<br>    type: string<br>    description: Success / Error message to be shown to users<br>/:<br>  get:<br>    description: Root of the API<br>    responses:<br>      200:<br>        description: API is working fine<br>        body:<br>          application/json:<br>            example: {<br>              message: &#39;API is working fine&#39;<br>            }<br>            properties:<br>              message: Message</pre><p>Being the new kid on the block, there are few disadvantages with RAML. It lacks strong documentation, limited tooling, and a very small community. Postman doesn’t even support RAML 1.0 yet and it’s not even in their roadmap.</p><p>In a nutshell, we needed the following solutions.,</p><ol><li>A way to let team managers and leads to review and approve the API Specs written by developers.</li><li>A way for our backend developers to document the APIs.</li><li>A way for our frontend developers to mock the API contracts.</li><li>An API validation layer for our APIs.</li></ol><p><a href="https://www.mulesoft.com/platform/api/manager">Mulesoft’s Anypoint API Manager</a> satisfies most of the requirements of API Governance. This product is similar to SwaggerHub and just like SwaggerHub, it’s a paid solution. We were looking for Open source alternatives. We had to come up with our own in-house solutions.</p><p>We developed a product called zDock ( short for Zolo API Documentation and Mocking Solution). The context diagram for the product goes something like this.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93KRJNlrWVPlionfZieS6w.png" /><figcaption>zDock Context Diagram</figcaption></figure><p>I will try to explain the diagram with respect to the requirements we had.,</p><h3>(1/4) A way to let team managers and leads to review and approve the API Specs written by developers.</h3><p>Instead of writing APIs directly, our developers first write RAML files and push it to Gitlab (our VCS) where we placed event triggers that get fired every time code get’s committed. These triggers call the API endpoint of zDock and zDock analyzes the commit and identifies the RAML files among the committed files and posts them to Confluence. An email is sent to the managers and the leads with the Confluence page link. We chose confluence because we were already using it for our Wiki and it has good features like highlighting and commenting on the code which made the review process seamless.</p><p>I might have actually oversimplified the whole review process because there are a ton of hurdles to cross. Primarily to post an API Spec as a Confluence page requires converting RAML to HTML. There are converters out there but Confluence is very stringent when it comes to taking HTML and only supports basic HTML tags. So we had to convert RAML to Markdown and then convert Markdown to HTML before sending it to Confluence for review.</p><p>The below code converts RAML to Markdown.,</p><pre>const raml2html = <strong><em>require</em></strong>(&#39;raml2html&#39;);</pre><pre>// convert RAML to markdown<br>const convertRAMLtoMarkdown = async (ramlFilePath, templatePath) =&gt; {<br>  try {<br>    const configWithCustomTemplate = raml2html.getConfigForTemplate(templatePath);<br>    return await raml2html.render(ramlFilePath, configWithCustomTemplate, {<br>      pretty: true<br>    });<br>  } catch (e) {<br>    throw e;<br>  }<br>};</pre><p>The function <em>convertRAMLtoMarkdown</em> takes two parameters. First is the RAML file path and the second is the template path. We used <em>nunjucks</em> for templating. The custom templates used for zDock are.,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9318cad82971dd2bf967220012cf9add/href">https://medium.com/media/9318cad82971dd2bf967220012cf9add/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91bde663bb0dfff6d1eb0ce12a632df5/href">https://medium.com/media/91bde663bb0dfff6d1eb0ce12a632df5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad04647087c78c9b3daccf2be2b3a394/href">https://medium.com/media/ad04647087c78c9b3daccf2be2b3a394/href</a></iframe><p>You can know more about nunjucks <a href="https://mozilla.github.io/nunjucks/">here</a>.</p><p>Once we had the Markdown, we had to convert it to HTML. We used <a href="https://github.com/showdownjs/showdown"><em>showdown</em></a> for this.</p><pre>const <strong><em>showdown </em></strong>= <strong><em>require</em></strong>(&#39;showdown&#39;);<br><br>// convert markdown to html<br>const convertMarkdownToHtml = (md) =&gt; {<br>  const converter = new <strong><em>showdown</em></strong>.Converter({<br>    simplifiedAutoLink: true,<br>    tables: true<br>  });<br>  return converter.makeHtml(md);<br>};</pre><h3>(2/4) A way for our backend developers to document the APIs.</h3><p>Since we did not go ahead with Mulesoft or SwaggerHub, we had to custom design a database to store the APIs. We used MongoDB for this purpose. Using the same Gitlab event triggers, we stored the RAML files in S3 and stored the S3 location in the database. The primary challenge was to figure out a way to visualize the RAML files. As I mentioned earlier there are opensource tools available to convert RAML to HTML but none of them were good enough.</p><p>After some digging, we found an opensource alternative, SwaggerUI but it only takes OpenAPI as input. So we did the unspeakable. We converted RAML to Swagger and used SwaggerUI for visualization of our APIs. We used <a href="https://www.npmjs.com/package/oas-raml-converter"><em>oas-raml-converter</em></a>. For command-line interface.,</p><pre>oas-raml-converter --from RAML --to OAS30 api.raml &gt; api.json</pre><p>If you are using a Node.js application then.,</p><pre>const converter = <strong><em>require</em></strong>(&#39;oas-raml-converter&#39;);<br>const fs = <strong><em>require</em></strong>(&#39;fs&#39;);</pre><pre>// convert raml to swagger<br>const convertRAMLtoOpenApi = async (ramlFilePath, openApiFilePath) =&gt; {<br>  try {<br>    const raml10ToOas20 = new converter.Converter(converter.Formats.RAML, converter.Formats.OAS20);<br>    const convertedData = await raml10ToOas20.convertFile(ramlFilePath);<br>    // save raml to file<br>    await fileUtil.writeToFile(openApiFilePath, convertedData);<br>  } catch (e) {<br>    throw e;<br>  }<br>};</pre><pre>// write content to file<br>const writeToFile = (filePath, content) =&gt; {<br>  return new <strong><em>Promise</em></strong>((resolve, reject) =&gt; {<br>    fs.writeFile(filePath, content, {}, function (e) {<br>      if (e) reject(e);<br>      else resolve();<br>    });<br>  });<br>};</pre><p>The above function <em>convertRAMLtoOpenApi</em> takes 2 parameters. The first one is the source path where the RAML file is present. The second parameter is the destination where the OpenAPI file will be stored.</p><p>First, we define the converter object with the desired specifications. In our use case, it’s RAML to OAS20 (OpenAPI 2.0).</p><pre>const raml10ToOas20 = new converter.Converter(converter.Formats.RAML, converter.Formats.OAS20);</pre><p>Then we call the async method which takes the RAML file as input and converts to OpenAPI.</p><pre>const convertedData = await raml10ToOas20.convertFile(ramlFilePath);</pre><p>Finally, we save the file to the disk using the following method.,</p><pre>// write content to file<br>const writeToFile = (filePath, content) =&gt; {<br>  return new <strong><em>Promise</em></strong>((resolve, reject) =&gt; {<br>    fs.writeFile(filePath, content, {}, function (e) {<br>      if (e) reject(e);<br>      else resolve();<br>    });<br>  });<br>};</pre><p>The final result looks something like this.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SsfC2q7AfSTopDhpXbtt5w.png" /><figcaption>Swagger UI</figcaption></figure><h3>(3/4) A way for our frontend developers to mock the API contracts</h3><p>Frontend developers include our Web Developers as well as Android and iOS developers. Every single one of them relies on these Contracts for developing their POJO classes or Factory Interfaces.</p><p>Now that we have OpenAPI files with us, we pushed them to S3 and used <a href="https://swagger.io/tools/swagger-ui/">Swagger UI</a> for visualizing. We still needed a mock server to let work with Swagger UI. Luckily RAML has very good mock servers available. We used <a href="https://github.com/mulesoft-labs/osprey-mock-service"><em>osprey-mock-service</em></a>.</p><pre>osprey-mock-service -f api.raml -p 9000</pre><p>In Node.js there is no library that can be used to start the mock server so we use the shell execution to achieve the same.</p><pre>// start or restart mock server<br>const startOrRestartMockServer = async (port, ramlFilePath) =&gt; {<br>  try {<br>    shell.exec(`kill -9 $(lsof -t -i:${port})`);<br>    shell.exec(`osprey-mock-service -f ${ramlFilePath} -p ${port} --cors &amp;`, { async: true });<br>  } catch (e) {<br>    throw e;<br>  }<br>};</pre><p>In the above code, first, we stop any process running on the port where we want our RAML Mock server to run.</p><pre>shell.exec(`kill -9 $(lsof -t -i:${port})`);</pre><p>Then we start the new server by providing the path.,</p><pre>shell.exec(`osprey-mock-service -f ${ramlFilePath} -p ${port} --cors &amp;`, { async: true });</pre><p>It is important to note that we use <strong><em>cors</em></strong> and <strong><em>{ async: true }</em></strong>. Else the execution will stop the moment we execute the shell script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZuIqUnYnOAF5lQFr1kpdQ.png" /><figcaption>Mocking RAML in Swagger UI</figcaption></figure><h3><strong>(4/4) An API validation layer for our APIs.</strong></h3><p>API Validation is one of the key features of API Governance. This is also a key security concern. Hackers will try to take advantage of poorly written or insecure APIs to extract sensitive information.</p><p>For example.,</p><pre>POST /login?email=&lt;email&gt;&amp;password=&lt;password&gt;<br># Hackers can use tools like wireshark or metasploit for capturing the secure information</pre><pre>GET /resource?limit=100000<br># Hackers can overlaod the database and capture all the data</pre><p>The best way to restrict them is by allowing only those APIs which are defined in the API Spec. This is achieved in two ways.,</p><ol><li>Addition of RAML validation in the application layer (middlewares)</li><li>Addition of RAML validation in the network layer (using CDNs like Akamai)</li></ol><p>There is a definite increment in the latency because of this but that is the price we pay to keep the REST endpoints secure.</p><p>We used <a href="https://www.npmjs.com/package/osprey"><em>osprey</em></a> for our Node.js Backend.,</p><pre>const osprey = require(&#39;osprey&#39;);</pre><pre>osprey.loadFile(path.join(__dirname, &#39;api_spec/api.raml&#39;), {})<br>  .then(function (middleware) {<br>  app.use(&#39;/api/&#39;+version, middleware, indexRouter);<br>  app.listen(port, () =&gt; {<br>    <strong><em>console</em></strong>.log(`listening to requests on port ${port}`);<br>  });<br>}).catch(function(e) {<br>  console.error(&quot;Error: %s&quot;, e.message);<br>});</pre><p>If there any errors in the raml file, an error will be thrown before starting the server. But using CDNs for RAML validation is the way ahead.</p><h3><strong>(Optional) We needed validators to help developers debug RAML.</strong></h3><p>Popular IDEs have plugins for supporting RAML. In the case of Intellij, we used the <a href="https://plugins.jetbrains.com/plugin/8459-raml-plugin-for-intellij/">RAML Plugin for Intellij</a>.</p><p>In Command-line, we can run the following to debug RAML using <a href="https://www.npmjs.com/package/raml-js-validator"><em>raml-js-validator</em></a>.</p><pre>raml-validate api.raml</pre><p>The support for RAML has been growing day by day and with an increase in developer adoption and continuous open-source contributions, we can finally count on RAML for writing concise and reusable API Specs.</p><p>I have obviously not explained in detail each step of the whole automation process because it goes beyond the scope of this article. However, if you have any questions, feel free to post in the comments.</p><h3>Verdict</h3><p>After implementing zDock, in a matter of week’s time, we were able to review and document 9 microservices. These services include close to 150 APIs. Our Frontend team was able to start designing Web Pages and App views as soon as RAML files were committed.</p><p>Of course, this was not easy. Our developers had to learn RAML and implement it for every single API they developed. We had to conduct multiple sessions and reiterate our process multiple times to make it work.</p><h3>Know more about</h3><ul><li>API Governance and Best Practices <a href="https://swagger.io/resources/articles/best-practices-in-api-governance/">here</a>.</li><li>RAML Tutorials <a href="https://raml.org/developers/raml-100-tutorial">here</a>.</li></ul><p><em>If you are into DevOps or Fullstack and find terms like ServiceMesh, Infrastructure Automation, Event Loop and Micro-Frontends exciting as much as we do, then drop us a line at </em><a href="/service/mailto:join-tech@zolostays.com"><em>join-tech@zolostays.com</em></a><em>. We would love to take you out for a Coffee ☕ to discuss the possibility of you working with us.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47b99a04d483" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zolo-engineering/take-control-of-your-apis-by-implementing-api-governance-using-raml-node-js-47b99a04d483">Take control of your APIs by implementing API Governance — Using RAML &amp; Node.js</a> was originally published in <a href="https://medium.com/zolo-engineering">Zolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#DevExplore: Aravind Raj | Android Dev Summit 2019]]></title>
            <link>https://medium.com/zolo-engineering/devexplore-aravind-raj-android-dev-summit-2019-99368b1367a0?source=rss----2c3ca3d17328---4</link>
            <guid isPermaLink="false">https://medium.com/p/99368b1367a0</guid>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Aravind Raj]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 13:31:56 GMT</pubDate>
            <atom:updated>2019-11-27T13:41:51.929Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>An Artist always finds new ways to express his thoughts;<br>An Athlete always challenges himself in different ways to excel in his sport;<br>Just like that a good Software Engineer should regularly practice, explore new technologies and improve his skills to make great products.</blockquote><p><em>This is the driving principle behind our work at </em><strong><em>Zolostays</em></strong><em>, every day.</em></p><p>Our Tech first Approach has helped us scale our business rapidly across 10+ cities and improve our operations and services efficiently since Day One.</p><p>We have a Technology team consisting of 30+ Developers, Product Managers, Designers and Leaders who help us shape our thoughts and business requirements into scalable products.</p><p>To that effect, we encourage our Developers and Designers to be an active part of the community and keep learning from each other. We also regularly host meetups at our office and try to accommodate as many community events as possible. If you’re a community organizer and looking for a place to host your next meetup or for sponsorship, do reach out to one of our team members.</p><p>On that note, one of our Android Developers, <a href="https://twitter.com/aravindcraj"><strong><em>Aravind Raj</em></strong></a> had recently got the opportunity to attend the <strong><em>Android Dev Summit 2019 </em></strong>at <strong><em>Sunnyvale, California. </em></strong>When we asked him about his experience and what he had learned, he was very excited to share his experiences which many might find helpful.</p><p>Over to Aravind.</p><figure><img alt="Aravind at Android Dev Summit, 2019." src="https://cdn-images-1.medium.com/max/1024/1*Lij7qvw4mrttb85KXbwObQ.jpeg" /><figcaption>Aravind at Android Dev Summit, 2019.</figcaption></figure><p>Hi, I’m <em>Aravind Raj, Sr. Android Developer at Zolostays</em>. I have been following the Android Dev Summit for the past few years and this was my first time attending it in person. I was extremely excited to meet all the great engineers from the Android team and a lot of amazing people from the community. 😍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFf8rvy3cuaMJiAWx4-ANA.png" /></figure><p>I arrived a bit early for the conference to complete my registration and collect my badge. I was a little nervous and felt blank since this was my first time, but the organizers were so helpful and kind to answer all my queries so politely. ☺️</p><h4>Keynote</h4><p>The room was fully packed and somehow I managed to get a seat in the middle of the hall. Everyone was very excited about the new things that were expected to release like Jetpack Compose Developer preview, Bazel support (Since it hit 1.0 a few days before the conference), etc.,</p><p>Android Dev Summit, 2019 started with an amazing keynote by <strong><em>Dave Burke</em></strong>, VP of Engineering and <strong><em>Steph Cuthbertson</em></strong>, Senior Director of Product Management.</p><p>The keynote had a lot of exciting news for Android Devs like:</p><ul><li><em>Jetpack Compose: Developer release</em></li><li><em>Android Studio 4.0: Canary release.</em></li><li><em>Motion Editor.</em></li><li><em>Modern Android Development.</em></li><li><em>Kotlin: Associate Android Developer Certification.</em></li><li><em>Kotlin build scripts full support.</em></li><li><em>Android Developer Challenge.</em></li></ul><h4><a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a></h4><p>Earlier this year at Google IO, 2019 the Android team had announced Jetpack Compose, a declarative UI toolkit but to be honest it was really hard and took a lot of effort to try out. We had to clone the entire repository and there were not many documents or examples to learn from. 😫</p><p>Looks like the Jetpack Compose team heard us and released a developer preview so we could try it out easily. We just need to download Android Studio 4.0 ➡️ New Project ➡️ Empty Compose Activity, that’s it. 🎉</p><p>We just made our “<em>Hello World” app using Jetpack Compose. </em>Yaaaay! 👏</p><p>I was personally very excited about this because I had been trying out Compose for a while now. It changes the way we think and develops our app UI, with reusability, and the code is clean and concise. Though it’s a little early for Compose, it’s worth to try it out and understand how it works.</p><p><a href="https://github.com/aravindcraj/jetpack-compose-samples">Check out the Sample projects to learn more about it.</a></p><h4><a href="https://developer.android.com/studio/preview">Android Studio 4.0</a></h4><p>Android Studio 4.0 is filled with a lot of features like Jetpack Compose, Motion Editor, New Layout Inspector with 360-degree hierarchy, Kotlin Build Script (KTS) support, View Binding, etc. There has never been a better time to try out all these new things. :D <strong>|| There has never been a better time to be an Android developer.’</strong></p><p>We have been using Kotlin Build Script (KTS) for almost ten months in production now and it has been a little difficult to maintain the project and update dependency manually by checking since KTS was not officially supported. It has become easier for us to maintain now as KTS is now officially supported. I always wanted the 360-degree hierarchy view on Layout Inspector since the time our iOS developer showed it to us on XCode. Project Marble brought a lot of stability changes to Android Studio and with all these new features Android Studio is easily one of the best IDEs.</p><h4><a href="https://developer.android.com/studio/preview/features#motion-editor">Motion Editor</a></h4><p>Creating meaningful and intuitive animations has never been easier. Motion Editor is a visual editor for creating animations and transitions for Motion Layout in which the motions can be triggered using click or swipe on the editor itself with preview.</p><p>As soon as I returned to work, I sat with our designers and showed them how easy it was to create cool animations using Motion Editor. The flexibility it gives to trigger an animation with various inputs like click, swipe, etc. is really amazing! The best thing about this is that we can play and see all these things in our layout preview section itself. 😃</p><h4><a href="https://youtu.be/5jJ-e278BFY?list=PLWz5rJ2EKKc_xXXubDti2eRnIKU0p7wHd&amp;t=919">Modern Android Development</a></h4><p>Modern Android Development is nothing but opinionated recommendations to build Android Applications using Jetpack Libraries. There has been a lot of support from Google in recent times for developer tools and libraries.</p><p>Jetpack Libraries have already been helping us a lot in writing clean and robust apps with less code. With Modern Android Development, the team promises to add more such libraries and continues to improve existing libraries to make our Developer experience more delightful. Some of the new releases are:</p><ul><li>Jetpack Compose — a new UI toolkit library to simplify UI development.</li><li>Jetpack Benchmark — to quickly benchmark your Android project on various things like Performance, Memory, etc.</li><li>Jetpack CameraX — to easily add powerful camera capabilities to Android apps.</li><li>ViewBinding — to get rid of findViewById and reference our views directly.</li></ul><p><em>I hope one-day Jetpack Keyboard will be made to handle Soft keyboard. </em>🙏</p><h4><a href="https://developers.google.com/certification/associate-android-developer">Kotlin: Associate Android Developer Certification</a></h4><p>Google announced a new Associated Android Developer certification with a specialization in Kotlin. As an introductory offer, you can avail the course for just $99 using the coupon code <strong>ADSCERT99. </strong>People who have attended the conference in person get it <strong>free of cost</strong>.</p><p>Another best part of attending the Android Dev Summit is that you get to meet a lot of great developers from all over the world and talk to Google Engineers, get your app reviewed and ask them all your doubts directly. Don’t hesitate as the team is very helpful. 😇</p><h4>People I met!</h4><figure><img alt="Stephanie Cuthbertson, Director Android at Google." src="https://cdn-images-1.medium.com/max/1024/1*ewrfpB2OJ3MHb-J3_NZDVQ.jpeg" /><figcaption>Stephanie Cuthbertson, Director, Android at Google.</figcaption></figure><p>Privileged to meet and have a great conversation with Steph, Director of Android about various things such as Future of Android, Wearables, Developer Experience, etc. Oh yeah! Even they are sad with Android names being replaced with numbers. Hope they come back soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvtp7gwE0-0gduQ1ezV8fg.jpeg" /><figcaption>Come on you know him.</figcaption></figure><p>Totally an unexpected conversation! I was very tired and was heading back to my hotel during the Afterparty. I thought I will grab a dessert by the time my cab arrives and ran into Chet, who was such a fun person to talk to and had such an amazing conversation about how I started with Android Development and how much the community has helped me to learn new things. I got to hear a lot of stories from his experience and was so lucky to be there at that time. By the way, Chet left to Droidcon London right after we met. 😃</p><figure><img alt="Nick Butcher (@crafty)" src="https://cdn-images-1.medium.com/max/1024/1*lidZALBnK_yiKUW0V-LaYw.jpeg" /><figcaption><a href="https://medium.com/u/22c02a30ae04">Nick Butcher</a></figcaption></figure><p>I would have been disappointed if I hadn’t met <a href="https://medium.com/u/22c02a30ae04">Nick Butcher</a>! Nick is an inspiration for me and many other devs; <a href="https://youtu.be/EjTJIDKT72M">his talk on Material Design at Google IO, 2016</a> has changed the way I think about developing apps and interactions. His samples, blogs, and <a href="https://github.com/android/plaid">Plaid</a> had helped me and a lot of other developers out there in learning many new things and understand the right way to do things! 😍</p><p>It was the most stupendous experience I have ever had at a conference. The place had very positive vibes and I had learned a lot. Looking forward to building great apps with everything I have learned.</p><p><strong>I would like to take this moment to thank <em>Akhil Sikri, CTO &amp; Sooraj, AVP Engineering at Zolostays</em> for giving me this great opportunity to attend the conference and sponsoring this trip. #DevExplore is a great initiative the company has started to help people learn new things and help them build great products.</strong></p><p>Further reads:</p><ul><li><a href="https://youtu.be/5jJ-e278BFY">Android Dev Summit, 2019 Keynote Video</a></li><li><a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a></li><li><a href="https://developer.android.com/jetpack/compose/tutorial">Jetpack Compose tutorial</a></li><li><a href="https://codelabs.developers.google.com/codelabs/jetpack-compose-basics/#0">Jetpack Compose Codelab</a></li><li><a href="https://medium.com/google-developers/defining-motion-paths-in-motionlayout-6095b874d37">Defining motion paths in MotionLayout</a></li><li><a href="https://developers.google.com/certification/associate-android-developer">Kotlin: Associate Android Developer Certification</a></li><li><a href="https://android-developers.googleblog.com/2019/10/android-dev-summit-2019-keynote.html">Modern Android Development</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99368b1367a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zolo-engineering/devexplore-aravind-raj-android-dev-summit-2019-99368b1367a0">#DevExplore: Aravind Raj | Android Dev Summit 2019</a> was originally published in <a href="https://medium.com/zolo-engineering">Zolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adaptive Web Applications with React, Redux]]></title>
            <link>https://medium.com/zolo-engineering/adaptive-web-applications-with-react-redux-d3dfcdf2cee8?source=rss----2c3ca3d17328---4</link>
            <guid isPermaLink="false">https://medium.com/p/d3dfcdf2cee8</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[adaptive-web-design]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Jailany Mohamed]]></dc:creator>
            <pubDate>Wed, 13 Nov 2019 14:18:57 GMT</pubDate>
            <atom:updated>2019-12-06T07:15:52.897Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adaptive Web Applications with React and Redux</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RGfQUrLNE3zLlOTi" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee?utm_source=medium&amp;utm_medium=referral">William Iven</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>What is an Adaptive Web Application?</strong></h3><p>An Adaptive web application, as opposed to a responsive web application use separate UI templates for different devices the user may use to access the application from. Adaptive web applications is not a new thing, I am sure you will remember the mobile domains (m.domain.com) to which the user will be redirected whenever he/she visited the site in a mobile device. Having a separate mobile site is also a form of an Adaptive Application, but it is not optimal as it comes along with its own problems like infrastructure, separate domain names etc.,</p><p>With an adaptive setup, you can render different template and content to different devices. The devices included can be Desktop, Mobile, Tablets, TV Devices and Bots.</p><h3>Why do we need Adaptive Web Applications?</h3><p>With the increased usage of mobile phones, it is essential for any transactional website to keep their design and UX mobile-first. Adaptive Development, lets you do that without compromising anything on the desktop counterpart.</p><p>Google has also started crawling and indexing web-pages using a mobile-first approach. This means that your website should be highly optimised for mobile with respect to content served and its speed. It is a lot of pain and work to get a higher page speed score for a responsive site which is not optimised for mobile. Adaptive Web Applications can help you tackle this problem as well.</p><p>The following are some of the advantages of AWA’s:</p><ol><li>Serve template and content as per the device of the user</li><li>Provide flows and UX tailor-made for different devices</li><li>Optimise your application by controlling what gets sent to the end-user device (HTML, Styles, Scripts, Assets, etc)</li></ol><h3>How was it done before SPAs?</h3><p>Before the implementation of Single Page Applications, the content for the page was rendered on the server and sent to the browser. In the older implementations, the mobile version of the site was hosted under a different subdomain, usually a mobile domain. The web server will find the device type from the user-agent header of the request and redirect the user to the mobile domain. The problem here is having a separate domain and an application for different device types.</p><p>It is also possible to do this without a separate mobile domain. We can set up adaptive rendering with Express JS using Handlebars as a templating engine. In this setup, express finds the device type of the request and pick the template from different folders. Even though we can solve the different domain problem in this approach, the pages are still server-rendered individually.</p><h3>How can it be done with client rendered SPAs?</h3><p>In the client-side world, the app loads the shell from the server and the rest of the application is mounted once the script is executed. To load a template or component conditionally, we can either use the width of the device or evaluate the userAgent property in the navigator object. The former approach is much lesser fool-proof compared to the latter.</p><p>This setup goes for a toss when we implement server-side rendering for faster-perceived speed and SEO purposes. This is because the device detection has to happen in the server and has to be propagated into the UI components. We cannot employ the methods discussed above since the `<strong><em>window</em></strong>` and `<strong><em>navigator</em></strong>` objects are not available in the server.</p><h3>How did we do it in a Server Rendered SPA?</h3><p>At <a href="https://zolostays.com/">Zolo</a>, We have a Server Rendered adaptive web application which is built with the help of React, Redux and couple of other libraries. The adaptive nature of our application helps us in providing separate UI for desktop and mobile users. We created our mobile UI to look and feel like a mobile app since ours is also an installable Progressive Web Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCSvj0DUOt1QvRjAWw0CKQ.png" /><figcaption>Desktop and Mobile Templates of a Property Details Page</figcaption></figure><p>Based on our implementation, we have created a starter kit for anyone who wishes to learn or implement Adaptive Web Design in their application.</p><p>Here is a rough outline of what we will be doing to implement Adaptive Web Design in a React-Redux application.</p><ol><li>Create an App Shell</li><li>Create Page Components for Desktop and Mobile Devices</li><li>Create an Express Server with feature to detect the device type</li><li>Create a shared Redux store between the Client and the Server</li><li>Set the device type in the store and pass it down to the browser</li><li>Use the value in the store to conditionally render the components</li></ol><blockquote>Note: We will not be going through the details of the webpack and other configurations of the project.</blockquote><p>We will be going through the above steps one by one with an example in the section below.</p><h4>Project Structure</h4><p>Our project will follow the folder structure as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*UmnM0S_ntXBg7B0UzYoSVg.png" /></figure><p>Client and Server logic are kept in separate folders.</p><p>In the client folder, we have an App Shell file (App.jsx) which holds the routing and shell logic. The pages folder will have all the page templates of different devices identified by the file extension.</p><p>We have designed the app in such a way that the actions, reducers, and services for the devices are kept the same. We will see that structure further down the article.</p><h4>Create an App Shell</h4><p>First, we create an App shell which will be common for desktop and mobile templates. You can have different App Shells for different device types. We keep it the same for simplicity.</p><p>We add the following code in the App.jsx file for creating the App Shell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45f71bacf8e410a0770fbbf222cca25f/href">https://medium.com/media/45f71bacf8e410a0770fbbf222cca25f/href</a></iframe><p>In the App Shell, we use styled-components to create a header which will be common for desktop and mobile.</p><h4>Create Page Components</h4><p>After creating the App Shell, we create two files in the pages folder, `<strong><em>home.desktop.jsx</em></strong>` and `<strong><em>home.mobile.jsx</em></strong>` which are the page files of the Home page. We have the files segregated with the device name as the extension.</p><p>Let’s create a simple page component that displays a line of text along with the device type.</p><p><strong>Desktop Component</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/548f298f50341dc3a00ba40c5ee3cd24/href">https://medium.com/media/548f298f50341dc3a00ba40c5ee3cd24/href</a></iframe><p><strong>Mobile Component</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec58be41a84d54c7dd887333263ac81d/href">https://medium.com/media/ec58be41a84d54c7dd887333263ac81d/href</a></iframe><p>In the above files, we created two simple page components. One for Desktop and One for Mobile.</p><h4>Create an Express Server</h4><p>We use express as our web server which will receive the first request and send the HTML response back to the browser.</p><p>In our case, only the first request will be served by Express, all the other navigation will be handled on the client-side by React.</p><p>In the server folder, we create the file `<strong><em>index.js</em></strong>` with the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7f5977de8ea94608ff69678d9e5dce4/href">https://medium.com/media/c7f5977de8ea94608ff69678d9e5dce4/href</a></iframe><p>Once we have the server up and running, we use <a href="https://www.npmjs.com/package/express-device"><strong>express-device</strong></a> package to find the device type.</p><pre>const device = require(‘express-device’);<br>app.use(device.capture());</pre><p>Now if you try to print req.device in the console, you will see the device object containing the following data.</p><pre>{ parser: <br>   DeviceParser {<br>     options: <br>      { emptyUserAgentDeviceType: &#39;desktop&#39;,<br>        unknownUserAgentDeviceType: &#39;phone&#39;,<br>        botUserAgentDeviceType: &#39;bot&#39;,<br>        carUserAgentDeviceType: &#39;car&#39;,<br>        consoleUserAgentDeviceType: &#39;tv&#39;,<br>        tvUserAgentDeviceType: &#39;tv&#39;,<br>        parseUserAgent: false<br>     },<br>     make_sure_parser_was_executed: [Function],<br>     get_model: [Function],<br>     get_type: [Function]<br>  },<br>  type: &#39;desktop&#39;,<br>  name: &#39;&#39; <br>}</pre><p>As you can see, we can get the type of device from <strong>req.device</strong></p><h4>Create Redux Store</h4><p>The next step is to create a redux store for storing the device type and other data as necessary.</p><p>We create a reducer file called core.reducer.js and set the initialState as mentioned below and export it for combining it with other reducers in the index reducer file.</p><pre>const initialState = {<br> config: {<br>   deviceType: &#39;&#39;<br> }<br>};</pre><p>In the index reducer file, we import the core reducer and combine it using <strong>combineReducer.</strong></p><blockquote>Note: In the example, we have only one reducer to explain the concept.</blockquote><p>Once the reducer is set up, we create the store using a function that will be shared by both the client and the server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24dff2d98eb2a2291cb1d960972a91c0/href">https://medium.com/media/24dff2d98eb2a2291cb1d960972a91c0/href</a></iframe><p>In the client folder, we import the configureStore function in the index.js file to create the store and add it to the Provider. We do the same in the server part as well.</p><p><strong>Client Store Creation</strong></p><pre>import { configureStore } from &#39;../server/framework/store&#39;;<br>const initialState = {};<br>const store = configureStore(initialState);</pre><p><strong>Server Store Creation</strong></p><pre>import { configureStore } from &#39;./store&#39;;<br>const store = configureStore({});</pre><h4>Set the device type on the Server State and pass to Client</h4><p>Once the store is created in the server, we extract that state using the getState() function.</p><pre>let state = store.getState();</pre><p>After that, we set the device type which we got from req.device.type in the state object.</p><pre>state.core.config.deviceType = req.device.type;</pre><p>Now, we have the device type stored in the state object which can be passed down to the client by setting it in the WINDOW object.</p><p>To do this, we take the HTML text which we got from reading the main.html file. We append the stringified state object to the end of the HTML and pass it on to the client as response.</p><pre>const store = configureStore({});<br>const state = store.getState();<br>state.core.config.deviceType = req.device.type;<br>const htmlPath = path.resolve(__dirname, &#39;../../build/main.html&#39;);<br>fs.readFile(htmlPath, &#39;utf8&#39;, (err, data) =&gt; {<br>  const html = data.replace(&#39;&lt;script&gt;&lt;/script&gt;&#39;,<br>    `&lt;script&gt;window.__PRELOADED_STATE__=${JSON.stringify(state)}<br>    &lt;/script&gt;`<br>  )<br>  res.send(html);<br>});</pre><h4>Conditionally render the components</h4><p>Earlier, we set the device type in the state on the server-side and pass it to the client-side.</p><p>In the client-side, while creating the store, we pass the object we got from the server as the initial state to the configureStore function. This will create the store on the client-side with the same state object from the server.</p><pre>import { configureStore } from &#39;../server/framework/store&#39;;<br>const initialState = window.__PRELOADED_STATE__ ?    window.__PRELOADED_STATE__  : {};<br>const store = configureStore(initialState);</pre><p>Now that we have the device type in the store, next step would be to connect to the store from the App shell and use the value to conditionally render the pages/components.</p><p>To connect to redux store from a react component, we use the connect method.</p><p>Once we get the value from the state as a prop in the component, we can do the conditional rendering of components as mentioned below.</p><pre>{<br>  this.props.config.deviceType === ‘desktop’ ? &lt;HomePageDesktop/&gt; : &lt;HomePageMobile/&gt;<br>}</pre><p>As you can see, the content of the page changes based on the device from which the site was accessed.</p><h3>Upcoming Work</h3><p>You might wonder why we have Redux here even though the usage of it has been very minimal in the example.</p><p>The above example can be implemented without the help of Redux. We can easily set the device type as a variable in the window object and use it in the components. This method will work fine as long as we are rendering only on the client. The same will be an issue if we are rendering on the server which can be solved by using Redux.</p><p>We will get into the implementation of the same in detail in the upcoming articles related to Server Side Rendering, Server Side Data loading. For now, the above method and the architecture help you create Adaptive Web Applications in React.</p><p>The codebase of the Adaptive Web Starter Kit is available <a href="https://github.com/ZoloStays/react-aw-starter">here</a>.</p><p>This article was originally posted <a href="https://zolostays.com/blog/adaptive-web-applications-with-react-and-redux/">here</a> on the <a href="https://zolostays.com/blog">Official Blog</a> of <a href="https://zolostays.com/">Zolostays</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3dfcdf2cee8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zolo-engineering/adaptive-web-applications-with-react-redux-d3dfcdf2cee8">Adaptive Web Applications with React, Redux</a> was originally published in <a href="https://medium.com/zolo-engineering">Zolo Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>