<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Narsimha on Medium]]></title>
        <description><![CDATA[Stories by Narsimha on Medium]]></description>
        <link>https://medium.com/@narsimhulu-464?source=rss-395aec026d0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3G_5ImeYClobd652</url>
            <title>Stories by Narsimha on Medium</title>
            <link>https://medium.com/@narsimhulu-464?source=rss-395aec026d0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:55:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@narsimhulu-464/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Visualizing the Logs Using ELK & Grafana]]></title>
            <link>https://narsimhulu-464.medium.com/visualizing-the-logs-using-elk-grafana-70fa31f73acf?source=rss-395aec026d0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/70fa31f73acf</guid>
            <category><![CDATA[elk-stack]]></category>
            <category><![CDATA[logstash]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Narsimha]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 05:30:06 GMT</pubDate>
            <atom:updated>2020-07-30T05:30:06.584Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello folks, this is extension post for the previous <a href="https://medium.com/@narsimhulu.464/elk-stack-e-lasticsearch-logstash-k-ibana-2a0c46cfb6f8">post</a> where in we discussed about the ELK components and their advantages one by one. In this post we’ll explore an example to understand the working part of ELK. We’ll also integrate ElasticSearch with Grafana which is also one of the popular monitoring tool nowadays.</p><p>Let’s dive into the example now</p><p><strong>Procedure for monitoring an application logs Using ELK stack:</strong></p><p>Here I am taking the server logs generated by nginx for my application.</p><ul><li>Start the ELK stack products Elastic search and kibana</li><li>Note : Start ElastcSearch first and kibana next because kibana depends on ElasticSearch.</li><li>Edit the config file of nginx to get the application logs of your project like proxy settings and proxy_server_name and log_format. If you are running on your local system server or any otherone, ignore this step.</li><li>nginx by deafult provides a log_format and that format may not be required or suitable for some kind of projects.</li><li>Start Nginx and your application servers.</li><li>Write the pipeline code of logstash in a config file with the extension .conf.</li></ul><pre>input{<br>    file{<br>            path =&gt; &quot;F:/nginx-1.17.9/logs/*.log&quot; // logs path<br>            type =&gt; &quot;logs&quot;<br>            start_position=&gt;&quot;end&quot;<br><br>    }<br>}<br><br>filter{<br>  grok{<br>    match =&gt; { &quot;message&quot; =&gt; &quot;%{IPORHOST:remote_addr} - - \[%{HTTPDATE:time_local}\] \&quot;%{WORD:http_method} %{DATA:url} HTTP/%{NUMBER:http_version}\&quot; %{NUMBER:response_code} %{NUMBER:body_sent_bytes} \&quot;%{DATA:referrer}\&quot; \&quot;%{DATA:agent}\&quot;&quot;}<br>  }<br>}<br><br>output {<br> elasticsearch {<br>   hosts =&gt; [&quot;localhost:9200&quot;]<br>   index =&gt; &quot;myproject&quot;<br>   <br> }<br>}</pre><ul><li><strong>Logstash File Explanation:</strong></li><li>Mention the source from where you are getting the logs using input plugins like file,http,cloudwatch etc..</li><li>Mention the type of logs and start_position of parsing.</li><li>Start_position for static logs is beginning and for dynamic logs is end because there will be a continuous flow of logs in case running application.</li><li>Write the filters for your logs in the desired format using filter plugins like grok.</li><li>Filter part optional, it is to parse your logs. The provided filter with grok in the above example is to parse nginx logs.</li><li>Write the destinations(outputs) to where the logs should be reached.</li><li>In case of elastic search the output name is elastisearch.</li><li>Mention the hostname as localhost:9200 and desired index name inside the elastic search output plugin.</li><li>Save the file and place it anywhere. Best practice is to place it inside the bin folder of logstash because logstash batch will also be located there itself.</li></ul><p>Start logstash by configuring the written config file like cfile.conf to logstash batch file.</p><p>Command : pathToLogstashBatchfileInsideBinFolder\logstash.bat -f pathWhereTheConfigFileLocated\Filename.conf</p><p>Example: .\logstash -f cfile.conf (Both files are located inside the bin folder only)</p><p>After successful run of logstash config file it will create index with the index name given in the config file.</p><p>We can check the whether the index is created or not using the address : <a href="http://localhost:9200/_cat/indices/">http://localhost:9200/_cat/indices/</a></p><p>Move to kibana and create the index pattern name with the same name given in config file by clicking on management tab in kibana.</p><p>Go to Discover tab</p><p>Select the index pattern name and visualize the logs transported from our application to elasticsearch through logstash when your application is under usage.</p><p>For better visualization purpose create graphs,pie charts etc..</p><p>To search for a particular type of log click on search and enter the keywords.</p><p>Check the logs for a range of time by using calendar option in kibana dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4n8iPOio1G6AU8b0nnzhQ.png" /><figcaption>Kibana Dashboard</figcaption></figure><p><strong>Procedure for Visualizing the logs of ElasticSearch Indices in Grafana</strong></p><ul><li>Start Grafana ,By default grafana works at port 3000.</li><li>Create an elastic search type datasource</li><li>Give name of the datasource.Mention the http url where elastic search operates. Default : <a href="http://localhost:9200/">http://localhost:9200</a></li><li>Give the Index pattern name for which you need to create the visualizations and elastic search version that you’re using on your local machine.</li><li>Provide data link if needed(optional)</li><li>click on save and Test button</li><li>If all the information provided for creating a datasource is fine then it says index name and datasource is ok.</li><li>Else check the index pattern name sometime it asks to mention the pattern name inside [] like [pattern_name].</li><li>Go to create a dashboard</li><li>create a panel by selecting Query as recently created elasticSearch datasource name and choose metric as the logs</li><li>Give name for panel then you’ll be able to view our application logs in grafana dashboard.</li><li>Alert can be created on graphs if required.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hntDWJIQtvKGwU4nvUuFWw.png" /><figcaption>ElasticSearch Datasource creation in Grafana</figcaption></figure><p>After adding elastic search datasource, we can look into logs and alarms set details graphically in Grafana Dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sz8QQSYIqqDn_IX1cQUzRA.png" /><figcaption>Grafana Dashboard</figcaption></figure><p>That’s it about the Visualizing the logs in Kibana and Grafana guys, For any queries on this article do comment here or reach my out at <strong>narsimhulu.464@gmail.com </strong>and at LinkedIn <strong>B Narsimha</strong>.</p><p><strong>Thank You!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70fa31f73acf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ELK STACK -E(lasticSearch)L(ogstash)K(ibana)]]></title>
            <link>https://narsimhulu-464.medium.com/elk-stack-e-lasticsearch-logstash-k-ibana-2a0c46cfb6f8?source=rss-395aec026d0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a0c46cfb6f8</guid>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[kibana]]></category>
            <category><![CDATA[logstash]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Narsimha]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 12:58:16 GMT</pubDate>
            <atom:updated>2020-07-30T05:32:56.907Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello folks, this post is the first part of ELK stack series in which will explains about the ELK stack which is mainly used for the Log Analysis and Log Management. ELK is the combination of ElasticSeach, Logstash and Kibana.</p><blockquote><strong>What is ELK?</strong></blockquote><blockquote>Elastic Stack is the collection of three open source products from Elastic such as Elastic Search,Logstash and kibana and it is designed to help users take data from any type of source and in any format and search, analyze, and visualize that data in real time. It uses Logstash for log aggregation, Elasticsearch for searching, and Kibana for visualizing and analyzing data.</blockquote><p><strong>Challenges Before ELK:</strong></p><ul><li>There is no universal log data structure format existing.</li><li>The formats of the logs can depend on various factors like the device type, vendor, application etc. This inconsistency in log structures would make the searching on logs a difficult process</li><li>The most important data in a log file is its time field.</li><li>But what happens when the time formats are different across different logs?. It becomes very difficult for us to do operations based on time.</li><li><strong>Logs of interest maybe</strong></li><li>a. Spread across different machines</li><li>b. Depending on the machine logs differ in formats</li><li>c. On different locations in the same machine</li><li><strong>In order to get useful insights from the data</strong></li><li>a. The data must be accessible.</li><li>b. Need for experienced workforce who are able to understand the log data</li><li>It is difficult for people to understand and make inferences from the textual data of the logs.</li></ul><p><strong>How ELK Helps in solving the above issues:</strong></p><ul><li>Would collect all the data, centralize it</li><li>Parse the logs to a common format, including time details</li><li>Makes the logs quickly searchable and analyzable</li><li>Visualize the data in numerous ways with a wide range of analytics</li><li>Allows the end user to draw inferences from data with minimal technical overhead.</li></ul><p><strong>ELK Architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHkmFPM4U35bBSNZ-kD4Aw.png" /></figure><p>As we can see in the above diagram, logstash will listen to the logs from the one or many applications and transform those to JSON format and send to ElasticSearch.</p><p>ElasticSearch will then process the logs, creates an index with the name given in Logstash configuration and store on to it.</p><p>Users can view the logs from Kibana which is the user interface for elastic search cluster.</p><p>If you are not yet installed ELK components, install them from <a href="https://www.elastic.co/guide/en/elastic-stack/7.x/installing-elastic-stack.html">here</a>.</p><h3><strong>Components Of ELK Stack:</strong></h3><ol><li><strong>Elastic Search:</strong></li></ol><ul><li>Elasticsearch is a NoSQL database. It is based on Lucene search engine, and it is built with RESTful APIS. It offers simple deployment, maximum reliability, and easy management.</li><li>It also offers advanced queries to perform detail analysis and stores all the data centrally. It is helpful for executing a quick search of the documents.</li><li>Elasticsearch also allows you to store, search and analyze big volume of data. It is mostly used as the underlying engine to powers applications that completed search requirements.</li><li>It has been adopted in search engine platforms for modern web and mobile applications. Apart from a quick search, the tool also offers complex analytics and many advanced features.</li></ul><p><strong>Features of Elastic search:</strong></p><ul><li>Open source search server is written using Java</li><li>Used to index any kind of heterogeneous data</li><li>Has REST API web-interface with JSON output</li><li>Full-Text Search</li><li>Near Real Time (NRT) search</li><li>Sharded, replicated searchable, JSON document store</li><li>Schema-free, REST &amp; JSON based distributed document store</li><li>Multi-language &amp; Geolocation support</li></ul><p><strong>Important Terms in elastic search:</strong></p><ul><li>Cluster :A cluster is a collection of nodes which together holds data and provides joined indexing and search capabilities.</li><li>Node : A node is an elasticsearch Instance. It is created when an elasticsearch instance begins.</li><li>Index pattern : We can create indices in elastic search through kibana which is called as a database in relation databases.</li><li>Type : It is the type of the log file which is called as a Table in RDS</li><li>Document: Documents refers to logs which is called as row in RDS terms</li><li>Field: Field is a column in RDS</li><li>Mapping :Schema</li></ul><p><strong>Advantages of Elastic Search:</strong></p><ul><li>Store schema-less data and also creates a schema for your data</li><li>Manipulate your data record by record with the help of Multi-document APIs</li><li>Perform filtering and querying your data for insights</li><li>Based on Apache Lucene and provides RESTful API</li><li>Provides horizontal scalability, reliability, and multitenant capability for real time use of indexing to make it faster search</li><li>Helps you to scale vertically and horizontally.</li><li>The default port where elastic search operates is 9200.</li><li>The indices created can be available at address : <a href="http://localhost:9200/_cat/indices/">http://localhost:9200/_cat/indices/</a></li></ul><p><strong>2. Logstash:</strong></p><ul><li>Logstash is the data collection pipeline tool.</li><li>It collects data inputs and feeds into the Elasticsearch.</li><li>It gathers all types of data from the different source and makes it available for further use.</li><li>Logstash can unify data from disparate sources and normalize the data into your desired destinations.</li><li>It allows you to cleanse and democratize all your data for analytics and visualization of use cases.</li></ul><p><strong>LogStash Components:</strong></p><ul><li>Input: passing logs to process them into machine understandable format.</li><li><strong>Sample Inputs:</strong></li><li>a. File : Streams events from files</li><li>b. cloudwatch : Pulls events from the Amazon Web Services CloudWatch API</li><li>c. Beats :Receives events from the Elastic Beats framework</li><li>d. github : Reads events from a GitHub webhook</li><li>e. http : Receives events over HTTP or HTTPS</li><li><strong>Filters</strong>: It is a set of conditions to perform a particular action or event</li><li><strong>Sample Filter plugins:</strong></li><li>a. grok : Parses unstructured event data into fields</li><li>b. Metrics : Aggregates Metrics.</li><li>c. uuid : Adds a UUID to events</li><li><strong>Output: </strong>Decision maker for processed event or log</li><li><strong>Sample Outputs:</strong></li><li>a. Elastic search : Stores Logs into Elastic Search.</li><li>b. File : Writes files into file on disk.</li><li>c. pipe : pipes events to another programs standard input.</li></ul><p><strong>Features of Logstash</strong></p><ul><li>Events are passed through each phase using internal queues</li><li>Allows different inputs for your logs</li><li>Filtering/parsing for your logs</li></ul><p><strong>Advantages of Logstash</strong></p><ul><li>Offers centralize the data processing</li><li>It analyzes a large variety of structured/unstructured data and events</li><li>Offers plugins to connect with various types of input sources and platforms</li></ul><p><strong>3. Kibana:</strong></p><ul><li>Kibana is a data visualization which completes the ELK stack. This tool is used for visualizing the Elasticsearch documents and helps developers to have a quick insight into it.</li><li>Kibana dashboard offers various interactive diagrams, geospatial data, and graphs to visualize complex quires.</li><li>It can be used for search, view, and interact with data stored in Elasticsearch directories.</li><li>Kibana helps you to perform advanced data analysis and visualize your data in a variety of tables, charts, and maps.</li><li>In Kibana there are different methods for performing searches on your data.</li><li><strong>Here are the most common search types:</strong></li><li>Free text searches :It is used for searching a specific string</li><li>Field-level searches : It is used for searching for a string within a specific field</li><li>Logical statements : It is used to combine searches into a logical statement.</li><li>Proximity searches: It is used for searching terms within specific character proximity.</li></ul><p><strong>Features of Kibana:</strong></p><ul><li>Powerful front-end dashboard which is capable of visualizing indexed information from the elastic cluster</li><li>Enables real-time search of indexed information</li><li>You can search, View, and interact with data stored in Elasticsearch</li><li>Execute queries on data &amp; visualize results in charts, tables, and maps</li><li>Configurable dashboard to slice and dice logstash logs in elasticsearch</li><li>Capable of providing historical data in the form of graphs, charts, etc.</li><li>Real-time dashboards which is easily configurable</li><li>Enables real-time search of indexed information</li><li>By deafult kibana works at the port : 5601</li></ul><p><strong>Advantages and Disadvantages of Kibana</strong></p><ul><li>Easy visualizing</li><li>Fully integrated with Elasticsearch</li><li>Visualization tool</li><li>Offers real-time analysis, charting, summarization, and debugging capabilities</li><li>Provides instinctive and user-friendly interface</li><li>Allows sharing of snapshots of the logs searched through</li><li>Permits saving the dashboard and managing multiple dashboards</li></ul><p>That’s it about the ELK stack guys, for the example implementation of ELK and stack and visualizing the logs in Kibana and Grafana have a look at <a href="https://medium.com/@narsimhulu.464/visualizing-the-logs-using-elk-grafana-70fa31f73acf">here</a>.</p><p>For any queries on this article do comment here or reach my out at <strong>narsimhulu.464@gmail.com </strong>and at LinkedIn <strong>B Narsimha</strong>.</p><p><strong>Thank You!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a0c46cfb6f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SonarQube For Continuous CodeQuality Testing]]></title>
            <link>https://narsimhulu-464.medium.com/sonarqube-for-continuous-codequality-testing-3eecb6fe27e3?source=rss-395aec026d0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eecb6fe27e3</guid>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[sonarscanner]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Narsimha]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 07:19:24 GMT</pubDate>
            <atom:updated>2020-12-28T06:54:58.631Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello folks, In this post we’ll discuss about Sonarqube which is an open source platform developed by SonarSource for the purpose of continuous inspection of code quality to perform automatic reviews with static analysis of code to detect bugs, code smells and security vulnerabilities. The source code for the example project is available <a href="https://github.com/Narsimha9/spring-alien">here</a>.</p><p><strong>Why SonarQube?</strong></p><p>In software development life cycle Code Review system plays a crucial role.</p><p>Delivering high-quality code is the topmost responsibility of all the developers. To ensure this, developers will again and again refactor the code .The delivering must be reliable and threat free. Achieving code reviews manually is not at all a best practice. Because it is more time consuming process.</p><p>To overcome this situation and deliver high-quality code we need a tool to <strong>Automatic code review</strong> with every release.</p><p><strong>What exactly SonarQube do?</strong></p><ul><li>Sonarqube performs static code analysis with a predefined set of rules under four domains.</li><li>Sonarqube reduce the time and effort and also ensures a high-level code quality and performance for large complex applications.</li><li>It identifies the bugs, security threats, code smells and vulnerabilities before the release of an application.</li><li>Let the work flow(in case of CI/CD).</li><li>Performs Security analysis.</li><li>As of now sonarqube can generate code quality report for 27 languages.</li></ul><h3><strong>Architectural Flow:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5iOySvfOSDmtjPhqWFTaQ.gif" /></figure><p>The SonarQube Platform is made of 4 components:</p><ol><li><strong>SonarQube Server</strong> :</li></ol><ul><li>This is where the Sonarqube compute engine works and takes the input from UI.</li><li>It consists of three parts</li><li><strong>i. Web Server</strong> : for developers, managers to browse quality snapshots and configure the SonarQube instance</li><li><strong>ii.</strong> <strong>Search Server : </strong>It is based on Elasticsearch to back searches from the UI.</li><li><strong>iii.</strong> <strong>Compute Engine Server</strong> in charge of processing code analysis reports and saving them in the SonarQube Database</li></ul><p>2. <strong>SonarQube Database </strong>to store:</p><ul><li>The configuration of the SonarQube instance (security, plugins settings, etc.)</li><li>the quality snapshots of projects, views, etc.</li><li>We can also configure our local Databases to store the generated reports.</li></ul><p>3. Multiple <strong>SonarQube Plugins</strong> installed on the server, possibly including language, SCM, integration, authentication, and governance plugins</p><p>4. One or more<strong> SonarQube Scanners</strong> running on your Build / Continuous Integration Servers to analyze projects.</p><p><strong>What is Static Code Analysis:</strong></p><p>Static Code Analysis address the weaknesses in source code that might lead to bugs, vulnerabilities and security hotspots.</p><p>This analysis process can also be achieved manually, but it takes more time and the result may or may not reliable.</p><p>Static Code Analysis in Sonarqube commonly follows the rules defined in different domains like maintainability, security, reliability domains.</p><p>Static code analysis stage comes in DevOps before the release of a software version, so that the developers can know the in early if there are any threats in the code.</p><ul><li>Static code analysis is very fast and it does automated reviews for developers.</li><li>Testing may or may not cover every possible execution path whereas Static code analyzer can go in depth an covers all parts of the code.</li><li>Manual code review system is prone to errors but a static code analyzer gives a high-level quality code without any threats and errors.</li></ul><p><strong>Rules in Sonarqube:</strong></p><p>Rule: A Rule is a coding standard or practice which should be followed. Not complying with coding rules leads to Bugs, Vulnerabilities, Code smells and Security Threats.</p><p>Rules in sonarqube are categorized into three based on there respective domains.</p><ol><li>Reliability Domain(Bugs):</li></ol><ul><li>A Bug is an issue that represents something wrong in the code. If this hasn’t broken yet, it will and probably at the worst possible moment.</li><li>It is actually a coding error.</li><li>It will be caused by incorrect or erroneous logic.</li><li>A problem is said to be a buggy when it contains large no.of bugs.</li><li><strong>Examples:</strong></li><li>Arithmetic &amp; Exception handling cases,Division by zero, Arithmetic overflow or Underflow.</li><li>Infinite loop and infinite recursion</li><li>Deadlocks, Starvation, Race Condition</li></ul><p>2. Maintainability Domain(Code Smells):</p><ul><li>Code smells are certain structures in the code that indicate the violation of fundamental design principles and negatively impact the design quality.</li><li>Code smells are usually not bugs; They aren’t technically incorrect and don’t prevent the program from functioning. Instead, they indicate the weakness in the design that may slow down the development or increase the risk of bugs or failures in the future.</li><li>Bad code smells can be indicator of factors that contribute to Technical Debt.</li><li><strong>Technical Debt: </strong>The estimated time it will take to fix all the code smells. To avoid this code should be refactored.</li><li><strong>Examples:</strong></li><li>Duplicated code, Defining large classes, lazy classes(which does too little)</li><li>Method level: Too many parameters, long method, Excessive return of data.</li><li>Contrived Complexity: Forced usage of over complicated design patterns where simpler would suffice.</li><li>Shotgun Surgery: A single change needs to be applied to multiple classes at the same time.</li></ul><p>3. Security Domain(Vulnerabilities &amp; Security Hotspots):</p><ul><li>Vulnerability: A security related issue which represents a backdoor for attackers.</li><li>Vulnerabilities are points in the code which are open to attack.</li><li>Security Hotspot: It is a security sensitive pieces of code that need to be manually reviewed. Upon review, you’ll either find that there is no threat or there exists a vulnerable code which needs to be fixed.</li><li>A vulnerability rule highlights the security threats only when it has a high level of confidence.</li><li>Where as a Hotspot rule guides secure code reviews by showing code where those issues might lurk, even if it could not detect any vulnerability.</li><li>The main goal of security Hotspot is to help focus the efforts of the security auditors who manually review the application source code.</li><li>The second goal is to educate the developers and increase their security awareness.</li></ul><p><strong>Prerequisites:</strong></p><ol><li>openjdk 11</li></ol><ul><li>The only prerequisite for running SonarQube is to have Java (Oracle JRE 11 or OpenJDK 11) installed on your machine.</li></ul><p>2. SonarQube</p><ul><li>Download and install the latest version of sonarqube <a href="https://www.sonarqube.org/downloads/">here</a>. There are a total of four editions available. Each edition provides differenet kind of features. Out of all community edition is available for free.</li></ul><p>3. SonarScanner</p><ul><li>SonarScanner is the one which does the actual process of scanning the projects and generate the reports. Download the sonarscanner from <a href="https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/">here</a>.</li><li>There are several kinds SonarScanners available for different build systems like Sonarscanners for Maven, MSBuild, Gradle, Ant, Azure Devops, Jenkins.</li><li>If our project is not specific to any of this build system., we can go ahead with common SonarScanner.</li></ul><p><strong>Adding Paths to Environmental Variables:</strong></p><ul><li>We need to add the paths of SonarQube platform and SonarScanner to our system/user Environment Variables in order to access the batch files or exe files from anywhere through terminal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*cZg2ul0UcUqkPfXWWzPikg.png" /></figure><ul><li>Inside SonarQube\bin folder , nested folders are available for different OS, choose accordingly and set the path.</li></ul><p><strong>Sonarqube Quality Gate:</strong></p><ul><li>Sonarqube Quality Gate is defined as a set of threshold measures set on our projects like Security Rating, Code Coverage, Maintainability Rating , Reliability Rating etc..</li><li>Using Quality Gates is the best approach to ensure that the coding standards are met in all of our projects.</li><li>When SonarQube runs it will check if the code meets all the quality thresholds which we have set in a Quality Gate and is applied to our project, else it will fail the Quality Gate and will not allow you to check in code to source control.</li><li>This is a very powerful feature since it enforces code quality in your projects and gives reviews to the Developers during the CI/CD process. Based on the Quality Gate output CI/CD process will decide to Abort the all operations or continue to execute. Want to know how this happens?, Checkout my ci/cd article <a href="https://medium.com/@narsimhulu.464/ci-cd-pipeline-with-jenkins-and-k8s-part-1-10c4d603c4c5">here</a>.</li><li>The output of the Quality Gate is Passed or Failed.</li></ul><p><strong>Code Coverage:</strong></p><ul><li>It is a metric used to check the quality of testcases. Basically it represents the percentage of production code that has been tested successfully.</li><li>There are different plugins for each language to generate code coverage report.</li><li>Example : Jacoco (for java, maven, gradle)</li></ul><p>Example Project:</p><ul><li>Here we have an example project to understood about how the SonarQube platform will generate the code quality report.</li><li>To achieve this, we need to write a properties file called “sonar-project.properties”</li><li>sonar-project.properties:</li></ul><pre>sonar.projectKey=demoapp<br>sonar.projectName= ProjectName<br>sonar.projectVersion=1.0<br>sonar.sources=.<br>sonar.sourceEncoding=UTF-8</pre><pre>sonar.host.url=http://localhost:9000<br>sonar.tests=src/test/<br>sonar.coverage.jacoco.xmlReportPaths=target/jacoco/test/jacoco.xml,target/jacoco/integrationTest/jacoco.xml</pre><pre>sonar.java.codeCoveragePlugin=jacoco</pre><pre>sonar.junit.reportPaths=target/test-results/test,target/test-results/integrationTest</pre><pre>sonar.testExecutionReportPaths=target/test-results/jest/TESTS-results-sonar.xml</pre><pre>sonar.exclusions=src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.js, target/classes/static/**/*.*</pre><ul><li>Let’s Understand the file,</li><li><strong>sonar.projectKey</strong> refers to the project key</li><li><strong>sonar.projectName</strong> the name of our project which will be displayed in the sonarqube dashboard.</li><li><strong>sonar.projectVersion</strong> is to identify the release version of the project.</li><li><strong>sonar.sources </strong>is to tell the SonarScanner about which files it should scan and generate the report. path “.” represent the current working directory.</li><li><strong>sonar.sourceEncoding</strong> is for mentioning Encoding which is to be UTF-8.</li><li>These five properties are mandatory for any project.</li><li>Remaining all optional and based on your project.</li><li><strong>sonar.host.url</strong> is by default works on 9000 port , it is where the generated report will be represented.</li><li>sonar.tests → To mention the place where we wrote the testcases foru our project.</li><li>sonar.coverage.jacoco → To generate the code coverage report.</li><li>sonar.java.codeCoveragePlugin → code coverage generating plugin name.</li><li>sonar.junit.reportPaths &amp; testExecutionReportPaths → Test Results paths</li><li>We may often required to exclude some files which are not part of code quality , sonar.exclusions property is useful to exclude those files.</li></ul><p>Report Generation:</p><ul><li>Start the Sonarqube by hitting <strong>StartSonar</strong> batch file from terminal. Just type in “StartSonar” to start it. Then sonarqube will start on it’s default port 9100. Go to browser and enter “localhost:9100” to view the dashboard.</li><li>open the terminal inside the project folder where the sonar-project.properties files of that project is placed.</li><li>Type in the command “sonar-scanner” to scan the project using the sonar-project file configuration details.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmQxqpeoRE0Tv-Y47anzug.png" /></figure><ul><li>Here I am taking a sample spring-boot project and generating the report for it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RT9U6zyrrcxlrNTq1AjSsw.png" /></figure><ul><li>After it’s scanning , if it gives the result as Execution success, then it means that the report is successfully, else it means that there is something problem in your code or in configuration file(sonar-project.props)</li><li>Go to the dashboard now and see the results of the generated report.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVox-fnoBVAFbnrUt_ZPCQ.png" /><figcaption>SonarQube Dashboard</figcaption></figure><ul><li>In the Dashboard we can observer that 3 project have been passed the quality gate and is indicated with the status “passed”. One project hasn’t been qualified the quality gate since, it didn’t met threshold measures set by me.</li><li>We can also observe that it showing the No.of bugs, Code smells,Duplications %, Hotspots etc… It also showing the Ratings for each domain there, to understand this look at the left side of the image also. Here, Code Coverage is 0.0% since I didn’t wrote test cases for my project.</li><li>Click on your project to check where the issues have generated. It will also shows us the<strong> Debt, </strong>which is the expexted time to resolve thise issues.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LACu5NrcNj-tmePqKJKqQ.png" /></figure><ul><li>Here we can see the issues for overall code as well as for new code. If we go to down we can observer an activity chart of all versions of our project.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*uumKW4XX3esHhIbrAT_qQA.png" /></figure><ul><li>To findout the issues and fix them click on any issue like bug or vulnerabilities. We’ll be redirected to a page where all the issues will be mentioned and it also provides the suggestions to fix them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OABJAmK4fdPrlPgrYMbZWA.png" /></figure><ul><li>This report will be generated based on the rules defined inside a Quality Profile. Each Quality profile consists of number of rules for the respective language.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efXZ6yg2jqt3uRj4_dL_6g.png" /><figcaption>Quality Profiles</figcaption></figure><p>Setting Up a New SonarQube Quality Gate:</p><ul><li>By default sonarqube provides a default Quality Gate called as Sonar way and is applied to all the projects. We can create new one and set to desired projects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uZnQdbcTuhJVv6b6-9sug.png" /><figcaption>SonarQube default Quality Gate with Threshold measures for each metrics</figcaption></figure><ul><li>In practical world, there quality gate criteria will defer so that we need to setup new one according to the threshold measures for the generated metrics.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EB02TqKgjyuN6_AC9o63nQ.png" /><figcaption>Spring-Sonar-Jenkins Quality Gate setup</figcaption></figure><ul><li>Here, we have setup a new quality gate on Overall code and on New code by adding conditions on metrics.</li><li>Whenever the sonar-scanner runs the project, the mentioned Quality gate will be passed onto the project to get the Status of the Quality gate.</li></ul><p>That’s it about the Sonarqube setup and execution guys, we can also write our own rules for our projects and can be embedded into our personal sonarqube or can also be released onto community. We’ll discuss about this concept in the next article.</p><p>For any queries on this article do comment here or reach my out at <strong>narsimhulu.464@gmail.com </strong>and at LinkedIn <strong>B Narsimha</strong>.</p><p><strong>Thank You!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eecb6fe27e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD Pipeline with Jenkins and K8s(Part 2)]]></title>
            <link>https://narsimhulu-464.medium.com/ci-cd-pipeline-with-jenkins-and-k8s-part-2-8aaeae023317?source=rss-395aec026d0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aaeae023317</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Narsimha]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 07:33:49 GMT</pubDate>
            <atom:updated>2020-07-29T03:50:59.290Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, This post is the continuation part for CI/CD pipeline with Jenkins and K8s(Part). If you haven’t looked into the Part 1, have a look at <a href="https://medium.com/@narsimhulu.464/ci-cd-pipeline-with-jenkins-and-k8s-part-1-10c4d603c4c5">here</a>. In this post we’ll discuss about the Continuous Deployment which was left out in Part 1. The source code for these examples can be found <a href="https://github.com/Narsimha9/spring-alien">here</a>.</p><p>Before diving into the Continuous Deployment example , Let us know about Continuous Deployment(CD).</p><blockquote><strong>Continuous Deployment (CD):</strong></blockquote><blockquote>Continuous Deployment (CD) is a software release process that uses automated testing to validate if changes to a codebase are correct and stable for immediate autonomous deployment to a production environment.</blockquote><p>Continuous Deployment is the final phase in the software cycle. The traditional process of Deployment follows moving code between machines and checking if it works fine or causing errors or is a resource heavy process.</p><p>By overcoming this problem CD tools can automate this entire deployment process, which allow engineering organizations to focus on core business needs instead of infrastructure overhead.</p><h3><strong>Continuous Deployment Procedure :</strong></h3><p>In the Previous part we’ve created a docker image of our project and pushed it into our docker hub registry.</p><p>To Deploy this image into Kubernetes and run the application from there we need to write two more files, called as deployment.yml and service.yml.</p><p>Kubernetes doesn’t run containers (contains images)directly, instead it wraps one or more containers into a higher-level structure called a pod. Deployment.yml file is to create a pod in kubernetes and deploy the obtained image from docker hub registry to that pod. A pod may contain serveral containers but all of those will share the same containers and network. This makes containers to easily communicate each other inside a pod.</p><p>service.yml provides an abstract way to expose an application running on a set of pods as a network service.</p><p>Let’s explore<strong> deployment.yml</strong> now</p><pre>apiVersion: apps/v1                       <br>kind: Deployment                       <br>metadata:                         <br>  labels:                           <br>    app: demospringalien  <br>  name: demospringalien<br>spec:                         <br>  replicas: 2                 <br>  selector:                           <br>    matchLabels:               <br>      app: demospringalien <br>  template:                         <br>    metadata:                   <br>      labels:                 <br>        app: demospringalien  <br>    spec:        <br>      containers:  <br>      - image: &lt;Your dockerhub username&gt;/springali:11<br>      name: demospringalien</pre><ol><li>apiVersion: it the Api version with which we are creating this Deployment.</li></ol><p>2. kind : To mention what kind of object we’re creating, here it is Deployment object.</p><p>3. metadata: The details provided here will be used to recognize this object. The name of the object will be declared here with key → <em>metadata.name</em></p><p>4. spec property tells about the specifications of the object.</p><ul><li>spec.replicas → The no.of instances of this object</li><li>spec.selector → Using selector client/user can identify a set of objects.</li><li>spec.selector.matchLables → matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is &quot;key&quot;, the operator is &quot;In&quot;.</li><li>spec.template.metadata.labels.app → is the name of the pod.</li><li>spec.template.spec.containers → it is an array which holds the details of the containers like image name.</li><li>spec.template.spec.containers[0].name → holds the container name , this container get the image “simhalp9/springali:11”.</li></ul><p><strong>Service.yml :</strong></p><pre>apiVersion: v1                       <br>kind: Service      <br>metadata:                        <br>  labels:                           <br>    app: demospringalien                        <br>  name: demospringalien               <br>spec:                   <br>  type: NodePort            <br>  ports:         <br>  - port: 8080  <br>    protocol: TCP<br>    targetPort: 8080       <br>    nodePort: 31235  <br>  selector:     <br>    app: demospringalien</pre><ul><li>This object is of kind “Service”, which provides an abstract way to expose an application running on a set of pods as a network service.</li><li>metadata → is tells the name of this object.</li><li>spec.type → exposes a service externally to the cluster by means of the target nodes IP address and the NodePort. NodePort is the default setting if the port field is not specified.</li><li>Inside spec.ports → port : The port in which the original application is running</li><li>targetPort and application port needs to be same. since, the image is running on the application port itself.</li><li>nodePort : Basically kubernetes assigns a randomly generated port number starting from 30000, here we are specifying manually to avoid it.</li></ul><p>We can write both deployment.yml and service.yml in a same file by writing a line like “_ _ _” after deployment.yml code . These two files will be deployed into a default namespace if we don’t mention any other namespace.</p><p>Now we need to deploy these two files into Kubernetes. Basically we can deploy these two files from cmd like below and can run our application in which nodePort our application is running.</p><pre>kubectl apply -f deployment.yml<br>kubectl apply -f service.yml</pre><p>But our aim is to deploy these onCommit of code and after continuous deployment. Therefore we need to include these commands in the Jenkinsfile which we wrote in the previous post.</p><p>These two steps are included in a stage named as “Deploying into K8s”</p><pre>stage(&#39;Deploying into k8s&#39;){     <br>   steps{               <br>        bat &#39;kubectl apply -f deployment.yml&#39;   <br>        bat &#39;kubectl apply -f service.yml&#39;                            <br>         }                            <br>    }</pre><p>Now start minikube (for <strong>windows User</strong>) using the command</p><pre>minikube start </pre><p>To see the output of our deployment , type the command</p><pre>minikube service servicename</pre><p>Start Kubernetes (<strong>other OS users</strong>)</p><p>Our ci/cd pipeline is now ready to test.</p><p>Make any change to application code, it starts executing from project building stage and after “pushing image to docker hub ” stage , continuous deployment stage will get started and the image will be pulled onto Kubernetes and deployed into K8s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAQDJ_cphd2jZ4TFimZzyQ.png" /><figcaption>Result of ci/cd pipeline</figcaption></figure><p>You can observe the created deployments like this. If the Deployment color is green, it means that your deployment and pods get created successfully and are working. If the color is Orange, then there is an error occured while deployment. Look into the pod events to find out the error. Most of the time it may be failed due to the failed process of image pulling from docker hub. So, be careful while mentioning the docker image name in deployment.yml.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nsrPY9TOAUJtRjWrKAx3g.jpeg" /><figcaption>Deployments</figcaption></figure><p>Look at the Deployments ,created pods and their configurations ..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9DyK4W6v-O_-BdU1C8UwQ.jpeg" /></figure><p>If you want to check its configuration, click it the you can see the yml configuration there.</p><p>Have a look at services also which we created to expose the application port to use and get accessed by outside world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dLy-OaMnwqOYcy3CZGuvg.jpeg" /></figure><p>We can check our application running on port 31235, which we gave as nodePort in deployment.yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pxKce1edG9dqHELX9co8g.jpeg" /><figcaption>Ouput of post request of the project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRnl8kjHWQDCfOb2xuzhxQ.jpeg" /><figcaption>output of Get request</figcaption></figure><p>Wrapping up,</p><p>We’ve created an image in part 1 after successful build and testing of the project, pushed the image onto docker hub. Now we deployed the image into Kubernetes by fetching the image from docker hub..</p><p>That’s the end of our series, CI/CD pipeline with Jenkins and Kubernetes.</p><p>That’s it guys, I hope you’ll understood well. For any queries on any of my articles feel free to reach me out at <strong>narsimhulu.464@gmail.com </strong>and at LinkedIn<strong> B Narsimha.</strong></p><p><strong>Thank You!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aaeae023317" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD Pipeline with Jenkins and Kubernetes(Part 1)]]></title>
            <link>https://narsimhulu-464.medium.com/ci-cd-pipeline-with-jenkins-and-k8s-part-1-10c4d603c4c5?source=rss-395aec026d0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c4d603c4c5</guid>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Narsimha]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 10:24:32 GMT</pubDate>
            <atom:updated>2023-08-04T00:30:15.950Z</atom:updated>
            <content:encoded><![CDATA[<h3>CI/CD Pipeline with Jenkins and K8s(Part 1)</h3><p>Hello folks, In this post I am going to explain about the ci/cd pipeline with Jenkins as automation server , Git as version control system and Kubernetes for the production.The source code example is available <a href="https://github.com/Narsimha9/spring-alien">here</a>. This a series in which we’ll discuss the actual ci/cd pipeline along with the other concepts which can be invoked in the process of continuous integration and continuous deployment like SonarQube which is a code quality testing tool.</p><p>Before Going to the example let us know the basic concepts like DevOps, ci/cd , need of ci/cd in real time and the architectural flow of ci/cd.</p><h3><strong>What is DevOps ?</strong></h3><p><strong>DevOps</strong> is a set of practices that combines software development (<em>Dev</em>) and <a href="https://en.wikipedia.org/wiki/IT_operations">IT operations</a> (<em>Ops</em>). It aims to shorten the systems development life cycle and provide <a href="https://en.wikipedia.org/wiki/Continuous_delivery">continuous delivery</a> with high <a href="https://en.wikipedia.org/wiki/Software_quality">software quality</a>. DevOps is complementary with <a href="https://en.wikipedia.org/wiki/Agile_software_development">Agile software development</a>; several DevOps aspects came from Agile methodology.</p><p>The set of DevOps tools increases an organization’s ability to deliver applications and services at high velocity: evolving and improving products at a faster pace than organizations using traditional software development and infrastructure management processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzrBwik3y2IK4gyw7HQqrg.png" /></figure><p>As you can see in the above image, DevOps is the combination of several stages , at each stage there are different tools that fulfills the stage functionalities.</p><h3><strong>What is CI/CD ?</strong></h3><p>Ci/Cd generally refers to the combined practices of continuous integration and either continuous delivery or continuous deployment. Basically ci/cd bridges the gaps between development and operational activities and teams by enforcing automation in building, testing and deployment of applications.</p><h3><strong>Challenges Before CI/CD ?</strong></h3><ol><li>Automation of build and testing process.</li><li>Fast delivery</li><li>Automation of application deployment</li><li>Fast feedback loop</li><li>Avoids the process Integration of all stages which is a hell</li><li>Improves code quality and test ability</li></ol><p>From the above challenges we can understand the need and importance of ci/cd in real time.</p><h3><strong>Architectural flow of CI/CD :</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*CweH91ah_rIhhQ4WSFODYg.png" /></figure><p>Basically, the process of ci/cd starts with the code committing stage in any version control system like Git. The committed code will then enters CI pipeline process, here we can include the stages as per the requirement.Generally this process includes Build stage, testing stage, Docker image generation, pushing the image into docker hub. If we wants to include the sonarqube for the purpose of code quality , we can also include it in ci process.</p><p>In the Cd process, the docker image will be pulled by the docker and will be deployed into the Kubernetes.</p><h3><strong>prerequisites:</strong></h3><ol><li>Jenkins</li></ol><p>Jenkins is a free and open source automation server. It helps automate the parts of software development related to building, testing, and deploying, facilitating continuous integration and continuous delivery.If you are not yet installed Jenkins, do install from <a href="https://www.jenkins.io/">here</a>.</p><p>2. Docker</p><p>Docker is a set of platform as a service(Paas) products that use OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels.</p><p>You can use Docker Desktop (If you are using windows then windows pro version only supports this and MAC OS will support docker desktop). For windows OS other than pro version we have an option with Docker Tool Box which provides the Virtual Box,Docker and Kitematic. We can setup the docker in virtual box and can use it. Install Docker Desktop from <a href="https://www.docker.com/products/docker-desktop">here </a>and Docker Tool Box<a href="https://docs.docker.com/toolbox/toolbox_install_windows/"> here</a>. For downloading docker in Linux and Ubuntu machines follow <a href="https://docs.docker.com/engine/install/ubuntu/">this</a>.</p><p>3. Version Control</p><p>Version control helps a software team manage changes to source code over time. Version control software keeps track of every modification to the code in a special kind of database. If a mistake is made, developers can turn back the clock and compare earlier versions of the code to help fix the mistake while minimizing disruption to all team members. My suggestion is to use<a href="https://www.atlassian.com/git/tutorials/install-git"> Git </a>as version control system.</p><p>Examples: Git, Bit bucket</p><p>4. Kubernetes</p><p>Kubernetes is an open-source container-orchestration system for automating computer application deployment, scaling, and management. Docker Desktop includes a standalone Kubernetes server and client, as well as Docker CLI integration. The Kubernetes server runs locally within your Docker instance, is not configurable, and is a single-node cluster. If you are using docker tool box then install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">kubectl</a> and <a href="https://kubernetes.io/docs/tasks/tools/install-minikube/">minikube. </a>After installation set the paths of both inside your system’s environment variables.</p><p>5. Docker Hub:</p><p><a href="https://hub.docker.com/">Docker Hub</a> is also like a version control system where we will store the docker images inside a registry. It stores all the versions of our images. Keep an account in the docker hub with valid credentials which will be more useful in the process of CI.</p><p>6. SonarQube:</p><p>SonarQube is an open-source platform developed by SonarSource for continuous inspection of code quality to perform automatic reviews with static analysis of code to detect bugs, code smells, and security vulnerabilities on 20+ programming languages. Since, this is optional stage in CI/CD , if you want to know about SonarQube and SonarQube Quality Gate, have a look at <a href="https://medium.com/@narsimhulu.464/sonarqube-for-continuous-codequality-testing-3eecb6fe27e3">here</a>. In the given link I gave a full fledged clarity about them.</p><p>We can install and use the community version of the SonarQube for free <a href="https://www.sonarqube.org/">here</a>.</p><p>7. ngrok:</p><p><strong>ngrok</strong> is a cross-platform application that enables developers to expose a local development server to the Internet with minimal effort. The software makes your locally-hosted web server appear to be hosted on a subdomain of <strong>ngrok</strong>.com, meaning that no public IP or domain name on the local machine is needed. Download the ngrok <a href="https://ngrok.com/pro">here</a>.</p><h3><strong>CI/CD Procedure :</strong></h3><p>Let’s now dive into the Steps to Ci/Cd</p><ol><li>Jenkins setup:</li></ol><p>After successful installation of Jenkins do register and login to the Jenkins dashboard with the help of a master key generated inside the directory created by Jenkins. The dashboard of Jenkins will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEJYkenAxYMQQ6Oc-OtrLQ.png" /><figcaption>Jenkins Dashboard</figcaption></figure><p>Explore the operations available in Jenkins before creating a pipeline to know the basic idea on Jenkins Features.</p><ul><li>Install the required plugins for ci/cd pipeline in the manage Jenkins section. The required plugins are, git,docker,blue ocean,maven (for spring boot),pipeline,build pipeline,delivery pipeline and sonarqube. Install the other plugins based on the framework you’ve chosen like node, java etc..</li></ul><pre>Manage Jenkins -&gt; Manage plugins -&gt; install the plugins</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDQ-3sKU9d5nPUy87_G6IA.png" /></figure><ul><li>Add the local paths of Git, shell (available inside Git folder),Maven, Docker. You can also choose the options like choose automatically , but sometimes it won’t work well and you’ll face problems.</li></ul><pre>Manage Jenkins -&gt; Global Tool Configuration -&gt; Add local git path   until git.exe, Maven path </pre><pre>Manage Jenkins -&gt; Global Tool Configuration -&gt; Add local SonarQube scanner and do remember the name given to this path in Jenkins.</pre><p>Add Docker paths like below. You’ll find out those inside your environment variables.</p><pre>Manage Jenkins -&gt; Configure System -&gt;Global properties</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtIa07zMIM0diX8XaQTWvg.png" /></figure><ul><li>Add Sonarqube and shell paths inside Configure system only.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-szfLa8t8rSlZmgzIMpmYA.png" /><figcaption>Sonar Path</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZExNoe6rf-QV8gibouilQ.png" /><figcaption>Shell path</figcaption></figure><ul><li>Set the docker details and kube config details for using Kubernetes in environment variables. Inside user directory .kube folder gets created.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*QtkZS11HUU-wA3yI3dyhIQ.png" /></figure><ul><li>Adding Docker Hub and Git credentials:</li></ul><pre> Credentials -&gt; system -&gt; Global credentials -&gt; Add credentials<br> (Give Username and    password of your docker hub &amp; git)</pre><p>We are done with setup of Jenkins and Docker.</p><p>Let’s test all of them to make sure that they are working fine with the help of a free style project in Jenkins.</p><ul><li>Click on New Item and choose a free style project with a name and observe the options available in the next page. Go to build step and choose Execute shell to test whether shell is working or not. Type in echo “test” in the text area,save and apply. Run this project using Build Now option and check the result. If it gives the result as “SUCCESS” then shell is working fine.</li><li>Now Choose Source Code Management as Git, Enter the Repository URL,choose the branches to build. Goto Build step and write the command “docker build”. This build will takes the code from the git hub repo and build the image based on the Dockerfile provided in the git repo.</li><li>For checking this functionality i’ve provided a Repository on github with java Helloworld code <a href="https://github.com/Narsimha9/Hello-world">here</a>. Feel free to fork it or use it directly.The result after building this step should be “Success”, Otherwise it means that you haven’t properly set the docker path or install the plugins in the Jenkins.</li><li>In the same way you can also test the maven or another shell commands.</li></ul><p><strong>2. Creating a CI/CD pipeline in Jenkins</strong></p><p>Create a New item by choosing pipeline project and give the same as you desired. In the Build triggers sections check the option “GitHub hook trigger for GITScm polling”, this will be used to build the entire project again when the user commits code on Git (Version control).</p><ul><li>In the pipeline section choose the option Pipeline script from SCM.Choose SCM as Git, enter the git url, Add credentials (previously set)name of the repo (if it is private),select Branches to build and script path as Jenkinsfile because inside the Git repo my Jenkinsfile is on root path itself.If it is not like that give the directory path and save it.</li><li>In this example I am taking a spring boot application. For a node application example check <a href="https://github.com/Narsimha9/simple-noje">here</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-y_uHnJ3sON45uojimzZg.png" /><figcaption>SCM setup</figcaption></figure><p><strong>3. Jenkinsfile Explanation</strong></p><p>We’ll look into the CI part of Jenkinsfile Now</p><pre>pipeline{<br>  environment {<br>    scannerHome = tool &#39;SonarQubeScanner&#39;<br>    registry = &quot;simhalp9/springali&quot;<br>    registryCredential = &#39;dockerhub&#39;<br>    dockerImage = &#39;&#39;<br>  }<br>  agent any<br>    stages {<br>        stage(&#39;clean&#39;) {<br>            steps {<br>                bat &#39;mvn clean&#39;<br>            }<br>        }<br>        stage(&#39;build and test&#39;) {<br>            steps {<br>                bat &#39;mvn package&#39;<br>            }<br>        }</pre><pre>        stage(&#39;Sonarqube&#39;) {<br> <br>            steps {<br>              script {<br>                  withSonarQubeEnv(&#39;sonarqube&#39;) {<br>                  bat &quot;${scannerHome}/bin/sonar-scanner&quot;<br>                    }<br>                  }<br>               }<br>          }<br>        stage(&quot;SonarQube Quality Gate&quot;){<br>          steps {<br>            script {<br>               timeout(time: 5, unit: &#39;MINUTES&#39;) { <br>               def qualitygate = waitForQualityGate() <br>               if (qualitygate.status != &#39;OK&#39;) {<br>               abortPipeline:true<br>               error &quot;Pipeline aborted due to quality gate failure:   ${qualitygate.status}&quot;<br>                 }<br>               else {<br>               echo &quot;Quality gate passed&quot;<br>                  }<br>              }<br>           }<br>         }<br>       }<br>        stage(&#39;Building image&#39;) {<br>            steps{<br>                script {<br>                  dockerImage = docker.build registry + &quot;:$BUILD_NUMBER&quot;<br>                }<br>             }<br>          }<br>          stage(&#39;Push Image&#39;) {<br>              steps{<br>                  script {<br>                      docker.withRegistry( &#39;&#39;, registryCredential )    {<br>                        dockerImage.push()<br>                      }<br>                  }<br>              }<br>            }<br>      <br>  }<br>}</pre><p>Basically in a Jenkinsfile we’ll write the pipeline stages that are to be executed in an sequential manner. Let’s explore the each ans every stage now.</p><ul><li>Environment setup</li></ul><pre>environment {<br>    scannerHome = tool &#39;SonarQubeScanner&#39;<br>    registry = &quot;simhalp9/springali&quot;<br>    registryCredential = &#39;dockerhub&#39;<br>    dockerImage = &#39;&#39;<br>  }</pre><ul><li>Here, we are getting the details of the sonarQubeScanner into scannerHome which we are set in Jenkins with the name “SonarQubeScanner”, docker hub registry name and docker hub credentials to access the registry and store the docker images.</li><li>SonarQube quality gate is provided to get the quality gate result, if it is failed then the remaining stages will be aborted.</li><li>Stage “Build”</li></ul><pre>stage(&#39;clean&#39;) {<br>            steps {<br>                bat &#39;mvn clean&#39;<br>            }<br>        }</pre><pre>stage(&#39;build and test&#39;) {<br>            steps {<br>                bat &#39;mvn package&#39;<br>            }<br>        }</pre><ul><li>Here, we are building the spring boot project with bat command , you can also run this commands using shell like, sh “mvn package”</li><li>Stage “SonaQube”</li></ul><pre>stage(&#39;Sonarqube&#39;) {<br> <br>            steps {<br>              script {<br>                  withSonarQubeEnv(&#39;sonarqube&#39;) {<br>                  bat &quot;${scannerHome}/bin/sonar-scanner&quot;<br>                    }<br>                  }<br>               }<br>          }<br>       stage(&quot;SonarQube Quality Gate&quot;){<br>          steps {<br>            script {<br>               timeout(time: 5, unit: &#39;MINUTES&#39;) { <br>               def qualitygate = waitForQualityGate() <br>               if (qualitygate.status != &#39;OK&#39;) {<br>               abortPipeline:true<br>               error &quot;Pipeline aborted due to quality gate failure:   ${qualitygate.status}&quot;<br>                 }<br>               else {<br>               echo &quot;Quality gate passed&quot;<br>                  }<br>              }<br>           }<br>         }<br>       }</pre><ul><li>These two stages are optional. But If we want to have a code quality testing then it is mandatory to write this step. In this stage we are scanning the project for checking the code quality with the help of file named as “sonar-project.properties”. More Details related to sonarqube and sonarqube quality gate are available in the later articles.</li><li>After the successful execution of Sonarqube stage the results will be appeared on the sonarqube dashboard. Here you can findout the code quality metrics like bugs, vulnerabilities, security threats and code hotspots.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_q_hSQ10tTsuOGMsE7DvjQ.png" /><figcaption>Sonarqube dashboard</figcaption></figure><ul><li>Stage “Image Building”</li></ul><pre>stage(&#39;Building image&#39;) {<br>            steps{<br>                script {<br>                  dockerImage = docker.build registry +  &quot;:$BUILD_NUMBER&quot;<br>                }<br>             }<br>          }</pre><p>In this stage we are guiding the Jenkins to build an image with a version number , here “BUILD_NUMBER” of Jenkins will be used as a version number for the generated image and “registry” is the name of the docker image.</p><ul><li>Image building stage will be carried out with the help of Dockerfile which is provided in root path</li></ul><pre>FROM openjdk:8-jre-alpine        <br>WORKDIR /app    <br>COPY ./target/springJPA-0.0.1-SNAPSHOT.jar /app/                       ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;springJPA-0.0.1-SNAPSHOT.jar&quot;]</pre><ul><li>Let us look into the each step in detail</li></ul><p>1. FROM will gets the openjdk:8-jre-alpine image which is the docker image of openjdk and it is useful for spring boot and java projects</p><p>2. We are creating and making working directory as /app</p><p>3. Copying the generated jar file which will be available in targets folder of the project after building stage.</p><p>Note: target folder will not be visible to you because all the actions are happening in docker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAPH_Xsi1PXZiN7_qXZkzA.png" /><figcaption>Docker image building step in pipeline</figcaption></figure><p>4. Starting the project with command “java -jar “generated jar filename” ”</p><ul><li>Stage “Image Pushing to Docker Hub”</li></ul><pre>stage(&#39;Push Image&#39;) {<br>              steps{<br>                  script {<br>                      docker.withRegistry( &#39;&#39;, registryCredential )    {<br>                        dockerImage.push()<br>                      }<br>                  }<br>              }<br>            }</pre><p>This stage tell the Jenkins to push the generated image to the dockerhub with the dockerhub registry credentials variable “registryCredentail” which we were set before in the Jenkins credentials. This variable consists of the Jenkins docker hub credentials name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGzFYUVf_Zuc6CnREJ_xGQ.png" /><figcaption>Generated docker images of all versions in Docker Hub registry</figcaption></figure><ul><li>Now when we hit “Build Now” in Jenkins , the pipeline stages will start executing one by one. You can see the results and progress of the stages in Jenkins dashboard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pEUJrLT5W2fXQ6e7fcxwhg.png" /><figcaption>Stage view of pipeline</figcaption></figure><ul><li>If you need to have a good visualization then watch it on “Blue Ocean” which is available on Jenkins Dashboard.</li><li>We can also view the logs of each stage in Jenkins in console output option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_pWADgISy64Zjvsg6wyag.png" /><figcaption>Console output logs</figcaption></figure><p>As of now we are creating a pipeline and configuring the required details in it, Running the Jenkinsfile which contains stages of ci/cd pipeline. It is getting the repo address, building an image and pushing the generated docker image into docker hub.</p><p>Now if we run our application, it will be accessed by the local web server. To make it available as a public URL we need to set <strong>ngrok </strong>in coordination with web hooks which is available in git.</p><p><strong>Setting the web hooks with ngrok:</strong></p><ul><li>Run the executable file of ngrok then it will opens a terminals with useful commands</li><li>Execute the command “ngrok http 8080”. Here, http is the protocol we are using (we can also use tcp) and 8080 is the port where our application is running.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNK6W54N1iUEjrVIdKSeuQ.png" /><figcaption>ngrok</figcaption></figure><ul><li>We can also set this for our domain name like this →ngrok http foo.dev:80</li><li>Copy the generated forwarding address for our application portby ngrok till ngrok.io.</li><li>In your Git repo , go to settings and choose webhooks, select add webhook and paste the ngrok generated url in the payload Url place and append “/github-webhook/” to this Url. Select the events to which you want to run this Url.</li><li>Now whenever we made any changes to the code and commit the repo, then ci/cd pipeline will be executed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlsQ9KvKIaOvrCtqVQLD6Q.png" /><figcaption>Webhooks setup with ngrok</figcaption></figure><ul><li>You are all set to run your Continuous integration process now. Make any changes in the code and hit commit. Your pipeline will automatically get’s started in jenkins and you can observe the each stage visually there in the Jenkins.</li><li>If any Stage get’s failed , remaining stages will be aborted automatically.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAQDJ_cphd2jZ4TFimZzyQ.png" /><figcaption>Blue Ocean Visualization of our pipeline project</figcaption></figure><p>Wrapping up, we have installed the prerequisites, started Jenkins, installed required plugins for ci/cd, added the local paths of Git, shell, maven, Docker, Sonarqube and kubernetes to Jenkins, tested whether all are working fine in Jenkins environment with a sample Helloworld project, Created a pipeline project, Wrote a Jenkinsfile which will build and test the project, scan the project for code quality, generate a docker image based on the SonarQube quality gate, pushed the generated docker image onto docker hub, added ngrok generated forwarding address to webhooks of the repo and finally started our project ci/cd project onCommit of code.</p><p>The next part of this series ,Continuous Deployment is available <a href="https://medium.com/@narsimhulu.464/ci-cd-pipeline-with-jenkins-and-k8s-part-2-8aaeae023317">here</a> .</p><p>That’s it about Continuous Integration guys, I hope you’ll understood well.For any queries on any of my articles feel free to reach me out at <strong>narsimhulu.464@gmail.com </strong>and at LinkedIn<strong> B Narsimha</strong></p><p>Thank You!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c4d603c4c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Microservices with Go kit Using Mongodb and Mysql]]></title>
            <link>https://narsimhulu-464.medium.com/go-microservices-e6065d7b917d?source=rss-395aec026d0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6065d7b917d</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Narsimha]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 11:59:34 GMT</pubDate>
            <atom:updated>2020-08-01T05:33:34.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go Microservices with Go-kit using Mongodb and Mysql</h3><p>Hello folks,In this post I will explain about developing the Go microservices with Go kit which is a toolkit for microservices in Go. As I have faced a lot of problems while learning this concept because of not having proper references I just wanted to write this post. The source code of the examples is provided <a href="https://github.com/Narsimha9/Go-Microservices-Using-Mongodb-Mysql">here</a>.</p><p>Before Getting into the topic let us discuss about the Go kit Architecture which will be helpful while implementing the Go microservices. This architecture is also be called as clean Architecture.</p><p><strong>Go-Kit Architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*CKj8nlknAJI_8TAG9zHZMQ.png" /><figcaption>source: gokit.io</figcaption></figure><p>Basically there are three layers or components in the Go kit based application.</p><ol><li>Transport layer</li><li>Endpoint layer</li><li>Service layer</li></ol><p><strong>Transport Layer:</strong></p><p>Transport layer is useful when you are writing microservices in any language to facilitate the communication between the service to service. The transport domain is bound to concrete transports like HTTP or gRPC. Go kit supports various transports using HTTP, gRPC, NATS, AMQP and Thrift. In a world where microservices may support one or more transports, this is very powerful; you can support a legacy HTTP API and a newer RPC service, all in a single microservice.</p><p><strong>Endpoint Layer:</strong></p><p>An endpoint is like an action/handler on a controller; it’s where safety and antifragile logic lives. If you implement two transports (HTTP and gRPC), you might have two methods of sending requests to the same endpoint. Each and every service method in Go kit needs to be converted into an endpoint to make RPC style communication between clients and servers (like Request and Response).</p><p><strong>Service Layer:</strong></p><p>Services are where all of the business logic is implemented. A service usually glues together multiple endpoints. In Go kit, services are typically modeled as interfaces, and implementations of those interfaces contain the business logic. Each service method then interacts with databases with the help of Repository interface created and the methods implemented for each repository abstract method.</p><p><strong>Example Services :</strong></p><p>Basically, Go kit provides different features such as tracing with zipkin, logging middleware, metrics with prometheus monitoring tools,rate-limiting and circuit breaking (hystrix). These are essential for any microservice. Here I am discussing about logging middleware, metrics with prometheus, database interaction with Mongodb and Mysql.</p><p>We’ll explore the example service in a manner that is how the Go kit microservices follows. Please make habit of writing all the layers inside the same package to reduce the risk overthinking and making mistakes while accessing the different functions. In the below example Iam explaining a POST request “/create”, remaining CRUD operations will be available in the provided <a href="https://github.com/Narsimha9/Go-Microservices">Github repo</a>.</p><ol><li>Define the model , make sure that each field in a struct should start with a capital letter otherwise the field cannot considered by the struct.</li></ol><pre>// model.go</pre><pre>package main<br>type User struct {</pre><pre>Id         string `json:&quot;id&quot; omitempty`<br>Userid     int    `json:&quot;userid&quot; binding:&quot;required&quot;`<br>Email      string ` json:&quot;email&quot; binding:&quot;required&quot;`<br>Password   string ` json:&quot;password&quot; binding:&quot;required&quot;`<br>Phone      string ` json:&quot;phone&quot; binding:&quot;required&quot;`</pre><pre>}</pre><p>2. Declare the service interface and all the abstract methods inside it which you are going to implement in the service layer. Also write a service struct and NewService which are useful when you are interacting with the database through repository. Then implement all the service methods.</p><p>Declaration and Implementation of service methods.</p><pre>// service.go</pre><pre>package main<br>import (<br>&quot;context&quot;<br>&quot;github.com/go-kit/kit/log&quot;<br>&quot;github.com/go-kit/kit/log/level&quot;<br>&quot;github.com/gofrs/uuid&quot;</pre><pre>)</pre><pre>// service implements the User Service<br>// logger for logging middleware</pre><pre>type userservicestruct struct {<br>repository Repository<br>logger     log.Logger<br>}<br>// Service describes the User service.</pre><pre>type UserService interface {</pre><pre>CreateUser(ctx context.Context, user User) (string, error)<br>}<br>// NewService creates and returns a new User service instance</pre><pre>func NewService(rep Repository, logger log.Logger) UserService {<br>return &amp;userservicestruct{<br>repository: rep,<br>logger:     logger,</pre><pre>}<br>}<br>func (s userservicestruct) CreateUser(ctx context.Context, user User) (string, error) {</pre><pre>logger := log.With(s.logger, &quot;method&quot;, &quot;Create&quot;)<br>uuid, _ := uuid.NewV4()<br>var id = uuid.String()<br>user.Id = id<br>userDetails := User{<br>Id:         user.Id,<br>Userid:   user.Userid,<br>Email:      user.Email,<br>Password:   user.Password,<br>Phone:      user.Phone,<br>}</pre><pre>if err := s.repository.CreateUser(ctx, userDetails); err != nil {<br>level.Error(logger).Log(&quot;err&quot;, err)<br>}<br>return id, nil<br>}</pre><p>3. Declare the Handlers and routes inside main.go which is the root file for a microservice. The handlers will call Endpoints, DecodeRequests &amp; encodeResponse. Create an instance of your service with Repository and NewService. NewService returns the address of repository instance.</p><pre>// main.go</pre><pre>package main</pre><pre>import (</pre><pre>&quot;fmt&quot;&quot;net/http&quot;<br>&quot;os&quot;<br>&quot;github.com/gorilla/mux&quot;<br>&quot;github.com/go-kit/kit/log&quot;<br>httptransport &quot;github.com/go-kit/kit/transport/http&quot;<br>&quot;github.com/go-kit/kit/log/level&quot;<br>)<br>func main() {<br>r := mux.NewRouter()<br>dbmname := &quot;mysql&quot; // change to mongo for mongodb<br>var svc UserService<br>//For the service implementation with mongodb<br>{</pre><pre>if dbmname == &quot;mongo&quot; {<br>db := GetMongoDB()<br>repository, err := NewRepo(db, logger)<br>if err != nil {<br>level.Error(logger).Log(&quot;exit&quot;, err)<br>os.Exit(-1)<br>}<br>svc = NewService(repository, logger)<br>} else {<br>// for the service implementaion with Mysql<br>sqldb := GetSqlDB()<br>repository, err := NewSqlRepo(sqldb, logger)<br>if err != nil {<br>level.Error(logger).Log(&quot;exit&quot;, err)<br>os.Exit(-1)<br>}<br>svc = NewService(repository, logger)<br>}<br>}</pre><pre>CreateUserHandler := httptransport.NewServer(<br>makeCreateUserEndpoint(svc),<br>decodeCreateUserRequest,<br>encodeResponse,<br>)<br></pre><pre>http.Handle(&quot;/&quot;, r)<br>http.Handle(&quot;/create&quot;, CreateUserHandler)<br>logger.Log(&quot;msg&quot;, &quot;HTTP&quot;, &quot;addr&quot;, &quot;:8000&quot;)<br>logger.Log(&quot;err&quot;, http.ListenAndServe(&quot;:8000&quot;, nil))<br>}</pre><p>4. Write the Adapters which will convert the service methods into endpoints to make RPC style communication with HTTP transport.</p><pre>// transport.go starts here<br>package main</pre><pre>import (<br>&quot;context&quot;<br>&quot;encoding/json&quot;<br>&quot;fmt&quot;<br>&quot;net/http&quot;<br>&quot;strconv&quot;<br>&quot;github.com/go-kit/kit/endpoint&quot;<br>&quot;github.com/gorilla/mux&quot;<br>)<br>// Endpoint for the User service.</pre><pre>func makeCreateUserEndpoint(s UserService) endpoint.Endpoint {<br>fmt.Println(&quot;make createUser endpoint called&quot;)<br>return func(ctx context.Context, request interface{}) (interface{}, error) {<br>req := request.(CreateUserRequest)<br>id, err := s.CreateUser(ctx, req.user)<br>return CreateUserResponse{Id: id, Err: err}, nil<br>}<br>}</pre><p>5. Write DecodeRequests to decode the incoming request into the json format and encodeResponse to send the response in json format. Sometimes the incoming request data may be in the form XML, HTML or JSON etc… To understand the incoming data Go-kit architecture uses DecodeRequests and to send the response in the same format, it uses encodeResponse.</p><pre>// transport.go continues here </pre><pre>func decodeCreateUserRequest(_ context.Context, r *http.Request) (interface{}, error) {<br>fmt.Println(&quot;decodeCreateUserRequest called&quot;)<br>var req CreateUserRequest<br>if err := json.NewDecoder(r.Body).Decode(&amp;req.user); err != nil {<br>return nil, err<br>}<br>return req, nil<br>}<br>//  encodes the output</pre><pre>func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {</pre><pre>fmt.Println(&quot;Encode Response called&quot;)<br>w.Header().Set(&quot;Content-Type&quot;, &quot;application/json; charset=utf-8&quot;)<br>return json.NewEncoder(w).Encode(response)<br>}</pre><pre>type (</pre><pre>CreateUserRequest struct {<br>user User<br>}</pre><pre>CreateUserResponse struct {<br>Id  string `json:&quot;id&quot;`<br>Err error<br>}<br>)</pre><ul><li>Structs are necessary for each service method to receive the request and pass it on to the method implementation through end points and to send the response.</li></ul><p>6. Now you are ready with basic setup of Go kit microservice. Let us now add database to this service.</p><pre>//dbconnection.go</pre><pre>package main</pre><pre>import (<br>&quot;database/sql&quot;<br>&quot;fmt&quot;<br>&quot;os&quot;<br>_ &quot;github.com/go-sql-driver/mysql&quot;<br>mgo &quot;gopkg.in/mgo.v2&quot;<br>)</pre><pre>// for mongodb</pre><pre>var db *mgo.Database</pre><pre>func GetMongoDB() *mgo.Database {</pre><pre>host := &quot;MONGO_HOST&quot;<br>dbName := &quot;Go_mic_service&quot;<br>fmt.Println(&quot;connection info:&quot;, host, dbName)<br>session, err := mgo.Dial(&quot;mongodb://localhost:27017&quot;)<br>if err != nil {<br>fmt.Println(&quot;session err:&quot;, err)<br>os.Exit(2)<br>}<br>db = session.DB(dbName)<br>return db<br>}</pre><pre>// for mysql</pre><pre>var sqldb *sql.DB<br>func GetSqlDB() *sql.DB {<br>var err error<br>dbUser := &quot;root&quot; // mysql username<br>dbPass := &quot;root&quot;  // mysql password<br>dbName := &quot;godb&quot; // mysql dbname<br>sqldb, err := sql.Open(&quot;mysql&quot;, dbUser+&quot;:&quot;+dbPass+&quot;@/&quot;+dbName)<br>if err != nil {<br>panic(err.Error())<br>}<br>return sqldb<br>}</pre><p>7. Create a Repository interface which consists of all the abstract methods which will interact with the database to get the things done. Also create a repo structure to return the database name .</p><pre>// repo.go stars here</pre><pre>package main</pre><pre>import (<br>&quot;context&quot;<br>&quot;database/sql&quot;<br>&quot;errors&quot;<br>&quot;fmt&quot;<br>&quot;github.com/go-kit/kit/log&quot;<br>_ &quot;github.com/go-sql-driver/mysql&quot;<br>&quot;gopkg.in/mgo.v2&quot;<br>&quot;gopkg.in/mgo.v2/bson&quot;<br>)<br>var RepoErr = errors.New(&quot;Unable to handle Repo Request&quot;)<br>const UserCollection = &quot;gotestuser&quot;<br>type Repository interface {<br>CreateUser(ctx context.Context, user User) error<br>}</pre><pre>// Repo structure for mongodb<br>type repo struct {<br>db     *mgo.Database<br>logger log.Logger<br>}<br>// Repo for mongodb<br>func NewRepo(db *mgo.Database, logger log.Logger) (Repository, error) {<br>return &amp;repo{<br>db:     db,<br>logger: log.With(logger, &quot;repo&quot;, &quot;mongodb&quot;),<br>}, nil<br>}</pre><p>Using Mysql</p><pre>// Repo structure for mysql</pre><pre>type sqlrepo struct {<br>sqldb  *sql.DB<br>logger log.Logger<br>}<br>// Repo for mysql</pre><pre>func NewSqlRepo(sqldb *sql.DB, logger log.Logger) (Repository, error) {<br>return &amp;sqlrepo{<br>sqldb:  sqldb,<br>logger: log.With(logger, &quot;sqlrepo&quot;, &quot;sqldb&quot;),<br>}, nil<br>}</pre><p>8. Implement all the abstract repository methods declared inside the Repository interface.</p><p>Using Mongodb..</p><pre>// repo.go continues here<br></pre><pre>func (repo *repo) CreateUser(ctx context.Context, user User) error {<br>fmt.Println(&quot;create user mongo repo&quot;, db)<br>err := db.C(UserCollection).Insert(user)<br>if err != nil {<br>fmt.Println(&quot;Error occured inside CreateUser in repo&quot;)<br>return err<br>} else {<br>fmt.Println(&quot;User Created:&quot;, user.Email)<br>}<br>return nil<br>}</pre><p>Using Mysql..</p><pre>func (sqlrepo *sqlrepo) CreateUser(ctx context.Context, user User) error {fmt.Println(&quot;create user sql repo&quot;, sqldb)<br>dbt := sqlrepo.sqldb<br>sqlresp, err := dbt.Prepare(&quot;INSERT INTO gotestuser (id,userid,email,password,phone) VALUES (?,?,?,?,?)&quot;)<br>sqlresp.Exec(user.Id, user.Userid, user.Email, user.Password, user.Phone)<br>fmt.Println(&quot;User Created:&quot;, sqlresp, err)<br>return nil<br>}</pre><p>Write go.mod to build and execute this service in an easy way.</p><pre>// go.mod</pre><pre>module UserService</pre><pre>go 1.14<br>require (<br>github.com/go-kit/kit v0.10.0<br>github.com/gofrs/uuid v3.3.0+incompatible<br>github.com/prometheus/client_golang v1.3.0<br>gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22<br>)</pre><p>Now our service is ready to test using postman, but let’s wait to add more features to this service.</p><p>Note : Don’t get confused by seeing the two databases. There are notable differences for them.</p><ol><li>main.go → service creation</li><li>dbconnection.go → GetSqlDB() and GetMongoDB()</li><li>repo.go →sqlrepo structure (for mysql), repo structure (for mongo),NewRepo()(for mongo) , NewSqlRepo (for mysql)</li><li>repo.go → repository methods implementations.</li><li>Before going to use mysql service methods create a database with name “godb” and a table inside it with the name “gotestuser” with the model fields.</li></ol><p>Apart from these changes all the remaining is same.</p><p><strong>9. Logging Middleware:</strong></p><p>Logging middleware is used to get the logs of service methods throughout the service starting from receiving request from client to traversing through transport , endpoint and service layers and sending the response to the client.</p><p>To have logging to your microservice add the following to the respective files.</p><pre>// Add this lines to main.go</pre><pre>logger := log.NewLogfmtLogger(os.Stderr) // creating logger</pre><pre>svc = loggingMiddleware{logger, svc} // passing the service to the loggingMiddleware</pre><p>Write logging.go file to enable and configure the logging for all the serrvice methods.</p><pre>package main</pre><pre>import (<br>&quot;context&quot;<br>&quot;time&quot;<br>&quot;github.com/go-kit/kit/log&quot;<br>)<br>type loggingMiddleware struct {<br>logger log.Logger<br>next   UserService<br>}</pre><pre>func (mw loggingMiddleware) CreateUser(ctx context.Context, user User) (Email string, err error) {<br>defer func(begin time.Time) {<br>_ = mw.logger.Log(<br>&quot;method&quot;, &quot;creatuser&quot;,<br>&quot;Email&quot;, user.Email,<br>&quot;err&quot;, err,<br>&quot;took&quot;, time.Since(begin),<br>)<br>}(time.Now())</pre><pre>Email, err = mw.next.CreateUser(ctx, user)<br>return<br>}</pre><p><strong>10. Instrumentation with prometheus :</strong></p><p>Instrumentation is necessary to monitor the application in every aspect with the help of metrics generated.prometheus is a monitoring tool for the metrics. We can export and view this metrics graphically in grafana by just mentioning the address where in the metrics are generated.</p><p>Add the Following imports and methods to main.go.</p><pre>&quot;github.com/prometheus/client_golang/prometheus/promhttp&quot;<br>stdprometheus &quot;github.com/prometheus/client_golang/prometheus&quot;<br>kitprometheus &quot;github.com/go-kit/kit/metrics/prometheus&quot;</pre><pre>// Adding requestcount,latency,countResult to metrics</pre><pre>fieldKeys := []string{&quot;method&quot;, &quot;error&quot;}<br>requestCount := kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{<br>Namespace: &quot;my_group&quot;,<br>Subsystem: &quot;string_service&quot;,<br>Name:      &quot;request_count&quot;,<br>Help:      &quot;Number of requests received.&quot;,<br>}, fieldKeys)</pre><pre>requestLatency := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{<br>Namespace: &quot;my_group&quot;,<br>Subsystem: &quot;string_service&quot;,<br>Name:      &quot;request_latency_microseconds&quot;,<br>Help:      &quot;Total duration of requests in microseconds.&quot;,<br>}, fieldKeys)</pre><pre>countResult := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{<br>Namespace: &quot;my_group&quot;,<br>Subsystem: &quot;string_service&quot;,<br>Name:      &quot;count_result&quot;,<br>Help:      &quot;The result of each count method.&quot;,<br>}, []string{})</pre><pre>svc = instrumentingMiddleware{requestCount, requestLatency, countResult, svc}</pre><pre>// Route to export the metrics<br>http.Handle(&quot;/metrics&quot;, promhttp.Handler())</pre><p>Add a instrumenting.go file to generate the metrics for all the service methods.</p><pre>// instrumenting.go</pre><pre>package main<br>import (<br>&quot;context&quot;<br>&quot;fmt&quot;<br>&quot;time&quot;<br>&quot;github.com/go-kit/kit/metrics&quot;<br>)</pre><pre>type instrumentingMiddleware struct {<br>requestCount   metrics.Counter<br>requestLatency metrics.Histogram<br>countResult    metrics.Histogram<br>next           UserService<br>}</pre><pre>func (mw instrumentingMiddleware) CreateUser(ctx context.Context, user User) (output string, err error) {<br>defer func(begin time.Time) {<br>lvs := []string{&quot;method&quot;, &quot;createuser&quot;, &quot;error&quot;, fmt.Sprint(err != nil)}<br>mw.requestCount.With(lvs...).Add(1)<br>mw.requestLatency.With(lvs...).Observe(time.Since(begin).Seconds())<br>}(time.Now())<br>output, err = mw.next.CreateUser(ctx, user)<br>return<br>}</pre><p>Hurray!!, you are all set to test the example microservice now.</p><ol><li>Build the Go service with : go build .</li><li>Run it using the exe file generated ,in this case it is “UserService”.</li><li>Go to the postman and test the following routes.</li></ol><p>i. localhost:8000/create</p><p>ii. localhost:8000/user/{userid}</p><p>iii. localhost:8000/deleteuser/{userid}</p><p>iv. localhost:8000/updateuser/</p><p>v. localhost:8000/getall</p><p>4. Go to the Browser and type in the address : localhost:8000/metrics to view the metrics.</p><p>You can write as many as microservices and make communication between them with the help of transports like Http and gRpc.</p><p>That’s it guys, I hope you’ll understood the things well. Still if anyone have any suggestions or doubts do comment here.I am always ready to help you out at any point of time.</p><p>For any queries feel free to reach me out at LinkedIn <strong>B Narsimha </strong>and <strong>narsimhulu.464@gmail.com.</strong></p><p><strong>Thank You !!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6065d7b917d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>