<?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 Rajkumar Rajaratnam on Medium]]></title>
        <description><![CDATA[Stories by Rajkumar Rajaratnam on Medium]]></description>
        <link>https://medium.com/@rajkumar.rajaratnam?source=rss-9072b29ccdd6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Rajkumar Rajaratnam on Medium</title>
            <link>https://medium.com/@rajkumar.rajaratnam?source=rss-9072b29ccdd6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:14:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajkumar.rajaratnam/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[CI/CD for WSO2 Products — Part 1: Deploying APIs to WSO2 API Manager using API Controller]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/ci-cd-for-wso2-products-part-1-deploying-apis-to-wso2-api-manager-using-api-controller-b64fa90b4472?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b64fa90b4472</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[wso2]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 23:53:47 GMT</pubDate>
            <atom:updated>2025-06-20T04:00:34.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>CI/CD for WSO2 Products — Part 1: Deploying APIs to WSO2 API Manager using API Controller</h3><p>In today’s fast-paced integration landscape, reliable and repeatable API deployments are essential. Manual deployments are not only time-consuming — they’re also error-prone and hard to trace. This article kicks off a series on implementing a modern CI/CD pipeline for WSO2 products, starting with deployment of APIs to WSO2 API Manager using the WSO2 API Controller (apictl), GitHub Actions, Vault, and Postman.</p><h3>Architecture Overview</h3><p>The diagram below shows a GitOps-style CI/CD pipeline to automate API and policy deployment into WSO2 API Manager environments. This approach decouples development from deployment, integrates reusable workflows, and ensures secure, auditable, and repeatable releases.</p><p>This architecture ensures:</p><ul><li><strong>Decoupled Ownership</strong>: APIs and policies live in independent repositories, while the deployment pipeline lives in a centralized repo.</li><li><strong>Centralized CI/CD Management</strong>: All deployments are coordinated via the wso2-pipeline repository.</li><li><strong>Reusable Workflows</strong>: CI/CD logic is standardized in the wso2-workflows repository and reused across other repos.</li><li><strong>Secure Secrets Management</strong>: Credentials are securely stored and accessed via <strong>HashiCorp Vault</strong> (or GitHub secrets).</li><li><strong>Automated Testing</strong>: <strong>Postman</strong> test suites ensure API integrity post-deployment.</li><li><strong>Self-hosted Runners</strong>: CI/CD steps run inside your network, with full access to internal infrastructure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R01xMR7zqTMnuLQFGD1Ydg.png" /></figure><h3>Repository Breakdown</h3><h4><strong>wso2-workflows: Reusable CI/CD Building Blocks</strong></h4><p>Stores reusable GitHub Action workflows:</p><ul><li>ci-*: Build Docker images and push them to a container registry.</li><li>cd-*: Deploy APIs, policies, Micro Integrator containers, Ballerina containers, etc.</li><li>release-*: Build and publish release artifacts.</li></ul><pre>wso2-workflows<br>└── .github<br>    └── workflows<br>        ├── cd-apim-apis.yml<br>        ├── cd-apim-rate-limiting-policies.yml<br>        ├── cd-apim-mediation-policies.yml<br>        ├── release-apim-policy.yml<br>        └── release-apim-api.yml</pre><h4>wso2-pipeline: Centralized CI/CD Orchestration</h4><p>A central repo with one branch per environment (dev, qa, uat). It holds release metadata (release.json) for each API/policy:</p><pre>wso2-pipeline<br>├── apim<br>│   ├── policies<br>│   │   ├── rate-limiting<br>│   │   │   └── policy-rate-limiting<br>│   │   │       └── release.json<br>│   │   └── mediation<br>│   │       └── policy-mediation<br>│   │           └── release.json<br>│   └── apis<br>│       └── api-identity-sys<br>│           ├── v2<br>│           │   └── release.json<br>│           └── v1<br>│               └── release.json<br>└── .github<br>    └── workflows<br>        ├── cd-apim-rate-limiting-policies.yml<br>        ├── cd-apim-mediation-policies.yml<br>        └── cd-apim-apis.yml</pre><p>Sample release.json:</p><pre>{<br>  &quot;artifactRepository&quot;: &quot;wso2-cicd/policy-mediation&quot;,<br>  &quot;releaseVersion&quot;: &quot;v1.8&quot;,<br>  &quot;artifacts&quot;: [<br>    &quot;policy-mediation.zip&quot;<br>  ],<br>  &quot;pullRequest&quot;: {<br>    &quot;url&quot;: &quot;https://github.com/wso2-cicd/policy-mediation/pull/4&quot;,<br>    &quot;title&quot;: &quot;Update addQueryParam.yaml&quot;,<br>    &quot;mergedAt&quot;: &quot;2025-06-19T12:29:57Z&quot;<br>  }<br>}</pre><h4>API Repositories</h4><p>Each API lives in its own repo with the following structure:</p><pre>api-identity-sys<br>├── apim                                        # All API Manager-specific artifacts<br>│   ├── v2                                      # Version 1 of the API<br>│   │   ├── Definitions<br>│   │   │   └── swagger.yaml                    # Swagger definition for the API<br>│   │   ├── Policies                            # Mediation policies attached to this API<br>│   │   │   ├── removeHeader_v1_common.yaml<br>│   │   │   ├── removeHeader_v1_common.j2<br>│   │   │   ├── disableChunking_v1_common.yaml<br>│   │   │   ├── disableChunking_v1_common.j2<br>│   │   │   ├── addLogMessage_v1_common.yaml<br>│   │   │   ├── addLogMessage_v1_common.j2<br>│   │   │   ├── addHeader_v2_common.yaml<br>│   │   │   └── addHeader_v2_common.j2<br>│   │   ├── api.yaml<br>│   │   └── Conf                                # Environment-specific configuration<br>│   │       ├── certificates<br>│   │       │   ├── backendUAT.crt              # UAT backend certificate<br>│   │       │   ├── backendPROD.crt             # PROD backend certificate<br>│   │       │   ├── backendQA.crt               # QA backend certificate<br>│   │       │   └── backendDev.crt              # Dev backend certificate<br>│   │       ├── params.yaml                     # Environment specific parameters like URLs, policies, etc<br>│   │       └── api_meta.yaml<br>│   └── v1                                      # Version 1 of the API, same structure as Version 1<br>│       ├── Policies<br>│       │   ├── addQueryParam_v1_common.yaml<br>│       │   ├── addQueryParam_v1_common.j2<br>│       │   ├── addQueryParam_v1_common.gotmpl<br>│       │   ├── addLogMessage_v1_common.yaml<br>│       │   ├── addLogMessage_v1_common.j2<br>│       │   ├── addHeader_v2_common.yaml<br>│       │   └── addHeader_v2_common.j2<br>│       ├── Definitions<br>│       │   └── swagger.yaml<br>│       ├── api.yaml<br>│       └── Conf<br>│           ├── certificates<br>│           │   ├── backendUAT.crt<br>│           │   ├── backendPROD.crt<br>│           │   ├── backendQA.crt<br>│           │   └── backendDev.crt<br>│           ├── params.yaml<br>│           └── api_meta.yaml<br>├── src                                         # API implementation source code (e.g., Spring Boot, .NET)<br>└── .github<br>    └── workflows<br>        └── apim-build-n-release-api.yml</pre><p>Each version (v1, v2, etc.) is stored in separate folders with environment-specific configs embedded.</p><p>The apim/v1/Conf/params.yaml file allows you to define configuration values that vary across environments (e.g., Dev, QA). These parameters are used during API deployment via apictl to inject the appropriate values dynamically.</p><p>Below is a sample structure:</p><pre>environments:<br>  - name: dev<br>    configs:<br>      endpoints:<br>        production:<br>          url: https://dev.x.com/iam/scim<br>      deploymentEnvironments:<br>        - displayOnDevportal: true<br>          deploymentEnvironment: Default<br>          deploymentVhost: localhost<br>      certs:<br>        - hostName: dev.x.com<br>          alias: backendDev<br>          path: backendDev.crt<br>      policies:<br>        - Gold<br><br>  - name: qa<br>    configs:<br>      endpoints:<br>        production:<br>          url: https://qa.x.com/iam/scim<br>      deploymentEnvironments:<br>        - displayOnDevportal: true<br>          deploymentEnvironment: Default<br>          deploymentVhost: localhost<br>      certs:<br>        - hostName: qa.x.com<br>          alias: backendQA<br>          path: backendQA.crt<br>      policies:<br>        - Unlimited<br>        - Gold<br><br>  - name: uat<br>    configs:<br>      endpoints:<br>        production:<br>          url: https://uat.x.com/iam/scim<br>      deploymentEnvironments:<br>        - displayOnDevportal: true<br>          deploymentEnvironment: Default<br>          deploymentVhost: localhost<br>      certs:<br>        - hostName: uat.x.com<br>          alias: backendUAT<br>          path: backendUAT.crt<br>      policies:<br>        - Unlimited<br>        - Gold<br><br>  - name: prod<br>    configs:<br>      endpoints:<br>        production:<br>          url: https://x.com/iam/scim<br>      deploymentEnvironments:<br>        - displayOnDevportal: true<br>          deploymentEnvironment: Default<br>          deploymentVhost: localhost<br>      certs:<br>        - hostName: x.com<br>          alias: backendPROD<br>          path: backendPROD.crt<br>      policies:<br>        - Unlimited<br>        - Gold</pre><h4>Policy Repositories</h4><p>mediation policies and rate-limiting policies can be maintained in separate dedicated repositories:</p><p>policy-mediation repository stores common, reusable mediation policies (e.g., logging, header injection) that can be attached to multiple APIs.</p><pre>policy-mediation<br>├── src<br>│   ├── addQueryParam<br>│   │   ├── v3<br>│   │   │   ├── addQueryParam.yaml<br>│   │   │   ├── addQueryParam.j2<br>│   │   │   └── addQueryParam.gotmpl<br>│   │   ├── v2<br>│   │   │   ├── addQueryParam.yaml<br>│   │   │   ├── addQueryParam.j2<br>│   │   │   └── addQueryParam.gotmpl<br>│   │   ├── v1<br>│   │   │   ├── addQueryParam.yaml<br>│   │   │   ├── addQueryParam.j2<br>│   │   │   └── addQueryParam.gotmpl<br>│   └── addHeader<br>│       ├── v1<br>│       │   ├── addHeader.yaml<br>│       │   └── addHeader.j2<br>│       └── v2<br>│           ├── addHeader.yaml<br>│           └── addHeader.j2<br>├── .github<br>│   └── workflows<br>│       └── apim-build-n-release-policy.yml</pre><p>policy-rate-limiting repo is used to manage shared rate-limiting policies, such as advanced, custom, subscription, and application level policies.</p><pre>policy-rate-limiting<br>├── src<br>│   ├── Custom-Admin5PerMin.yaml<br>│   ├── Application-100PerMin.yaml<br>│   ├── Advanced-100KPerMin.yaml<br>│   ├── Subscription-Diamond.yaml<br>│   └── Subscription-Platinum.yaml<br>├── .github<br>│   └── workflows<br>│       └── apim-build-n-release-policy.yml</pre><h3>GitHub Self-Hosted Runners</h3><p>CI/CD jobs run on <strong>self-hosted GitHub runners</strong> deployed within your organization’s network. These runners are pre-installed with:</p><ul><li>apictl – WSO2 CLI to deploy APIs</li><li>newman – Postman CLI to run tests</li></ul><h3>Secrets via HashiCorp Vault</h3><p>All sensitive values (e.g., APIM credentials, backend credentials) are stored in <strong>Vault</strong>, accessed by workflows via authenticated GitHub-to-Vault integration. If Vault isn’t available, GitHub Secrets can be used as an alternative.</p><h3>CI/CD Flow Walkthrough</h3><h4>0. API Development</h4><p>Developers build and test the API using WSO2 Publisher Portal in Dev.</p><h4>1. Push Code to Git</h4><ul><li>Export API archive (via apictl or download ZIP from Publisher Portal)</li><li>Extract and replace files inside apim/v1 in the API repo</li><li>Push to main branch → triggers the build workflow</li></ul><h4>2–3. Trigger Build Workflow</h4><p>The workflow:</p><ul><li>Packages the API</li><li>Creates a release and upload the API artifact (e.g., Identity-System.zip)</li><li>Updates release.json in the wso2-pipeline/dev branch with the new release version (e.g., wso2-pipeline/apim/apis/api-identity-sys/v1/release.json) → triggers the CD workflow</li><li>If this is the <strong>first release</strong> of a given API or Policy repository, the workflow will automatically open a <strong>pull request to the </strong><strong>wso2-pipeline repository</strong>. This allows a team lead or maintainer to <strong>review and approve the addition</strong> of the new artifact to the centralized CI/CD pipeline. Once merged, the new API or Policy will be fully integrated and automatically deployed to the Dev environment.</li></ul><h4>4. CD Trigger via Pipeline Repo</h4><ul><li>cd-apim-apis.yml detects changes to release.json and triggers API deployment</li><li>cd-apim-policies.yml watches for policy changes</li><li>GitHub self-hosted runner picks up the job and starts the CD pipeline steps</li></ul><h4>5. Download Artifact</h4><ul><li>Reads from release.json and downloads the appropriate API release with artifacts.</li></ul><h4>6. Fetch Secrets</h4><ul><li>Vault is queried securely for APIM login credentials</li></ul><h4>7. Deploy to Dev</h4><ul><li>API deployed using:</li></ul><pre>apictl import api -f Identity-System/ -e dev -k --update --rotate-revision --params Identity-System/v1/Conf</pre><h4>8. Download Postman Tests</h4><ul><li>Tests scripts and Dev environment configs fetched from Postman workspace</li></ul><h4>9. Execute Automated Tests</h4><ul><li>Postman tests executed via newman CLI</li></ul><h4>10. Open Pull Request to QA</h4><ul><li>After successful Dev validation, a pull request is automatically created <em>to</em> the qa branch of the wso2-pipeline repository. Instead of opening a PR directly from the dev branch—which could include unrelated changes—the system creates a temporary branch from the qa branch, updates only the relevant release.json for the specific API, and then opens a PR from this temporary branch to qa. This ensures that only scoped changes are promoted without accidentally including updates for other APIs.</li><li>If Dev validation fails, the system can also trigger a revert pull request. This simply rolls back the release.json to its previous version to undo the deployment.</li></ul><h4>11. Manual Approval to Deploy to QA</h4><ul><li>PR reviewed and merged by a lead/team owner</li></ul><h4>12–17. QA Deployment &amp; Testing</h4><ul><li>Same steps as Dev: download artifacts →fetch secrets → deploy → run Postman tests</li></ul><h4>18. Automatic PR to UAT</h4><ul><li>If QA tests pass, the same promotion process continues to UAT</li></ul><h3>Benefits of This CI/CD Model</h3><ul><li><strong>GitOps &amp; GitHub-Native</strong>: All changes are traceable via PRs and commits, ensuring full auditability.</li><li><strong>Centralized CI/CD</strong>: A single pipeline repo manages all deployments with one branch per environment, making it easy to track what’s deployed where. It also sets the foundation for building a <strong>Release Management UI</strong>, which we’ll explore in a future blog post</li><li><strong>Secure &amp; Scalable</strong>: Secrets are safely managed with Vault, and reusable workflows allow consistent scaling across multiple APIs.</li><li><strong>Automated Validation</strong>: Postman tests run after every deployment to catch issues early and ensure quality.</li><li><strong>Rollback Ready</strong>: Each version is recorded in release.json, allowing simple and fast rollbacks.</li></ul><h3>Reference Implementation on GitHub</h3><p>A complete reference implementation of the CI/CD model described in this blog is available on GitHub:<br> 👉 <a href="https://github.com/wso2-cicd"><strong>github.com/wso2-cicd</strong></a></p><p>This implementation includes:</p><ul><li>Reusable GitHub Actions workflows for APIs and policies</li><li>GitOps-style repository structures</li><li>Real examples for API, mediation, and rate-limiting policy deployments</li><li>Centralized release metadata management</li></ul><p>You can use this as a starting point to implement automated, auditable deployments in your own WSO2 environments.</p><h3>What’s Next?</h3><p>In <strong>Part 2</strong> of this series, we’ll shift our focus to the CI/CD pipelines for automating the deployment of WSO2 API Manager server components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b64fa90b4472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Connect at Scale: The Hidden Challenges]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/kafka-connect-at-scale-the-hidden-challenges-44bab174740d?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/44bab174740d</guid>
            <category><![CDATA[kafka-connect]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 05:08:57 GMT</pubDate>
            <atom:updated>2025-03-04T05:08:57.360Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Kafka Connect’s scalability issues, poor observability, SMT limitations, predicate complexities, error handling flaws, and rebalancing struggles in real-world enterprise use cases.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuTF2xQQhIGWauNUc_LUxw.png" /></figure><p>Kafka Connect is a framework designed for streaming data between various sources and Apache Kafka, as well as from Kafka to different sinks. It provides a no-code, configuration-driven approach that simplifies deploying connectors. However, once you start using it in large-scale enterprise environments, its limitations quickly become apparent.</p><p>We’ve used Kafka Connect extensively with the SQL Database Source Connector and the HTTP Sink Connector, and along the way, we’ve encountered numerous issues. In this post, I’ll highlight the most significant challenges we’ve faced and why they make Kafka Connect a difficult choice for large-scale integrations.</p><p>Let’s dive into some of the pain points at the Kafka Connect level before looking at specific issues with the HTTP Sink Connector.</p><h3>Pain Points at the Kafka Connect Level</h3><h4>1. A Monolithic JVM That Lacks Isolation</h4><p>Kafka Connect runs as a monolithic Java application, where all deployed connectors and their tasks run within the same JVM instance. This architecture introduces several problems:</p><ul><li><strong>Resource Contention:</strong> One misbehaving connector task can degrade the performance of others.</li><li><strong>Lack of Scalability:</strong> Scaling is limited to increasing the number of worker nodes, which is not always ideal.</li><li><strong>No Deployment Isolation:</strong> Even a minor update to a single connector or a new connector deployment requires restarting the entire Kafka Connect cluster because it needs to reload secrets and configurations.</li><li><strong>Operational Complexity:</strong> Debugging and managing multiple connectors in a shared JVM is a nightmare in production environments.</li></ul><h4>2. SMT (Single Message Transformations) Are Too Basic</h4><p>Kafka Connect provides Single Message Transformations (SMT) to modify events before they reach Kafka or a downstream system. While useful for simple field renaming or filtering, SMT is far too limited for most enterprise use cases.</p><ul><li><strong>No Complex Transformations:</strong> If you need to merge fields, apply complex conditional logic, or transform nested structures, SMT won’t be enough.</li><li><strong>Costly Workarounds:</strong> The only alternative is to pass raw events to Kafka and transform them later using Kafka Streams — a much more expensive approach in terms of infrastructure and compute costs.</li></ul><h4>3. Severe Lack of Logs &amp; Visibility</h4><p>Kafka Connect does not provide built-in logs or message tracing for connectors, making it extremely difficult to troubleshoot failures.</p><ul><li><strong>No Event Tracking:</strong> There’s no way to natively track what happened to a record once it enters Kafka Connect.</li><li><strong>Hacks Exist, But They’re Limited:</strong> Some workarounds involve implementing an SMT that writes logs, but this only captures a single point in the data flow. You still don’t get end-to-end traceability.</li></ul><p>For large-scale enterprise deployments, lack of observability is a dealbreaker — it makes debugging painful, and leads to blind spots in your data pipeline.</p><h4>4. Frequent and Costly Rebalancing</h4><p>One of the most frustrating aspects of Kafka Connect is its frequent task rebalancing.</p><ul><li><strong>Excessive Rebalancing:</strong> Even minor disruptions — such as a brief network glitch — can trigger a full rebalance across all tasks.</li><li><strong>Slow Recovery:</strong> In our experience, when the SQL DB Source Connector undergoes rebalancing, it can take 2–3 hours before it resumes<strong> </strong>streaming data.</li><li><strong>Operational Headaches:</strong> This behavior significantly impacts uptime and adds operational overhead, especially in mission-critical data pipelines.</li></ul><h4>5. Predicates Are Unmanageable in Complex Setups</h4><p>Predicates allow conditional routing, filtering, and transformation rules within Kafka Connect. However, they quickly become unmanageable in enterprise environments with:</p><ul><li>Multiple databases and tables feeding into Kafka.</li><li>Varying routing and filtering requirements across different event types.</li><li>A growing rule set that becomes difficult to maintain over time.</li></ul><p>As complexity increases, managing predicates becomes a nightmare, making Kafka Connect difficult to scale in large deployments.</p><h3>Issues Specific to HTTP Sink Connector</h3><p>Now, let’s discuss some critical pain points specific to the HTTP Sink Connector. If you’re interested in understanding the inner workings of this connector, check out my previous <a href="https://medium.com/@rajkumar.rajaratnam/confluent-http-sink-connector-enhancing-error-handling-and-reprocessing-in-kafka-10246f246d99">blog</a>.</p><h4>1. Error Handling and Retries Are Too Basic</h4><p>The HTTP Sink Connector includes basic error handling, retries, and dead-letter queue (DLQ) support. However, it has several major limitations in an enterprise setup:</p><p><strong>a. Retries All HTTP Errors (Even When Not Necessary)</strong></p><ul><li>The connector treats all HTTP status codes above 299 as errors, automatically retrying and publishing failed requests to a dead-letter topic.</li><li>In many cases, not all HTTP errors should be retried.</li><li>Example: A 400 Bad Request from an email API indicating that a user has opted out should not be retried or sent to the dead-letter topic. It should simply be ignored as a successful case.</li></ul><p><strong>b. Cannot Inspect HTTP Response Bodies for Intelligent Retries</strong></p><ul><li>In enterprise integrations, decision-making often depends on the HTTP response body rather than just the status code.</li><li>Some 400 errors should be retried, while others should not — but the connector has no mechanism to differentiate them.</li></ul><p><strong>c. Does Not Retry Network Failures</strong></p><ul><li>The connector fails immediately on network issues rather than retrying.</li><li>We’ve seen cases where a brief network outage resulted in 50,000 records being dumped into the dead-letter topic — creating unnecessary operational burdens.</li></ul><p><strong>d. Uses Two Different Dead Letter Topics for Different Error Types</strong></p><ul><li><strong>DLQ Topic:</strong> For deserialization or SMT issues.</li><li><strong>Error Topic:</strong> For HTTP errors.</li></ul><p>Having two separate dead-letter topics adds operational complexity without providing significant benefits.</p><h4>2. Lack of Correlation ID Support</h4><p>In enterprise integrations, a Correlation ID is crucial for troubleshooting and tracing transactions. However, the HTTP Sink Connector fails to handle it properly:</p><ul><li><strong>No Support for Batching with Unique Headers:</strong> If records contain a header (e.g., Correlation ID) with different values, the connector cannot batch them into a single request.</li><li><strong>Forced to Drop Correlation IDs:</strong> The only workaround is to remove the header using a custom SMT, which means you lose end-to-end traceability.</li></ul><p>This is a huge limitation for teams that rely on Correlation IDs for debugging and observability.</p><h3>Final Thoughts</h3><p>Kafka Connect is often marketed as a plug-and-play solution for integrating data into Kafka. However, once you start using it at scale, the cracks begin to show.</p><p>For simple use cases, Kafka Connect is a great tool. But for enterprise-grade, high-volume data pipelines, its limitations — monolithic architecture, weak transformation capabilities, lack of logs, and painful rebalancing issues — make it a frustrating choice.</p><p>Would I recommend Kafka Connect? Yes, but only if you’re aware of its limitations and prepared to work around them. Otherwise, you might be better off building a custom integration layer that offers better isolation, scalability, observability, error handling, and transformation capabilities such as <a href="https://github.com/ballerina-connect/kafka-to-http">Ballerina Connect</a>.</p><p>Have you experienced similar challenges with Kafka Connect? Let’s discuss in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44bab174740d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Confluent HTTP Sink Connector: Enhancing Error Handling and Reprocessing in Kafka]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/confluent-http-sink-connector-enhancing-error-handling-and-reprocessing-in-kafka-10246f246d99?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/10246f246d99</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kafka-connect]]></category>
            <category><![CDATA[confluent]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 16:19:31 GMT</pubDate>
            <atom:updated>2024-02-12T18:01:45.641Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing Retries, Dead Letter Queue, Error Topic, and Efficient Message Reprocessing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VnF4QX3nGm5Kl_wMD1YjQ.png" /></figure><h4>Introduction</h4><p>The Confluent HTTP Sink connector serves as a crucial bridge between Kafka source topics and HTTP target APIs, facilitating seamless data, eliminating the need for manual coding efforts.</p><p>Its integration within Kafka Connect enables effortless deployment, allowing users to leverage its capabilities without extensive development overhead. Below is a sample connector configuration that we can deploy to self managed Kafka Connect running on Kubernetes, highlighting essential parameters only:</p><pre>apiVersion: platform.confluent.io/v1beta1<br>kind: Connector<br>metadata:<br>  name: signup-http-snk<br>  namespace: wso2-dev<br>spec:<br>  class: &quot;io.confluent.connect.http.HttpSinkConnector&quot;<br>  taskMax: 2<br>  connectClusterRef:<br>    name: wso2-dev<br>  configs:<br>    topics: signup<br>    connector.class: &quot;io.confluent.connect.http.HttpSinkConnector&quot;<br>    http.api.url: https://api.wso2.com/signup<br>    request.method: &quot;POST&quot;<br>    request.body.format: &quot;json&quot;<br>    max.poll.records: &quot;500&quot;<br>    batch.max.size: &quot;500&quot;<br>    max.retries: &quot;5&quot;<br>    retry.backoff.ms: &quot;3000&quot;<br>    retry.on.status.codes: 400,500-<br>    errors.tolerance: all<br>    errors.log.enable: &quot;true&quot;<br>    errors.log.include.messages: &quot;true&quot;<br>    errors.deadletterqueue.context.headers.enable: &quot;true&quot;<br>    errors.deadletterqueue.topic.name: signup.dlq<br>    behavior.on.error: &quot;log&quot;<br>    reporter.error.topic.name: signup.error<br>    reporter.result.topic.name: signup.success</pre><p>In this article, we delve into the intricacies of error handling and reprocessing within the Confluent Cloud environment alongside self-managed Kafka Connect setups. Through a comprehensive exploration, we aim to elucidate the mechanisms that govern the behavior of this connector, shedding light on error handling strategies and efficient message reprocessing methodologies.</p><h4>Understanding the Data Flow</h4><p>Before delving into the specifics of error handling and reprocessing, let’s understand the underlying data flow within the Kafka Connect and Confluent HTTP Sink connector ecosystem. The following breakdown elucidates the journey of a message passing through various components as depicted in the diagram above:</p><ol><li><strong>Data Ingestion:</strong> Originating from various sources, messages are generated and deposited into the designated Source topic, facilitated by connectors deployed within Kafka Connect, such as CDC connectors.</li><li><strong>Message Reception:</strong> The HTTP Sink connector intercepts incoming messages from the Source topic.</li><li><strong>Message Processing:</strong> Upon reception, the HTTP Sink connector undertakes crucial tasks including message deserialization and application of Single Message Transformations (SMT). However, these processing steps are susceptible to failure.</li><li><strong>Error Handling:</strong> In instances where processing encounters errors within Kafka Connect, the HTTP Sink connector swiftly redirects the problematic message to the Dead Letter Queue (DLQ) topic. Subsequently, the message flow ends at this juncture.</li><li><strong>API Invocation:</strong> Successfully processed messages undergo invocation of the designated HTTP API, initiating communication with the targeted external system.</li><li><strong>API Response Reception:</strong> The HTTP Sink connector receives the response from the HTTP API</li><li><strong>Retry Condition Evaluation:</strong> Post-reception of the API response, the connector evaluates the HTTP status code against the predefined set of retry conditions, factoring in both the configured maximum retries (max.retries) and defined status codes (retry.on.status.codes).</li><li><strong>Retry Execution:</strong> If the conditions for retrying are met, the HTTP Sink connector orchestrates subsequent API calls with an exponential backoff delay, ensuring resilience in the face of transient errors.</li><li><strong>Status Code Validation:</strong> In cases where retry attempts are exhausted, or when retry conditions are not met, the connector evaluates the HTTP status code to ascertain the success or failure of the operation (status &gt; 199 &amp;&amp; status &lt; 300.). However, this validation logic remains hardcoded within the connector, lacking configurable parameters for defining success criteria.</li><li><strong>Success Message Handling:</strong> Should the validation confirm a successful operation, the connector produces a message to the Success topic, facilitating downstream processes and acknowledging the successful transmission.</li><li><strong>Error Message Handling:</strong> Conversely, if the validation indicates a failed operation, the connector produces a message to the Error topic, earmarking it for further analysis and resolution.</li><li><strong>Error Analysis and Filtering:</strong> Custom-built reprocessing applications come into play, consuming messages from both the DLQ and Error topics. These applications may apply filters based on various criteria such as status codes and backend responses, ensuring the refinement and optimization of erroneous messages.</li><li><strong>Reprocessing:</strong> Subsequently, the reprocessing applications generate refined messages, directing them to the dedicated Reprocess topic for further processing by the HTTP Sink connector.</li><li>Message Reconsumption: The HTTP Sink connector seamlessly consumes messages from the Reprocess topic, initiating a recursive cycle wherein refined messages undergo the same processing flow, ensuring persistent and efficient message handling.</li></ol><h4>Exploring Error Handling Strategies</h4><p>Effective error handling forms the cornerstone of robust data processing pipelines. The Confluent HTTP Sink connector incorporates several strategies to mitigate processing failures:</p><p><strong>Retries:</strong> Out-of-the-box support for retrying failed requests empowers the connector to resiliently navigate transient errors. Configuration parameters such as maximum retries, retry backoff intervals, and retry conditions offer fine-grained control over retry behavior, bolstering fault tolerance.</p><pre>max.retries: &quot;5&quot;<br>retry.backoff.ms: &quot;3000&quot;<br>retry.on.status.codes: 400,500-</pre><p>With the provided configuration, the connector is equipped to automatically retry requests in response to backend responses of 400 or any error codes falling within the range of 500 and above. This retry mechanism is orchestrated up to five times, employing an exponential delay strategy between retries. Specifically, the delays between successive retry attempts are set at intervals of 3 seconds, 6 seconds, 12 seconds, 24 seconds, and 48 seconds, respectively. This progressive delay scheme ensures a measured approach to retrying failed requests, optimizing the chances of successful transmission while mitigating the impact of transient errors.</p><p><strong>Dead Letter Queue (DLQ):</strong> In scenarios where processing failures occur prior to API invocation, the DLQ serves as a safety net, capturing erroneous messages for subsequent analysis. Configurable parameters enable seamless integration and management of DLQ functionality, ensuring comprehensive error logging and monitoring.</p><pre>errors.tolerance: all<br>errors.log.enable: &quot;true&quot;<br>errors.log.include.messages: &quot;true&quot;<br>errors.deadletterqueue.context.headers.enable: &quot;true&quot;<br>errors.deadletterqueue.topic.name: signup.dlq</pre><p>An example DLQ topic message is shown below.</p><p><strong>Error Topic:</strong> Messages failing post-API invocation undergo classification based on HTTP status codes. Those diverging from predefined success criteria (status &gt; 199 &amp;&amp; status &lt; 300)are channeled into an Error topic, facilitating granular error tracking and resolution. However, this validation logic remains hardcoded within the connector, lacking configurable parameters for defining success criteria.</p><p>Here is the configuration to enable Error reporting:</p><pre>reporter.error.topic.name: signup.error</pre><p>An example Error topic message is shown below.</p><p><strong>Success Topic: </strong>When the HTTP response status falls within the range of 200 to 299, signifying a successful operation, the HTTP Sink connector seamlessly directs the message to the Success topic. This dedicated destination serves as a pivotal component in various scenarios, offering both functional and operational benefits.</p><p>Here is the configuration to enable Success reporting:</p><pre>reporter.result.topic.name: signup.success</pre><p>It is crucial to emphasize that the DLQ, Error, and Success topics are established on a per-consumer basis. This means that each consumer within the Kafka ecosystem maintains its own dedicated instances of these topics. By adopting this per-consumer approach, we ensure tailored error handling and processing for individual consumers, thereby optimizing fault tolerance and streamlining troubleshooting efforts.</p><h4>Efficient Message Reprocessing</h4><p>Message reprocessing is a critical aspect of data pipeline maintenance, ensuring timely resolution of processing anomalies and seamless data flow.</p><p>In addressing message processing failures, we have two distinct approaches to reprocessing:</p><ol><li><strong>Source Topic Reprocessing:</strong> This method involves reprocessing messages by resending them directly to the original source topic after identifying and rectifying the underlying issue. Although straightforward, this approach has its drawbacks. Reprocessed messages reintroduced into the source topic risk causing message duplication, potentially impacting other consumers. Consequently, while viable, this method may not be optimal for scenarios where minimizing message duplication is paramount.</li><li><strong>Dedicated Reprocess Topic:</strong> Alternatively, we can opt for a dedicated reprocess topic tailored to each consumer. In this setup, failed messages are redirected to a separate reprocess topic specific to the affected consumer. The HTTP Sink connector is then configured to consume messages from both the source and reprocess topics, enabling targeted reprocessing without compromising the integrity of the source topic. This approach offers a more nuanced and efficient solution, minimizing message duplication and streamlining reprocessing efforts across diverse use cases.</li></ol><p>By carefully evaluating the trade-offs between message duplication and reprocessing efficiency, we can determine the most suitable approach based on their specific requirements and operational constraints.</p><h4>Conclusion</h4><p>In conclusion, the Confluent HTTP Sink connector embodies a robust framework for error handling and message reprocessing within Kafka environments. By leveraging configurable retry mechanisms, DLQ functionality, and dynamic reprocessing strategies, organizations can fortify their data pipelines against unforeseen anomalies and ensure uninterrupted data transmission. Embracing these best practices fosters resilience, agility, and operational excellence, empowering enterprises to harness the full potential of Kafka-based ecosystems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10246f246d99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Message Traceability in Kafka]]></title>
            <link>https://medium.com/gloo-systems/enhancing-message-traceability-in-kafka-d9ef93db30f9?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ef93db30f9</guid>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 17:34:04 GMT</pubDate>
            <atom:updated>2024-02-01T03:16:04.086Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing Correlation IDs for Seamless Troubleshooting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3T6f95hoU3MncEWQ65czQ.png" /></figure><h4>Introduction</h4><p>In the dynamic landscape of enterprise systems, ensuring smooth communication and traceability across multiple components is crucial. This blog post delves into the implementation of Kafka Correlation IDs, offering end-to-end message tracing capabilities. The focus is on a common use case where Database changes trigger a cascade of events, involving Kafka Connect, kSQL, and external Middleware and backend applications, as depicted in the diagram above.</p><h4>Data Flow</h4><p>The depicted diagram outlines a scenario where Database changes initiate a series of actions. A Change Data Capture (CDC) connector in Kafka Connect captures these changes and forwards them to a Kafka topic. A streaming application, such as kSQL, processes these messages and sends them to another Kafka topic. Sink connectors in Kafka Connect then consume these messages and dispatch them to an external HTTP API running in a Middleware like WSO2 Micro Integrator or Mule ESB. The final destination may involve additional backend processing. Depending on the response from the HTTP API, Kafka Connect may produce messages to error topics as well.</p><h4>Navigating Failure Points</h4><p>With multiple systems in play, the potential for failure points increases. To effectively troubleshoot issues, a Correlation ID is essential. Each message entering the system is tagged with a unique UUID, ensuring its propagation through all systems. Correlation IDs are logged by each component, enabling comprehensive analysis in case of failures.</p><h4>Centralized Logging with ELK</h4><p>To facilitate troubleshooting, logs from all systems are centralized using tools like the Elastic Stack (ELK). Searching for a specific Correlation ID in ELK should reveal the entire journey of the corresponding message, pinpointing where and why it failed.</p><p>To elevate the troubleshooting experience, consider forwarding copies of messages from various Kafka topics, including regular, dead-letter queue (DLQ), and error topics, to the ELK stack. This proactive measure ensures a more comprehensive and insightful analysis, allowing for a deeper understanding of the system’s behavior and potential issues.</p><h4>Implementing Correlation IDs in Kafka</h4><p>While many components in the solution naturally support Correlation IDs, Kafka requires a custom implementation. By default, Kafka lacks built-in support for Correlation IDs, necessitating manual implementation.</p><p>The crucial entry point for implementing Correlation IDs is within Kafka producers. These producers must inject the Correlation ID into the header of each produced message. Using headers rather than the message body offers several advantages, including easier inspection and automatic forwarding through Kafka components like topics, streams, and Kafka Connect.</p><h4>Leveraging Single Message Transforms (SMTs)</h4><p>To inject headers in Kafka Connect, Single Message Transforms (SMTs) come into play at the connector level. A custom SMT implementation, such as the provided “InsertUuidHeader,” enables seamless integration into the Kafka Connect environment. The configuration involves specifying the type of transformation and the header name for the Correlation ID.</p><pre>transforms: insertCorrelationId<br>transforms.insertCorrelationId.type: systems.gloo.kafka.connect.transforms.InsertUuidHeader<br>transforms.insertCorrelationId.uuid.header.name: &quot;X-Correlation-ID&quot;</pre><h4>Limitations</h4><p>While the implementation of Correlation IDs significantly enhances traceability, it’s important to note a limitation when using the Confluent HTTP sink connector. This specific connector, when handling messages with distinct Kafka header values, such as the injected UUIDs in our scenario, does not batch requests. Consequently, each message is transmitted individually to the target system, foregoing the usual efficiency gained through request batching. Awareness of this limitation is crucial for optimizing performance expectations, especially in scenarios where large volumes of messages with varying Kafka header values are processed.</p><h4>Closing Thoughts</h4><p>In conclusion, the integration of Correlation IDs in Kafka is a pivotal step towards achieving comprehensive message traceability. This approach ensures that troubleshooting is efficient and effective, even in complex enterprise ecosystems. For those looking to implement Correlation IDs in their Kafka environment, the provided source code is available at [link]. Streamline your system’s traceability and enhance troubleshooting capabilities with Kafka Correlation IDs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ef93db30f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gloo-systems/enhancing-message-traceability-in-kafka-d9ef93db30f9">Enhancing Message Traceability in Kafka</a> was originally published in <a href="https://medium.com/gloo-systems">Gloo Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Centralized Logging for Ballerina Applications Running in Kubernetes Using EFK Stack]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/ballerina-centralized-logging-efk-73b3678de4cb?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b3678de4cb</guid>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[kibana]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 20:41:09 GMT</pubDate>
            <atom:updated>2018-09-17T20:49:23.245Z</atom:updated>
            <content:encoded><![CDATA[<p>After deploying many <a href="http://ballerina.io/">Ballerina</a> Microservices in Kubernetes environment, I’ve been trying setup a centralized logging solution for my Ballerina microservices and ended up with EFK (<strong>Elastic, Fluentd and Kibana</strong>) stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MPp-mVyU-gkk5riSRsncg.png" /></figure><p>If your application in Docker container writes logs to stdout/stderr, they are persisted in <strong>/var/log/containers</strong> directory on the Kubernetes Nodes. Ballerina writes logs to stdout/stderr by default. So I’m going to run Fluentd in every Kubernetes nodes, collect logs from <strong>/var/log/containers </strong>directory<strong> </strong>and send them to Elasticsearch. And then I’m going to use Kibana to visualize the logs.</p><h4>Prerequisites</h4><ul><li>Kubernete cluster. If you don’t have a Kubernetes cluster up and running, go grab my <a href="https://medium.com/@wso2tech/multi-node-kubernetes-cluster-with-vagrant-virtualbox-and-kubeadm-9d3eaac28b98">Vagrantfile</a> and configure a multi node Kubernetes cluster in VirtualBox.</li><li>Local Kubectl should have access to your remote Kubernetes cluster. <br>If you haven’t setup your local Kubectl to access your remote Kubernetes cluster, read my <a href="https://medium.com/@wso2tech/configure-local-kubectl-to-access-remote-kubernetes-cluster-ee78feff2d6d">previous blog</a> and configure it.</li></ul><h4>Deploying Elasticsearch</h4><p>Let’s first deploy Elasticsearch as a StatefulSet.</p><pre><strong>$ kubectl apply -f </strong><a href="https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/es-statefulset.yaml"><strong>https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/es-statefulset.yaml</strong></a><br>serviceaccount/elasticsearch-logging created<br>clusterrole.rbac.authorization.k8s.io/elasticsearch-logging created<br>clusterrolebinding.rbac.authorization.k8s.io/elasticsearch-logging created<br>statefulset.apps/elasticsearch-logging created</pre><p>Let’s verify the deployment.</p><pre>$ <strong>kubectl get statefulsets -n kube-system</strong><br>NAME                    DESIRED   CURRENT   AGE<br>elasticsearch-logging   2         2         3m</pre><pre>$ <strong>kubectl get pods -l k8s-app=elasticsearch-logging -n kube-system</strong><br>NAME                      READY     STATUS    RESTARTS   AGE<br>elasticsearch-logging-0   1/1       Running   0          4m<br>elasticsearch-logging-1   1/1       Running   0          3m</pre><p>Looks good. Let’s deploy a Kubernetes Service to expose the StatefulSet.</p><pre>$ <strong>kubectl apply -f </strong><a href="https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/es-service.yaml"><strong>https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/es-service.yaml</strong></a><br>service/elasticsearch-logging created</pre><p>Let’s verify the deployment.</p><pre>$ <strong>kubectl get svc -l k8s-app=elasticsearch-logging -n kube-system</strong><br>NAME                    TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   <br>elasticsearch-logging   ClusterIP   10.101.152.251   &lt;none&gt;        9200/TCP  </pre><h4>Deploying Fluentd DaemonSet</h4><p>I’m deploying Fluentd as a DaemonSet, because I want this to be scheduled to run on every node and collect logs from Docker containers which is stored in <strong>/var/log/containers </strong>directory on the Kubernetes Nodes.</p><pre>$ <strong>kubectl apply -f </strong><a href="https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/fluentd-es-configmap.yaml"><strong>https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/fluentd-es-configmap.yaml</strong></a><br>configmap/fluentd-es-config-v0.1.5 created</pre><pre>$ <strong>kubectl apply -f </strong><a href="https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/fluentd-es-ds.yaml"><strong>https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/fluentd-es-ds.yaml</strong></a><br>serviceaccount/fluentd-es created<br>clusterrole.rbac.authorization.k8s.io/fluentd-es created<br>clusterrolebinding.rbac.authorization.k8s.io/fluentd-es created<br>daemonset.apps/fluentd-es-v2.2.0 created</pre><p>Let’s verify.</p><pre>$ <strong>kubectl get DaemonSet -n kube-system -l k8s-app=fluentd-es</strong><br>NAME                DESIRED   CURRENT   READY     UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE<br>fluentd-es-v2.2.0   2         2         2         2            2           &lt;none&gt;          58s</pre><pre>$ <strong>kubectl get pods -n kube-system -l k8s-app=fluentd-es</strong><br>NAME                      READY     STATUS    RESTARTS   AGE<br>fluentd-es-v2.2.0-4pmd2   1/1       Running   0          5m<br>fluentd-es-v2.2.0-zx5d9   1/1       Running   0          5m</pre><h4>Deploying Kibana</h4><p>Let’s deploy a Kubernetes Deployment controller for Kibana.</p><pre>$ <strong>kubectl apply -f </strong><a href="https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/kibana-deployment.yaml"><strong>https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/kibana-deployment.yaml</strong></a><br>deployment.apps/kibana-logging created</pre><p>Let’s verify</p><pre>$ <strong>kubectl get deployments -n kube-system -l k8s-app=kibana-logging</strong><br>NAME             DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE<br>kibana-logging   1         1         1            1           4m</pre><pre>$ <strong>kubectl get pods  -n kube-system -l k8s-app=kibana-logging</strong><br>NAME                              READY     STATUS    RESTARTS   AGE<br>kibana-logging-56c4d58dcd-7xfmq   1/1       Running   0          1m</pre><p>Let’s deploy a Kubernetes Service (with NodePort service type) to expose our Kibana deployment.</p><pre>$ <strong>kubectl apply -f </strong><a href="https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/kibana-service.yaml"><strong>https://raw.githubusercontent.com/ecomm-integration-ballerina/efk-stack/master/kibana-service.yaml</strong></a><br>service/kibana-logging created</pre><p>Let’s verify.</p><pre>$ <strong>kubectl get svc  -n kube-system -l k8s-app=kibana-logging</strong><br>NAME             TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)          <br>kibana-logging   NodePort   10.99.67.110   &lt;none&gt;     5601:<strong>32016</strong>/TCP</pre><p>Looks good, we can access Kibana using <strong>http://NodeIP:NodePort</strong>. NodePort is 32016 and NodeIP can be any of the Kubernetes Node IPs (192.168.205.10, 192.168.205.11 and 192.168.205.12)</p><h4>Testing</h4><p>Refer my previous blog on <a href="https://medium.com/@wso2tech/ballerina-kubernetes-d56b35746f4d">Deploying Ballerina Microservices in Kubernetes</a> and deploy a sample Ballerina service in your Kubernetes cluster and generate some logs.</p><p>Load Kibana dashboard using <a href="http://192.168.205.10:32016/app/kibana">http://192.168.205.10:32016/app/kibana</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arj4SVL2u3CCTsdCszUl0g.png" /></figure><p>You can query all the logs from a namespace using the following filter.</p><pre>kubernetes.namespace_name:&quot;my-namespace&quot;</pre><p>My Ballerina service is running in the “utility” namespace, so if I query it using the above filter, I get my Ballerina service logs, as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MPp-mVyU-gkk5riSRsncg.png" /></figure><p>Likewise you can configure different filters — out of scope of this article.</p><h4>Summary</h4><p>Since Ballerina writes logs to stdout/stderr by default, Ballerina service logs are persisted in <strong>/var/log/containers </strong>directory on Kubernetes Nodes. It is very convenient to run a Fluentd process in every Kubernetes Nodes to collect/format the logs and send it to Elasticsearch and then visualize it using Kibana.</p><h4>References</h4><ul><li><a href="https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/fluentd-elasticsearch">https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/fluentd-elasticsearch</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b3678de4cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing and Deploying Ballerina Microservices in Kubernetes in 5 Minutes]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/ballerina-kubernetes-d56b35746f4d?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d56b35746f4d</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[ingress]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 12:13:43 GMT</pubDate>
            <atom:updated>2018-09-17T14:46:07.151Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s easier now than ever before to develop and deploy microservices in containers so quick with <a href="https://ballerina.io/">Ballerina</a>.</p><p>We are going to develop a Ballerina microservice and deploy it in Kubernetes in just 5 minutes. Thanks to Ballerina for making all this possible by providing builtin support for automatically generating Docker and Kubernetes artifacts from the annotations.</p><h4>Prerequisites</h4><ul><li><a href="http://ballerina.io/">Ballerina</a> : If you don’t have Ballerina installed in your system, refer this <a href="https://ballerina.io/learn/getting-started/">official doc</a> and set this up.</li><li><a href="http://kubernetes.io/">Kubernetes</a> : If you don’t have a Kubernetes cluster up and running, go grab my <a href="https://medium.com/@wso2tech/multi-node-kubernetes-cluster-with-vagrant-virtualbox-and-kubeadm-9d3eaac28b98">Vagrantfile</a> and configure a multi node Kubernetes cluster in VirtualBox.</li><li>Local Kubectl should have access to your remote Kubernetes cluster. This is required because we are going to deploy the Kubernetes artifacts from local machine to a remote cluster. If you haven’t set this up, read my <a href="https://medium.com/@wso2tech/configure-local-kubectl-to-access-remote-kubernetes-cluster-ee78feff2d6d">previous blog</a> and do it.</li><li>Understanding of my previous blog on how to deploy <a href="https://medium.com/@wso2tech/ballerina-docker-9e2a51306c3e">Ballerina Microservices in Docker</a> is mandatory.</li></ul><h4>Developing a Ballerina Microservice</h4><p>I’m going to be using the same service that I developed in my previous blog on how to deploy <a href="https://medium.com/@wso2tech/ballerina-docker-9e2a51306c3e">Ballerina Microservices in Docker</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3453449b559a9f6490c1fa8aa6d52cc0/href">https://medium.com/media/3453449b559a9f6490c1fa8aa6d52cc0/href</a></iframe><h4>Generating Kubernetes Artifacts Automatically</h4><p>Ballerina provides builtin support for automatically generating Docker and Kubernetes artifacts as part of the build process. You just need to annotate your Ballerina program with Docker and Kubernetes annotations and Ballerina build process will generate Docker and Kubernetes artifacts for you. Very convenient.</p><p>Let’s annotate our service with Kubernetes annotations. Note that you don’t need docker annotations anymore, because Kubernetes annotations are self-contained and it has its own annotations for generating Dockerfile and Docker image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95693fb9b1e7aab2aa58992b91f9e808/href">https://medium.com/media/95693fb9b1e7aab2aa58992b91f9e808/href</a></iframe><p>Let’s build it and see the outputs.</p><pre>$ <strong>ballerina build utility.bal</strong><br>Compiling source<br>    utility.bal</pre><pre>Generating executable<br>    utility.balx<br> <a href="http://twitter.com/kubernetes">@kubernetes</a>:Service     - complete 1/1<br> <a href="http://twitter.com/kubernetes">@kubernetes</a>:Ingress     - complete 1/1<br> <a href="http://twitter.com/kubernetes">@kubernetes</a>:Deployment     - complete 1/1<br> <a href="http://twitter.com/kubernetes">@kubernetes</a>:Docker     - complete 3/3</pre><pre>Run the following command to deploy the Kubernetes artifacts:<br> kubectl apply -f /Users/raj/projects/medium-blogs/ballerina-in-k8s/kubernetes/</pre><p>This time ballerina build command has done four things for me. 1) It has generated the compiled binary. 2) It has generated the Dockerfile. 3) It has built the Docker image. 4) It has generated the Kubernetes artifacts.</p><pre>$ <strong>tree</strong><br>.<br>├── kubernetes<br>│   ├── docker<br>│   │   └── Dockerfile<br>│   ├── utility_deployment.yaml<br>│   ├── utility_ingress.yaml<br>│   └── utility_svc.yaml<br>├── utility.bal<br>└── utility.balx</pre><pre>$ <strong>docker images</strong><br>REPOSITORY             TAG                 IMAGE ID<br>utility                v3                  a73bbdde85e4</pre><p>Let’s move on to making this Docker image available to our Kubernetes cluster.</p><h4>Loading Docker Image in Kubernetes Cluster</h4><p>Before deploying Kubernetes artifacts, we need to make sure Docker runtime within the Kubernetes cluster is able to find our Docker image.</p><p>If you have a Docker registry (private or DockerHub), you could have annotated your Ballerina program so that it can automatically push the Docker image to the registry for you. Then the Docker runtime within our Kubernetes cluster can pull the image from this Docker registry. I don’t have a Docker registry configured (I could’ve used DockerHub, but I intentionally ignored it to experiment a different way of loading docker images), so I’m going to load the Docker image manually in the Kubernetes nodes.</p><p>Save the Docker image as a tar ball with the following command.</p><pre><strong>$ docker save utility:v3 &gt; utility-v3.tar</strong><br><strong>$ ls</strong><br>kubernetes  <strong>utility-v3.tar</strong> utility.bal utility.balx</pre><p>You have to copy this tar ball to the Kubernetes nodes. You can either scp or utilize the vagrant mounting. If you are using my <a href="https://medium.com/@wso2tech/multi-node-kubernetes-cluster-with-vagrant-virtualbox-and-kubeadm-9d3eaac28b98">Vagrantfile</a> to provision your Kubernetes cluster, your project directory (where the Vagrantfile is located) is mounted to the /vagrant directory of the Kubernetes nodes. In other words, if you place a file in your project directory, you can access it in the /vagrant directory of the Kubernetes nodes.</p><pre>$ <strong>cp utility-v3.tar ../../ecomm-integration-ballerina/kubernetes-cluster/</strong><br>$ <strong>cd ../../ecomm-integration-ballerina/kubernetes-cluster/</strong><br>$ <strong>ls</strong><br>LICENSE          <strong>utility-v3.tar</strong>         Vagrantfile</pre><pre>$ <strong>vagrant ssh k8s-node-1</strong><br>Welcome to Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-134-generic x86_64)</pre><pre>vagrant@k8s-node-1:/vagrant$ <strong>pwd</strong><br>/vagrant<br>vagrant@k8s-node-1:/vagrant$ <strong>ls</strong><br>Vagrantfile <strong>utility-v3.tar</strong></pre><p>Use the following command in Kubernetes nodes to create a Docker image from the tar ball.</p><pre>vagrant@k8s-node-1:/vagrant$ <strong>docker load -i utility-v3.tar</strong><br>c9b26f41504c: Loading layer [==================================================&gt;] 3.584 kB/3.584 kB<br>638d4576a926: Loading layer [==================================================&gt;] 78.62 MB/78.62 MB<br>dd41350bacfe: Loading layer [==================================================&gt;] 47.15 MB/47.15 MB<br>fe07b911d809: Loading layer [==================================================&gt;] 27.65 kB/27.65 kB<br><strong>Loaded image: utility:v3</strong></pre><p>Alright, our Docker image is available in Kubernetes nodes. Now docker pull can locally find our image.</p><pre>vagrant@k8s-node-1:/vagrant$ <strong>docker images</strong><br>REPOSITORY                    TAG                 IMAGE ID     <br>utility                       v3                  a73bbdde85e4      </pre><p>Let’s move on to deploying ballerina-generated Kubernetes artifacts in our Kubernetes cluster.</p><h4>Deploying Kubernetes Deployment</h4><p>Let’s deploy the ballerina-generated Kubernetes Deployment controller (utility_deployment.yaml) and verify everything is okay.</p><pre>$ <strong>kubectl apply -f kubernetes/utility_deployment.yaml</strong><br>deployment.extensions/utility-deployment created</pre><pre>$ <strong>kubectl get deployments</strong><br>NAME                 DESIRED   CURRENT   UP-TO-DATE   AVAILABLE<br>utility-deployment   1         1         1            1</pre><pre>$ <strong>kubectl get rs</strong><br>NAME                            DESIRED   CURRENT   READY     <br>utility-deployment-74d458c6bf   1         1         1         </pre><pre>$ <strong>kubectl get pods</strong><br>NAME                                  READY     STATUS    RESTARTS   <br>utility-deployment-74d458c6bf-lgpd2   1/1       Running   0  <br>        <br>$ <strong>kubectl logs utility-deployment-74d458c6bf-lgpd2</strong><br>ballerina: initiating service(s) in &#39;utility.balx&#39;<br>ballerina: started HTTP/WS endpoint 0.0.0.0:8280</pre><p>All good, our Ballerina microservice is up and running inside a Docker container in a Kubernetes Pod.</p><p>Let’s see a couple of different ways to access our Ballerina microservice running in Kubernetes cluster.</p><blockquote>I’m trying all these different ways just for understanding some Kubernetes stuffs, you can just skip and go to ingress section directly.</blockquote><h4>Accessing Ballerina Microservice via PodIP</h4><p>Let’s get the Pod IP using the following Kubectl command.</p><pre>$ <strong>kubectl get pods -l app=utility -o wide</strong><br>NAME                                  READY     STATUS    RESTARTS   AGE       IP           NODE         NOMINATED NODE<br>utility-deployment-74d458c6bf-lgpd2   1/1       Running   1          21h       <strong>172.16.2.4</strong>   k8s-node-2   &lt;none&gt;</pre><p>172.16.2.4 is the Pod IP. You can also get this using the following command.</p><pre>$ <strong>kubectl get pods -l app=utility -o yaml | grep podIP</strong><br>      cni.projectcalico.org/podIP: 172.16.2.4/32<br>    podIP: <strong>172.16.2.4</strong></pre><p>This IP address is only reachable from your Kubernetes nodes. Send a request to your service in this IP address from one of your Kubernetes nodes.</p><pre>vagrant@k8s-node-2:~$ <strong>curl -i  </strong><a href="http://172.16.2.4:8280/utility/hello"><strong>http://172.16.2.4:8280/utility/hello</strong></a><br>HTTP/1.1 200 OK<br>content-type: text/plain<br>content-length: 31<br>server: ballerina/0.981.1<br>date: Sun, 16 Sep 2018 23:58:11 GMT</pre><pre><strong>Congratulations, let&#39;s dance!</strong></pre><p>Great, it works.</p><p>Hey, but Pods are mortal. They die due to various reasons and will be replaced by new identical Pods with different IPs. So we cannot really use Pod IP to call our service. This is the problem a Kubernetes Service solves.</p><blockquote>A Kubernetes Service is an abstraction which defines a logical set of Pods running somewhere in your cluster, that all provide the same functionality. When created, each Service is assigned a unique IP address (also called clusterIP). This address is tied to the lifespan of the Service, and will not change while the Service is alive. Pods can be configured to talk to the Service, and know that communication to the Service will be automatically load-balanced out to some pod that is a member of the Service.</blockquote><p>There are many different ways (ClusterIP, NodePort, LoadBalancer, ExternalName and Ingress) you can expose Kubernetes Service. We will see couple of them in this blog.</p><p>Let’s create and deploy a Kubernetes Service to expose our Kubernetes Deployment.</p><h4>Deploying Kubernetes Service</h4><p>You’d have noticed earlier in this blog that ballerina build command has automatically generated the Service yaml for us (utility_svc.yaml).</p><p>Let’s deploy this.</p><pre>$ <strong>kubectl apply -f kubernetes/utility_svc.yaml</strong><br>service/utility created</pre><p>Let’s verify.</p><pre>$ <strong>kubectl get svc -l app=utility</strong><br>NAME      TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)<br>utility   NodePort   10.106.85.57   &lt;none&gt;        8280:30438/TCP</pre><p>When you deploy a Kubernetes Service, Kubernetes system creates an Endpoint object behind the scenes and updates it with the Pod IPs. When Pod dies and new Pods are created, this Endpoint object will be updated with new IPs. Alright, essentially it is a mapping between Cluster IP and active Pods’ IPs. When you send a request to the Cluster IP, it will be load balanced to set of Pod IPs.</p><pre>$ <strong>kubectl get ep utility</strong><br>NAME      ENDPOINTS         AGE<br>utility   <strong>172.16.2.4</strong>:8280   12m</pre><p>You can see that the Endpoint has the Pod IP we used a while ago in this blog to access our Ballerina service. If you scale your replicas, you would see new Pod IPs are being added to this Endpoint object. Let’s scale our deployment to 2 replicas and verify a new Pod is created and Endpoint is updated with its IP.</p><pre>$ <strong>kubectl scale deployment utility-deployment --replicas=2</strong><br>deployment.extensions/utility-deployment scaled</pre><pre>$ <strong>kubectl get pods -l app=utility</strong><br>NAME                                  READY     STATUS    RESTARTS<br>utility-deployment-74d458c6bf-gjkvq   1/1       Running   0<br>utility-deployment-74d458c6bf-lgpd2   1/1       Running   1</pre><pre>$ <strong>kubectl get ep utility</strong><br>NAME      ENDPOINTS                         AGE<br>utility   <strong>172.16.1.3</strong>:8280,<strong>172.16.2.4</strong>:8280   25m</pre><p>Let’s move on and see how we can access our service using the Cluster IP of the Service.</p><h4>Accessing Ballerina Microservice via ClusterIP</h4><p>As we saw earlier, we can get the Cluster IP of our Kubernetes Service using following command.</p><pre>$ <strong>kubectl get svc -l app=utility</strong><br>NAME      TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)<br>utility   NodePort   <strong>10.106.85.57</strong>   &lt;none&gt;        8280:30438/TCP </pre><p>10.106.85.57 is the Cluster IP. This IP is reachable only from your Kubernetes nodes. Let’s send a request to our Ballerina service in this IP and verify.</p><pre>vagrant@k8s-node-2:~$ <strong>curl -i </strong><a href="http://10.106.85.57:8280/utility/hello"><strong>http://10.106.85.57:8280/utility/hello</strong></a><br>HTTP/1.1 200 OK<br>content-type: text/plain<br>content-length: 31<br>server: ballerina/0.981.1<br>date: Mon, 17 Sep 2018 00:37:00 GMT</pre><pre><strong>Congratulations, let&#39;s dance!</strong></pre><p>Great, it works.</p><p>Hey, but we still haven’t exposed our Ballerina service outside of our Kubernetes cluster. Let’s move on and see a couple of ways to expose our Kubernetes Service outside the cluster.</p><h4>Accessing Ballerina Microservice via NodePort</h4><p>One of the way to expose your Kubernetes Service onto an external IP address is to use the NodePort service type. If you’d have noticed the ballerina-generated service definition (utility_svc.yaml), you would see I’ve already used NodePort as the service type. So if your Kubernetes nodes has public IPs, your Ballerina service is ready to serve traffic on the internet.</p><blockquote>When you deploy a Kubernetes Service with NodePort service type, it exposes the service on each Kubernetes Node’s IP at a static port (this is called <strong>NodePort</strong>). A <strong>ClusterIP</strong> service, to which the <strong>NodePort</strong> service will route, is automatically created. You’ll be able to contact the <strong>NodePort</strong>service, from outside the cluster, by requesting <strong>&lt;NodeIP&gt;:&lt;NodePort&gt;</strong>.</blockquote><p>When the client sends the request to NodeIP, it is routed to the Cluster IP and from there it is routed to one of Pods (using the Endpoint object mapping).</p><p>Let’s get the Node IP.</p><pre>$ <strong>kubectl get nodes -o yaml | grep IP</strong><br>      projectcalico.org/IPv4Address: 192.168.205.10/24<br>      type: InternalIP<br>      projectcalico.org/IPv4Address: 192.168.205.11/24<br>      type: InternalIP<br>      projectcalico.org/IPv4Address: 192.168.205.12/24<br>      type: InternalIP</pre><p>Let’s get the NodePort of our Kubernetes Service.</p><pre>$ <strong>kubectl get svc utility -o yaml | grep nodePort -C 5</strong><br>  uid: 7b9d09ea-ba0f-11e8-920c-021d76b33cfe<br>spec:<br>  clusterIP: <strong>10.106.85.57</strong><br>  externalTrafficPolicy: Cluster<br>  ports:<br>  - nodePort: <strong>30438</strong><br>    port: 8280<br>    protocol: TCP<br>    targetPort: 8280<br>  selector:<br>    app: utility</pre><p>Let’s send a request to NodeIP:NodePort and see if it works. You can pick any one of the Nodes.</p><pre>$ <strong>curl -i 192.168.205.10:30438/utility/hello</strong><br>HTTP/1.1 200 OK<br>content-type: text/plain<br>content-length: 31<br>server: ballerina/0.981.1<br>date: Mon, 17 Sep 2018 01:27:46 GMT</pre><pre><strong>Congratulations, let&#39;s dance!</strong></pre><p>Great, it works perfect. We just accessed our Ballerina service from outside the Kubernetes cluster.</p><p>I’ll explore how we can expose our Service using LoadBalancer and ExternalName service types in another blog. Lastly let’s see how we can expose our Service using Ingress.</p><h4>Accessing Ballerina Microservice via Ingress</h4><blockquote>Unlike all the above examples, Ingress is not a type of service. Instead, it sits in front of multiple services and act as a “smart router” or entrypoint into your cluster.</blockquote><p>Most importantly, Ingress doesn’t eliminate the need for an external load balancer. You still need to expose your Ingress Controller deployment to the internet using an external load balancer.</p><blockquote>Ingress resources don’t do anything by themselves: they are processed by ingress controllers, which vanilla Kubernetes does not provide by default. Managed Kubernetes providers may pre-install an appropriate ingress controller for you, e.g. Google Kubernetes Engine pre-installs a <a href="https://github.com/kubernetes/ingress-gce">GCE ingress controller</a> which provisions Google Cloud load balancers.</blockquote><p>Let’s deploy Nginx Ingress Controller in our Kubernetes cluster.</p><pre>$ <strong>kubectl apply -f https://raw.githubusercontent.com/ecomm-integration-ballerina/kubernetes-cluster/master/ingress/nginx-ingress.yaml</strong><br>namespace/ingress-nginx created<br>deployment.extensions/default-http-backend created<br>service/default-http-backend created<br>configmap/nginx-configuration created<br>configmap/tcp-services created<br>configmap/udp-services created<br>serviceaccount/nginx-ingress-serviceaccount created<br>clusterrole.rbac.authorization.k8s.io/nginx-ingress-clusterrole created<br>role.rbac.authorization.k8s.io/nginx-ingress-role created<br>rolebinding.rbac.authorization.k8s.io/nginx-ingress-role-nisa-binding created<br>clusterrolebinding.rbac.authorization.k8s.io/nginx-ingress-clusterrole-nisa-binding created<br>deployment.extensions/nginx-ingress-controller created</pre><p>Let’s verify the deployment.</p><pre>$ <strong>kubectl get pods -n ingress-nginx</strong><br>NAME                                        READY     STATUS   <br>default-http-backend-6586bc58b6-fqrzj       1/1       Running            <br>nginx-ingress-controller-6bd7c597cb-4gvw4   1/1       Running          </pre><p>Nginx Ingress Controller and default backend pods are up and running. What is this default backend pod? Nginx requires us to setup a default backend service so that it can fall back when it can’t match any services for the incoming requests. Nginx enforces two requirements on this backend pod that it should return 200 on /healthz endpoint and 404 for any other endpoints. You can verify whether this behavior is provided by the default backend pod. Run following commands from the Kubernetes master node. We are using Cluster IP to access the service.</p><pre>$ <strong>kubectl get svc default-http-backend -n ingress-nginx</strong><br>NAME                   TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE<br>default-http-backend   ClusterIP   10.101.224.131   &lt;none&gt;        80/TCP    18m</pre><pre>$ <strong>curl -i </strong><a href="http://10.101.224.131/healthz"><strong>http://10.101.224.131/healthz</strong></a><br>HTTP/1.1 200 OK<br>Date: Mon, 17 Sep 2018 05:02:46 GMT<br>Content-Length: 2<br>Content-Type: text/plain; charset=utf-8</pre><pre>ok</pre><pre><strong>$ curl -i </strong><a href="http://10.101.224.131/other"><strong>http://10.101.224.131/other</strong></a><br>HTTP/1.1 404 Not Found<br>Date: Mon, 17 Sep 2018 05:02:50 GMT<br>Content-Length: 21<br>Content-Type: text/plain; charset=utf-8</pre><pre>default backend - 404</pre><p>That works as expected.</p><p>Let’s get the IP of the Nginx Controller Pod.</p><pre>$ kubectl <strong>get pods -o wide -n ingress-nginx</strong><br>NAME                                        READY     STATUS    RESTARTS   AGE       IP           NODE         NOMINATED NODE<br>default-http-backend-6586bc58b6-fqrzj       1/1       Running   0          56m       172.16.1.5   k8s-node-1   &lt;none&gt;<br>nginx-ingress-controller-6bd7c597cb-4gvw4   1/1       Running   0          56m       <strong>172.16.1.4</strong>   k8s-node-1   &lt;none&gt;</pre><p>172.16.1.4 is the Nginx Controller Pod IP, this is not reachable from outside the cluster. Anyway, let’s try to access our service via ingress on this IP. We first need to deploy an ingress resource to expose our deployment. Let’s deploy the ballerina-generated ingress resouce.</p><pre>$ <strong>kubectl apply -f kubernetes/utility_ingress.yaml</strong><br>ingress.extensions/utilityep-ingress created</pre><p>Let’s verify.</p><pre>vagrant@k8s-head:~$ <strong>kubectl get ing</strong><br>NAME                HOSTS                   ADDRESS   PORTS     AGE<br>utilityep-ingress   ballerina.gateway.com             80        23m</pre><p>Let’s map this ballerina.gateway.com host entry to Nginx Controller Pod IP in /etc/hosts in one of the Kubernetes nodes.</p><pre>vagrant@k8s-head:~$ <strong>cat /etc/hosts</strong><br>127.0.0.1 localhost<br><strong>172.16.1.4 ballerina.gateway.com</strong></pre><p>From the same Kubernetes node where you mapped /etc/hosts, Let’s send a request to our Ballerina service via ingress.</p><pre>$ <strong>curl -i </strong><a href="http://ballerina.gateway.com/utility/hello"><strong>http://ballerina.gateway.com/utility/hello</strong></a><br>HTTP/1.1 200 OK<br>Server: nginx/1.15.3<br>Date: Mon, 17 Sep 2018 05:47:26 GMT<br>Content-Type: text/plain<br>Content-Length: 31<br>Connection: keep-alive</pre><pre><strong>Congratulations, let&#39;s dance!</strong></pre><p>Great, it works. We’ve just accessed our Ballerina service via ingress. But let’s see how we can access it from outside the cluster.</p><p>As I mentioned earlier, we need to expose our Nginx Ingress Controller deployment to the internet. I don’t have an external load balancer, so I’m going to expose this using NodePort service type. Let’s create and deploy a Kubernetes Service to do so.</p><pre>$ <strong>kubectl apply -f </strong><a href="https://raw.githubusercontent.com/ecomm-integration-ballerina/kubernetes-cluster/master/ingress/nginx-ingress-svc.yaml"><strong>https://raw.githubusercontent.com/ecomm-integration-ballerina/kubernetes-cluster/master/ingress/nginx-ingress-svc.yaml</strong></a><br>service/nginx-ingress created</pre><p>Let’s verify</p><pre>$ <strong>kubectl get svc nginx-ingress -n ingress-nginx</strong><br>NAME            TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)                      <br>nginx-ingress   NodePort   10.102.89.81   &lt;none&gt;        80:30101/TCP,443:30216/TCP </pre><p>Okay, so the NodePort 30101 is for HTTP and 30216 is for HTTPS. And we already know our Kubernetes node IPs (192.168.205.10, 192.168.205.11, 192.168.205.12).</p><p>Let’s map ballerina.gateway.com to one of these IP in our local machine.</p><pre>Rajs-MacBook-Pro:ballerina-in-k8s raj$ <strong>cat /etc/hosts</strong><br>127.0.0.1 localhost<br><strong>192.168.205.10 ballerina.gateway.com</strong></pre><p>Let’s send a request from our local machine.</p><pre>Rajs-MacBook-Pro:ballerina-in-k8s raj$ <strong>curl -i </strong><a href="http://ballerina.gateway.com:30101/utility/hello"><strong>http://ballerina.gateway.com:30101/utility/hello</strong></a><br>HTTP/1.1 200 OK<br>Server: nginx/1.15.3<br>Date: Mon, 17 Sep 2018 05:55:21 GMT<br>Content-Type: text/plain<br>Content-Length: 31<br>Connection: keep-alive</pre><pre><strong>Congratulations, let&#39;s dance!</strong></pre><p>Awesome, we have just accessed our Ballerina service via ingress from outside our cluster.</p><h4>References</h4><ol><li><a href="https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0">Kubernetes NodePort vs LoadBalancer vs Ingress?</a></li><li><a href="https://www.joyfulbikeshedding.com/blog/2018-03-26-studying-the-kubernetes-ingress-system.html">Studying the Kubernetes Ingress System</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d56b35746f4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing and Deploying Ballerina Microservices in Docker in 5 Minutes]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/ballerina-docker-9e2a51306c3e?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2a51306c3e</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Sat, 15 Sep 2018 16:56:13 GMT</pubDate>
            <atom:updated>2018-09-16T00:53:56.958Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s easier now than ever before to develop and deploy microservices so quick with <a href="https://ballerina.io/">Ballerina</a>.</p><p>We are going develop a Ballerina microservice and deploy it in Docker in just 5 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*Jp13XqUhB1-Y2VyPsF0imA.png" /></figure><h4>Prerequisites</h4><ul><li><a href="https://ballerina.io/">Ballerina</a></li><li><a href="https://www.docker.com/">Docker</a></li></ul><h4>Developing a Ballerina Microservice</h4><p>Following is the simple Ballerina rest service that we are going to use in this blog. Learn more from <a href="https://ballerina.io/learn/">official documents</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3453449b559a9f6490c1fa8aa6d52cc0/href">https://medium.com/media/3453449b559a9f6490c1fa8aa6d52cc0/href</a></iframe><p>You can use ballerina run command to compile and deploy this service locally in your laptop.</p><pre>$ <strong>ballerina run utility.bal</strong><br>ballerina: initiating service(s) in &#39;utility.bal&#39;<br>ballerina: started HTTP/WS endpoint 0.0.0.0:8280</pre><p>Service should be up now and listening on your host IP and port 8280. You can send a request and verify.</p><pre>$ <strong>curl -i </strong><a href="http://localhost:8280/utility/hello"><strong>http://localhost:8280/utility/hello</strong></a><br>HTTP/1.1 200 OK<br>content-type: text/plain<br>content-length: 31<br>server: ballerina/0.981.1<br>date: Fri, 14 Sep 2018 22:28:56 -0500</pre><pre><strong>Congratulations, let&#39;s dance!</strong></pre><p>If you want to ship and deploy this service in any other computing system such as bare metal, virtual machine or containers, you would want to generate the compiled binary file (.balx) for the above program. This compiled binary bundles all your packages and their dependencies. You can just run it anywhere, provided that Ballerina is installed there. You can use ballerina build command to generate compiled binary file.</p><pre>$ <strong>ballerina build utility.bal</strong><br>Compiling source<br>    utility.bal</pre><pre>Generating executable<br>    <strong>utility.balx</strong></pre><p>The utility.balx is the compiled binary. You can deploy this compiled binary using ballerina run command. Try deploying it locally in your laptop.</p><pre>$ <strong>ballerina run utility.balx</strong><br>ballerina: initiating service(s) in &#39;utility.balx&#39;<br>ballerina: started HTTP/WS endpoint 0.0.0.0:8280</pre><p>All good, let’s move on to deploying this compiled binary in Docker container.</p><h4>Creating Docker Artifacts Manually : Hard Way</h4><p>Ballerina provides an extremly convenient way of automatically generating Dockerfile. We will see that in detail later in this blog. But for now, let’s try to create Dockerfile manually so that we can understand the process bettter.</p><p>Let’s start by writing a Dockerfile. I’m using ballerina/ballerina:0.981.1 as the base image which has OpenJDK and Ballerina v0.981.1 installed. This is the smallest base image available as of now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b72fae4a4410ec56112e6ab599ac127d/href">https://medium.com/media/b72fae4a4410ec56112e6ab599ac127d/href</a></iframe><p>Above Dockerfile is self explanatory, you just need to copy the compiled binary to the home directory, expose the service port and run the compiled binary using ballerina run command.</p><p>Let’s build the docker image and tag it as utility:v1</p><pre>$ <strong>docker build -t utility:v1 .</strong><br>Sending build context to Docker daemon  9.216kB<br>Step 1/5 : FROM ballerina/ballerina:0.981.1<br> ---&gt; a65975411327<br>...<br>Successfully built 87a50ea2712a<br>Successfully tagged utility:v1</pre><h4>Deploying in Docker</h4><p>Use the following command to deploy a container from the image we’ve built with our service. Port 8281 of the docker host is mapped to port 8280 of the docker container.</p><pre><strong>$ docker run -d -p 8281:8280 --name utility_api utility:v1</strong><br>147a2ea17b08e757894883b49022e975bb69fb6e671b5038b89b3eb778278ec7</pre><p>Use the following command to check if the container is up.</p><pre><strong>$ docker ps</strong><br>CONTAINER ID        IMAGE               COMMAND                  CREATED             <strong>STATUS</strong>              <strong>PORTS</strong>                    NAMES<br>147a2ea17b08        utility:v1          &quot;/bin/sh -c &#39;balleri…&quot;   46 seconds ago      <strong>Up 45 seconds</strong>       <strong>0.0.0.0:8281-&gt;8280/tcp </strong>  utility_api</pre><p>Use the following command to check the service logs inside the docker container. By default Ballerina writes all the logs to stdout and stderr and that is the reason why docker logs shows us the ballerina logs too.</p><pre><strong>$ docker logs utility_api</strong><br>ballerina: initiating service(s) in &#39;utility.balx&#39;<br>ballerina: started HTTP/WS endpoint 0.0.0.0:8280</pre><p>All good, our service is up and running inside the docker container. Send a request and verify.</p><pre><strong>$ curl -i </strong><a href="http://localhost:8281/utility/hello"><strong>http://localhost:8281/utility/hello</strong></a><br>HTTP/1.1 200 OK<br>content-type: text/plain<br>content-length: 31<br>server: ballerina/0.981.1<br>date: Sat, 15 Sep 2018 04:56:07 GMT</pre><pre><strong>Congratulations, let&#39;s dance!</strong></pre><p>Let’s now move on to generating docker files automatically using Ballerina’s builtin docker annotations.</p><h4>Generating Docker Artifacts Automatically : Easy Way</h4><p>Ballerina provides builtin support for automatically generating Docker and Kubernetes artifacts as part of the build process. You just need to annotate your Ballerina program with Docker and Kubernetes annotations and Ballerina build process will generate Docker and Kubernetes artifacts for you. Very convenient.</p><p>Here is how you need to annotate your Ballerina program with docker annotations. See <a href="https://github.com/ballerinax/docker">here</a> for the list of supported annotations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/375eae79f31e429f3f5883a0b85ace95/href">https://medium.com/media/375eae79f31e429f3f5883a0b85ace95/href</a></iframe><p>Let’s build this updated program and see the outputs.</p><pre><strong>$ ballerina build utility.bal</strong><br>Compiling source<br>    utility.bal</pre><pre>Generating executable<br>    utility.balx<br> <a href="http://twitter.com/docker">@docker</a>    - complete 3/3</pre><pre>Run the following command to start a Docker container:<br> docker run -d -p 8280:8280 utility:v2</pre><p>Let’s have a look at the generated files.</p><pre><strong>$ tree</strong><br>.<br>├── docker<br>│   └── Dockerfile<br>├── utility.bal<br>└── utility.balx</pre><pre>1 directory, 3 files</pre><p>This time ballerina build command has done three things for me. 1) It has generated the compiled binary as we’ve already seen earlier. 2) It also has generated the Dockerfile for me. This Dockerfile is excatly same as the Dockerfile we created manually earlier in this blog.</p><pre><strong>$ cat docker/Dockerfile</strong><br># Auto Generated Dockerfile</pre><pre>FROM ballerina/ballerina:0.981.1<br>LABEL maintainer=&quot;<a href="/service/mailto:dev@ballerina.io">dev@ballerina.io</a>&quot;</pre><pre>COPY utility.balx /home/ballerina</pre><pre>EXPOSE  8280</pre><pre>CMD ballerina run utility.balx</pre><p>3) Additionally, it has built the docker image too for me. The utility:v2 docker image was automatically built by ballerina build command.</p><pre><strong>$ docker images</strong><br>REPOSITORY             TAG                 IMAGE ID            <br><strong>utility                v2                  1c5c9f5196b8</strong><br>utility                v1                  87a50ea2712a</pre><p>You can deploy a container from utility:v2 docker image. Use a different name and port mapping than what we used earlier in the blog.</p><pre><strong>$ docker run -d -p 8282:8280 --name utility_api_2 utility:v2</strong><br>f621409f585ff42aeabaa042140e51469bffd40ac03edf98a495f4267645142e</pre><p>See if the logs looks okay.</p><pre><strong>$ docker logs utility_api_2<br></strong>ballerina: initiating service(s) in &#39;utility.balx&#39;<br>ballerina: started HTTP/WS endpoint 0.0.0.0:8280</pre><p>Send a request and verify if service works okay.</p><pre><strong>$ curl -i </strong><a href="http://localhost:8282/utility/hello"><strong>http://localhost:8282/utility/hello</strong></a><strong><br></strong>HTTP/1.1 200 OK<br>content-type: text/plain<br>content-length: 31<br>server: ballerina/0.981.1<br>date: Sat, 15 Sep 2018 05:25:03 GMT</pre><pre><strong>Congratulations, let&#39;s dance!</strong></pre><h4>Summary</h4><p>Ballerina provides awesome builtin support for</p><ul><li>Dockerfile generation using @docker:* annotations.</li><li>Docker image generation.</li><li>Docker push support with docker registry.</li><li>Docker based ballerina debug support.</li><li>Copying files to containers.</li></ul><p>Learn more about Ballerina’s builtin Docker support <a href="https://github.com/ballerinax/docker">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2a51306c3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configure Local Kubectl to Access Remote Kubernetes Cluster]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/configure-local-kubectl-to-access-remote-kubernetes-cluster-ee78feff2d6d?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee78feff2d6d</guid>
            <category><![CDATA[vagrant]]></category>
            <category><![CDATA[kubeadm]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 17:23:51 GMT</pubDate>
            <atom:updated>2019-11-01T15:19:48.620Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/@wso2tech/multi-node-kubernetes-cluster-with-vagrant-virtualbox-and-kubeadm-9d3eaac28b98">previous post</a>, I explained how to configure a multi node Kubernetes cluster using Vagrant, VirtualBox and Kubeadm. Today I’m trying to get my local Kubectl running on my Macbook to access the remote Kubernetes cluster running on VirtualBox. This way I don’t need to ssh into Kubernetes master to run Kubectl. Very convenient. Here is how I did it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txtpUibnVfZS2ZYzbf1UhQ.png" /></figure><h4>Step-1 : Install Kubectl in Macbook</h4><p>You can install Kubectl in Macbook using Homebrew with the following command.</p><pre>brew install kubernetes-cli</pre><p>Now if you run kubectl version command in your Macbook terminal, you will get some errors like below.</p><pre>Rajs-MacBook-Pro:.kube raj$ kubectl version<br>Client Version: version.Info{Major:&quot;1&quot;, Minor:&quot;11&quot;, GitVersion:&quot;v1.11.2&quot;, GitCommit:&quot;bb9ffb1654d4a729bb4cec18ff088eacc153c239&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2018-08-08T16:31:10Z&quot;, GoVersion:&quot;go1.10.3&quot;, Compiler:&quot;gc&quot;, Platform:&quot;darwin/amd64&quot;}<br><strong>The connection to the server localhost:8080 was refused - did you specify the right host or port?</strong></pre><p>Kubectl in my Macbook is trying to connect to the local Kubernetes master and failing because I do not have any local Kubernetes cluster running on my Macbook. Now let’s see how I can point my Kubectl to a remote Kubernetes master.</p><h4>Step-2 : Download Kubernetes Credentials From Remote Cluster</h4><p>You need to first copy some Kubernetes credentials from remote Kubernetes master to your Macbook.</p><pre>scp -r vagrant@192.168.205.10:/home/vagrant/.kube .</pre><h4>Step-3 : Copy Kubernetes Credentials To Your Home</h4><p>Copy the Kubernetes Credentials your downloaded to your home directory as shown below.</p><pre>cp -r .kube $HOME/</pre><p>That’s all you have to do. Your local Kubectl should be able to connect with the remote Kubernetes cluster now.</p><p>Now if you run kubectl version command in your Macbook terminal, you will get successfully connected to remote Kubernetes master and the output will be like this.</p><pre>Rajs-MacBook-Pro:.kube raj$ kubectl version<br>Client Version: version.Info{Major:&quot;1&quot;, Minor:&quot;11&quot;, GitVersion:&quot;v1.11.2&quot;, GitCommit:&quot;bb9ffb1654d4a729bb4cec18ff088eacc153c239&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2018-08-08T16:31:10Z&quot;, GoVersion:&quot;go1.10.3&quot;, Compiler:&quot;gc&quot;, Platform:&quot;darwin/amd64&quot;}<br><strong>Server Version: version.Info{Major:&quot;1&quot;, Minor:&quot;11&quot;, GitVersion:&quot;v1.11.2&quot;, GitCommit:&quot;bb9ffb1654d4a729bb4cec18ff088eacc153c239&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2018-08-07T23:08:19Z&quot;, GoVersion:&quot;go1.10.3&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;}</strong></pre><p>Run kubectl get nodescommand in your Macbook terminal and verify you can list your remote cluster nodes.</p><pre>Rajs-MacBook-Pro:kubernetes-cluster raj$ kubectl get nodes<br>NAME         STATUS    ROLES     AGE       VERSION<br>k8s-head     Ready     master    4d        v1.11.2<br>k8s-node-1   Ready     &lt;none&gt;    4d        v1.11.2<br>k8s-node-2   Ready     &lt;none&gt;    4d        v1.11.2</pre><p>Follow me on Twitter <a href="https://twitter.com/raj10x">@raj10x</a> for latest blogs!</p><figure><a href="https://twitter.com/raj10x"><img alt="" src="https://cdn-images-1.medium.com/max/771/1*ZVSBo3C13iGOU3Ur0J5qXA.png" /></a></figure><p><a href="https://twitter.com/raj10x">Raj Rajaratnam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee78feff2d6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi Node Kubernetes Cluster with Vagrant, VirtualBox and Kubeadm]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/multi-node-kubernetes-cluster-with-vagrant-virtualbox-and-kubeadm-9d3eaac28b98?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d3eaac28b98</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubeadm]]></category>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[virtualbox]]></category>
            <category><![CDATA[vagrant]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Wed, 05 Sep 2018 20:17:12 GMT</pubDate>
            <atom:updated>2019-11-01T15:20:17.722Z</atom:updated>
            <content:encoded><![CDATA[<p>TL;DR, Go grab my Vagrantfile at <a href="https://github.com/ecomm-integration-ballerina/kubernetes-cluster">https://github.com/ecomm-integration-ballerina/kubernetes-cluster</a> and run vagrant up to bring a 3 node Kubernetes cluster up and running in VirtualBox.</p><p>I have been trying to setup a multi node Kubernetes cluster to try out <a href="https://ballerina.io/">Ballerina</a> integrations at scale in containers.</p><p>There are many third party tools to setup a Kubernetes cluster. I’ve looked at two options, Minikube and Kubeadm. Minikube doesn’t support multi node setup, so I picked Kubeadm. Kubeadm is still in beta, do not use it in production.</p><p>I followed <a href="https://kubernetes.io/docs/setup/independent/install-kubeadm/">Kubeadm</a> guide and setup a three node cluster (single master and two nodes) manually first and then automated in Vagrant because I can recreate the cluster easily later with no effort.</p><p>So here is how I did it. Try it, create issues in my <a href="https://github.com/ecomm-integration-ballerina/kubernetes-cluster">repo</a> and send pull requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxBqMYeNb5WhhnZEZtKC7A.png" /></figure><blockquote>Note: Step-1 to Step-8 should be done in all the Kubernetes nodes (master + nodes). Step-9 to Step-12 should be done in Kubernetes master. Step-13 should be done in Kubernetes nodes.</blockquote><h4>Step-1: Pick a base box for Kubernetes nodes</h4><pre>config.vm.box = &quot;ubuntu/xenial64&quot;<br>config.vm.box_version = &quot;20180831.0.0&quot;</pre><h4>Step-2: Setup a network</h4><pre>config.vm.network :private_network, ip: &quot;192.168.205.10&quot;</pre><h4>Step-3: Setup memory and CPUs</h4><pre>v.customize [&quot;modifyvm&quot;, :id, &quot;--memory&quot;, &quot;2048&quot;]<br>v.customize [&quot;modifyvm&quot;, :id, &quot;--cpus&quot;, &quot;2&quot;]</pre><h4>Step-4: Install Docker</h4><p>I’m not going to use vagrant docker provisioning because it always installs the latest version, but Kubeadm requires 17.03 or older. So I’m going to use shell provisioning to install docker.</p><pre>apt-get update<br>apt-get install -y apt-transport-https ca-certificates curl software-properties-common<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -<br>add-apt-repository &quot;deb https://download.docker.com/linux/$(. /etc/os-release; echo &quot;$ID&quot;) $(lsb_release -cs) stable&quot;<br>apt-get update &amp;&amp; apt-get install -y docker-ce=$(apt-cache madison docker-ce | grep 17.03 | head -1 | awk &#39;{print $3}&#39;)</pre><h4>Step-5: Allow regular user to run docker commands</h4><p>I’m adding the regular user (vagrant) to the docker user group so that I can run docker commands as vagrant user without sudo privileges.</p><pre>usermod -aG docker vagrant</pre><h4>Step-6: Install Kubeadm, Kubelet and Kubctl</h4><p>I’m using shell provisioning to install Kubeadm, Kubelet and Kubectl from the repositories.</p><pre>    apt-get install -y apt-transport-https curl<br>    curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -<br>    cat &lt;&lt;EOF &gt;/etc/apt/sources.list.d/kubernetes.list<br>    deb http://apt.kubernetes.io/ kubernetes-xenial main<br>EOF<br>    apt-get update<br>    apt-get install -y kubelet kubeadm kubectl<br>    apt-mark hold kubelet kubeadm kubectl</pre><h4>Step-7: Kubelet requires swap to be disabled</h4><p>Running following bash command will disable the swap in the current login session.</p><pre>swapoff -a</pre><h4>Step-8: Disable swap permanently</h4><p>Following change will keep swap off after reboot too</p><pre>sudo sed -i &#39;/ swap / s/^\(.*\)$/#\1/g&#39; /etc/fstab</pre><h4>Step-9: Initialize Kubernetes master</h4><p>Following Kubeadm command will install and configure a Kubernetes master.</p><pre># ip of this box<br>IP_ADDR=`ifconfig enp0s8 | grep Mask | awk &#39;{print $2}&#39;| cut -f2 -d:`<br><br># install k8s master<br>HOST_NAME=$(hostname -s)<br>kubeadm init --apiserver-advertise-address=$IP_ADDR --apiserver-cert-extra-sans=$IP_ADDR  --node-name $HOST_NAME --pod-network-cidr=192.168.0.0/16</pre><h4>Step-10: Allow regular user to run Kubectl commands</h4><p>I’m going to copy the Kubectl credentials to vagrant user’s home directory to be able to run Kubectl commands without sudo privileges.</p><pre>#copying credentials to regular user - vagrant<br>sudo --user=vagrant mkdir -p /home/vagrant/.kube<br>cp -i /etc/kubernetes/admin.conf /home/vagrant/.kube/config<br>chown $(id -u vagrant):$(id -g vagrant) /home/vagrant/.kube/config</pre><h4>Step-11: Install a Pod Network</h4><p>We need to install a Pod Network to enable pod-to-pod communication in our Kubernetes cluster. There are many third party Pod Network projects such as Calico, Flannel and Weave. I’ve tried to use Weave, but looks like there are some bugs that prevent a Weave pod to be scheduled on Kubenetes nodes. Then I’ve tried Calico and it works fine so far.</p><pre># install Calico pod network addon<br>export KUBECONFIG=/etc/kubernetes/admin.conf<br>kubectl apply -f https://docs.projectcalico.org/v3.1/getting-started/kubernetes/installation/hosted/rbac-kdd.yaml<br>kubectl apply -f https://docs.projectcalico.org/v3.1/getting-started/kubernetes/installation/hosted/kubernetes-datastore/calico-networking/1.7/calico.yaml</pre><h4>Step-12: Save the Kubeadm join commands</h4><p>Our Kubernetes master should be up and running by now. We can join Kubernetes nodes to master using Kubeadm join command. You can run kubeadm token create — print-join-command in Kubernetes master to get the join command that should be executed in Kubernetes nodes.</p><p>I’m going to store the output of this command in a file in Kubernetes master. Later I’m going to download this file from inside Kubernetes nodes, execute and join the cluster.</p><pre>kubeadm token create --print-join-command &gt;&gt; /etc/kubeadm_join_cmd.sh<br>chmod +x /etc/kubeadm_join_cmd.sh</pre><h4>Step-13: Execute Kubeadm join command in Kubernetes nodes</h4><p>What I’m doing here is to scp the above kubeadm_join_cmd.sh from master to nodes and execute it. I’m using sshpass to run prompt-less scp command in bash.</p><pre>apt-get install -y sshpass<br>sshpass -p &quot;vagrant&quot; scp -o StrictHostKeyChecking=no vagrant@192.168.205.10:/etc/kubeadm_join_cmd.sh .<br>sh ./kubeadm_join_cmd.sh</pre><p>That’s all, your cluster should be up and running now.</p><h4>Putting it all together</h4><p>Here is my full Vagrantfile gist. But be sure check <a href="https://github.com/ecomm-integration-ballerina/kubernetes-cluster">my repo</a> to get the up-to-date Vagrant file. Run vagrant up to bring up a 3 node Kubernetes cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93dc7e7cd99e0724af5dc426b499b37/href">https://medium.com/media/f93dc7e7cd99e0724af5dc426b499b37/href</a></iframe><p>Follow me on Twitter <a href="https://twitter.com/raj10x">@raj10x</a> for latest blogs!</p><figure><a href="https://twitter.com/raj10x"><img alt="" src="https://cdn-images-1.medium.com/max/771/1*ZVSBo3C13iGOU3Ur0J5qXA.png" /></a></figure><p><a href="https://twitter.com/raj10x">Raj Rajaratnam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d3eaac28b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manipulating scoped properties in Prototyped APIs in WSO2 API Manager]]></title>
            <link>https://medium.com/@rajkumar.rajaratnam/manipulating-scoped-properties-in-prototyped-apis-in-wso2-api-manager-417fedf4d3f3?source=rss-9072b29ccdd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/417fedf4d3f3</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[wso2]]></category>
            <category><![CDATA[apim]]></category>
            <dc:creator><![CDATA[Rajkumar Rajaratnam]]></dc:creator>
            <pubDate>Thu, 02 Aug 2018 18:58:36 GMT</pubDate>
            <atom:updated>2019-11-01T15:18:25.256Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note: In this article, I’m explaining a specific usecase where you want to extend the extend the API prototyping capabilities of WSO2 API Manager, but the same concept applies to any other usecases.</em></p><p>WSO2 API Manager allows you to deploy API prototypes for the purpose of early promotion and testing. You can deploy a new API or a new version of an existing API as a prototype. It gives subscribers an early implementation of the API that they can try out without a subscription or monetization, and provide feedback to improve. After a period of time, publishers can make changes the users request and publish the API.</p><p>When we implement a prototyped API with advanced usecases, we may find some gaps in the out of the box capabilities provided by prototyped APIs. To name a few;</p><ul><li>We can’t read incoming HTTP headers in prototyped APIs</li><li>We can’t set outgoing HTTP headers in prototyped APIs</li></ul><p>This blog post explains how we can extend API Manager to manipulate scoped properties in prototyped APIs. Doing so will allow us to do some advanced stuffs in prototyped APIs including but not limited to read incoming or set outgoing HTTP headers.</p><h4>Internals</h4><p>Before diving into the details, let’s know some internals which will help us to understand the solution;</p><ul><li>Prototyped API’s core capability is implemented using <a href="https://docs.wso2.com/display/ESB490/Script+Mediator">script mediator</a></li><li>Only the properties set in the default context (a.k.a scope) can be manipulated using the script mediator. Properties set in other <a href="http://soatutorials.blogspot.com/2014/03/wso2-esb-properties-tutorial.html">contexts</a> (transport and axis2) can be manipulated using a <a href="https://docs.wso2.com/display/ESB490/Sequence+Mediator">sequence mediator</a></li><li>Incoming HTTP headers will be available as transport scoped properties in the mediation engine. We can access them using $trp:headerName</li><li>If you create a property with transport scope, it will be sent as an outgoing HTTP header.</li><li>There are some <a href="https://docs.wso2.com/display/ESB490/HTTP+Transport+Properties#HTTPTransportProperties-HTTP_SC">special properties</a> in axis2 scope like HTTP_SC that can be used to set the HTTP Status Code of the response.</li><li>API Manager (Publisher UI, to be accurate) doesn’t support attaching a mediation sequence to a prototyped API.</li><li>Prototyped API’s definition (what should be included in api.xml deployed to Gateway) is determined by APIM_HOME/repository/resources/api_templates/prototype_template.xml</li><li>When we deploy a prototyped API from Publisher UI, it creates the API definition based on prototype_template.xml together with the information provided in the Publisher UI and deploy it to Gateway. This process happens everytime we redeploy the API. Hence, manual changes we do to the API definition in the Gateway will be overwritten when we redeploy the API next time.</li><li>Prototype_template.xml can be updated to include additional mediators we want in the prototyped APIs.</li></ul><p>Let’s come up with a use-case for a prototyped API.</p><h4>Utility API</h4><p>The Utility API is a prototyped API, deployed for our customers who want to check the connectivity with our API Management platform.</p><p>Customers send the following request with Content-Type: application/json header;</p><p>{ “request”: “hello” }</p><p>And they receive the following response with 200 HTTP Status Code;</p><p>{ “response”: “hello” }</p><p>If they don’t send Content-Type: application/json header, they receive the following response with 400 HTTP Status Code;</p><p>{ “response”: “bad request” }</p><p>Let’s create the Utility API with POST /hello resource and embedded above logic in the inline script, as shown below.</p><pre>var reqPayload = mc.getPayloadJSON();</pre><pre>var resPayload = {};<br>if (mc.getProperty(&#39;Content-Type&#39;) == &#39;application/json&#39;) {<br>     resPayload = {&quot;response&quot;: reqPayload.request};<br>     mc.setProperty(&quot;HTTP_SC&quot;, &quot;200&quot;);<br>} else {<br>     resPayload = {&quot;response&quot;: &quot;bad request&quot;};<br>     mc.setProperty(&quot;HTTP_SC&quot;, &quot;400&quot;);<br>}</pre><pre>mc.setPayloadJSON(resPayload);<br>mc.setProperty(&#39;CONTENT_TYPE&#39;, &#39;application/json&#39;);</pre><p>After deploying this as a prototyped API, let’s have look at the API artifact in the Gateway, at APIM_HOME/repository/deployment/server/synapse-configs/default/api/admin--Utility_v1.0.xml. Note that the API name is prefixed with the provider name who created the API.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;api xmlns=&quot;<a href="http://ws.apache.org/ns/synapse">http://ws.apache.org/ns/synapse</a>&quot; name=&quot;admin--Utility&quot; context=&quot;/utility/1.0&quot; version=&quot;1.0&quot; version-type=&quot;context&quot;&gt;<br>   &lt;resource methods=&quot;POST&quot; url-mapping=&quot;/hello&quot; faultSequence=&quot;fault&quot;&gt;<br>      &lt;inSequence&gt;<br>         &lt;script language=&quot;js&quot;&gt;<br>            var reqPayload = mc.getPayloadJSON();<br>            <br>            var resPayload = {};<br>            if (mc.getProperty(&#39;Content-Type&#39;) == &#39;application/json&#39;) {    <br>              resPayload = {&quot;response&quot;: reqPayload.request};    <br>              mc.setProperty(&quot;HTTP_SC&quot;, &quot;200&quot;);<br>            } else {    <br>              resPayload = {&quot;response&quot;: &quot;bad request&quot;};    <br>              mc.setProperty(&quot;HTTP_SC&quot;, &quot;400&quot;);<br>            }</pre><pre>            mc.setPayloadJSON(resPayload);<br>            mc.setProperty(&#39;CONTENT_TYPE&#39;, &#39;application/json&#39;);<br>          &lt;/script&gt;<br>         &lt;filter source=&quot;boolean(get-property(&#39;CONTENT_TYPE&#39;))&quot; regex=&quot;false&quot;&gt;<br>            &lt;then&gt;<br>               &lt;property name=&quot;messageType&quot; value=&quot;application/xml&quot; scope=&quot;axis2&quot; /&gt;<br>            &lt;/then&gt;<br>            &lt;else&gt;<br>               &lt;property name=&quot;messageType&quot; expression=&quot;get-property(&#39;CONTENT_TYPE&#39;)&quot; scope=&quot;axis2&quot; /&gt;<br>            &lt;/else&gt;<br>         &lt;/filter&gt;<br>         &lt;respond /&gt;<br>      &lt;/inSequence&gt;<br>      &lt;outSequence&gt;<br>         &lt;send /&gt;<br>      &lt;/outSequence&gt;<br>   &lt;/resource&gt;<br>   &lt;handlers&gt;<br>      &lt;handler class=&quot;org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler&quot;&gt;<br>         &lt;property name=&quot;apiImplementationType&quot; value=&quot;INLINE&quot; /&gt;<br>      &lt;/handler&gt;<br>   &lt;/handlers&gt;<br>&lt;/api&gt;</pre><p>Pretty straightforward API definition. A script mediator followed by couple of filter and property mediators. As I mentioned earlier, the content of API definition is generated based on prototype_template.xml. If we want to include an additional mediator in the flow, we would update prototype_template.xml.</p><p>We are not done yet. Even if we now send the request as{ “request”: “hello” } with Content-Type: application/json, we will get { “response”: “bad request” } as response. Reason is that the transport or axix2 scope properties can’t be manipulated (get or set) in script mediator.</p><p>Let’s see how we can update prototype_template.xml to include two sequence mediators in prototyped API definition, one before script mediator and another one after the script mediator. We are doing this because we can manipulate transport or axis2 scope properties in a sequence mediator.</p><h4>Updating prototype_template.xml</h4><p>Let’s open APIM_HOME/repository/resources/api_templates/prototype_template.xml in <strong>Publisher</strong> node, search for “script” and find a script mediator definition. There will be only one script mediator by default. Let’s add two sequence mediators before and after the script mediator, as shown below. API details like name, version, context, etc are available inside the template, hence we are using them (!apiName and !apiVersion) to name our sequences. In other words, we are engaging sequences in API level, not globally.</p><pre><strong><em>#set ($beforeScriptSeqKey = &quot;--beforeScript_v&quot;)<br>#set ($beforeScriptSeqKey = &quot;$!apiName$beforeScriptSeqKey$!apiVersion&quot;)<br>&lt;sequence key=&quot;$beforeScriptSeqKey&quot;/&gt;</em></strong><br>#if(!$resource.getMediationScript().equalsIgnoreCase(&quot;null&quot;))<br>    &lt;script language=&quot;js&quot;&gt;<br>        &lt;![CDATA[<br>                        $resource.getMediationScript()<br>                ]]&gt;<br>    &lt;/script&gt;<br><strong><em>#set ($afterScriptSeqKey = &quot;--afterScript_v&quot;)<br>#set ($afterScriptSeqKey = &quot;$!apiName$afterScriptSeqKey$!apiVersion&quot;)<br>&lt;sequence key=&quot;$afterScriptSeqKey&quot;/&gt;</em></strong></pre><p>I reiterate that we need to do this change in Publisher node, not Gateway.</p><p>Let’s redeploy the API in Publisher UI and have look at the API artifact in the Gateway, at APIM_HOME/repository/deployment/server/synapse-configs/default/api/admin--Utility_v1.0.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;api xmlns=&quot;<a href="http://ws.apache.org/ns/synapse">http://ws.apache.org/ns/synapse</a>&quot; name=&quot;admin--Utility&quot; context=&quot;/utility/1.0&quot; version=&quot;1.0&quot; version-type=&quot;context&quot;&gt;<br>   &lt;resource methods=&quot;POST&quot; url-mapping=&quot;/hello&quot; faultSequence=&quot;fault&quot;&gt;<br>      &lt;inSequence&gt;<br>         <strong><em>&lt;sequence key=&quot;admin--Utility--beforeScript_v1.0&quot;/&gt;</em></strong><br>         &lt;script language=&quot;js&quot;&gt;<br>            var reqPayload = mc.getPayloadJSON();<br>            <br>            var resPayload = {};<br>            if (mc.getProperty(&#39;Content-Type&#39;) == &#39;application/json&#39;) {    <br>              resPayload = {&quot;response&quot;: reqPayload.request};    <br>              mc.setProperty(&quot;HTTP_SC&quot;, &quot;200&quot;);<br>            } else {    <br>              resPayload = {&quot;response&quot;: &quot;bad request&quot;};    <br>              mc.setProperty(&quot;HTTP_SC&quot;, &quot;400&quot;);<br>            }</pre><pre>            mc.setPayloadJSON(resPayload);<br>            mc.setProperty(&#39;CONTENT_TYPE&#39;, &#39;application/json&#39;);<br>          &lt;/script&gt;<br>         <strong><em> &lt;sequence key=&quot;admin--Utility--afterScript_v1.0&quot;/&gt;</em></strong><br>          &lt;filter source=&quot;boolean(get-property(&#39;CONTENT_TYPE&#39;))&quot; regex=&quot;false&quot;&gt;<br>            &lt;then&gt;<br>               &lt;property name=&quot;messageType&quot; value=&quot;application/xml&quot; scope=&quot;axis2&quot; /&gt;<br>            &lt;/then&gt;<br>            &lt;else&gt;<br>               &lt;property name=&quot;messageType&quot; expression=&quot;get-property(&#39;CONTENT_TYPE&#39;)&quot; scope=&quot;axis2&quot; /&gt;<br>            &lt;/else&gt;<br>         &lt;/filter&gt;<br>         &lt;respond /&gt;<br>      &lt;/inSequence&gt;<br>      &lt;outSequence&gt;<br>         &lt;send /&gt;<br>      &lt;/outSequence&gt;<br>   &lt;/resource&gt;<br>   &lt;handlers&gt;<br>      &lt;handler class=&quot;org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler&quot;&gt;<br>         &lt;property name=&quot;apiImplementationType&quot; value=&quot;INLINE&quot; /&gt;<br>      &lt;/handler&gt;<br>   &lt;/handlers&gt;<br>&lt;/api&gt;</pre><p>We can see a sequence mediator &lt;sequence key=”admin--Utility--beforeScript_v1.0&quot;/&gt; is added before script mediator and another sequence mediator &lt;sequence key=”admin--Utility--afterScript_v1.0&quot;/&gt; is added after the script mediator automatically.</p><p>Now we have to create and deploy these two sequences and deploy in Gateway manually. We can use puppet to automate the deployment.</p><h4>Creating sequences</h4><p>Let’s create admin--Utility--beforeScript_v1.0.xml with the following content and deploy it to Gateway, at APIM_HOME/repository/deployment/server/synapse-configs/default/sequences</p><pre>&lt;sequence xmlns=&quot;<a href="http://ws.apache.org/ns/synapse">http://ws.apache.org/ns/synapse</a>&quot; name=&quot;admin--Utility--beforeScript_v1.0&quot;&gt;<br>  &lt;property name=&quot;Content-Type&quot; expression=&quot;$trp:Content-Type&quot;/&gt;<br>  &lt;log level=&quot;custom&quot;&gt;<br>    &lt;property name=&quot;where&quot; expression=&quot;fn:concat(&#39;admin-Utility-beforeScript_v1.0: &#39;, $ctx:Content-Type)&quot;/&gt;<br>  &lt;/log&gt;<br>&lt;/sequence&gt;</pre><p>What we are doing here is that we are reading the value of Content-Type property in transport scope and set it to Content-Type property in default scope so that it can be manipulated in script mediator.</p><p>Let’s create admin--Utility--afterScript_v1.0.xml with the following content and deploy it to Gateway, at APIM_HOME/repository/deployment/server/synapse-configs/default/sequences</p><pre>&lt;sequence xmlns=&quot;<a href="http://ws.apache.org/ns/synapse">http://ws.apache.org/ns/synapse</a>&quot; name=&quot;admin--Utility--afterScript_v1.0&quot;&gt;<br>  &lt;property name=&quot;HTTP_SC&quot; expression=&quot;$ctx:HTTP_SC&quot; scope=&quot;axis2&quot;/&gt;<br>  &lt;log level=&quot;custom&quot;&gt;<br>    &lt;property name=&quot;where&quot; expression=&quot;fn:concat(&#39;admin-Utility-afterScript_v1.0: &#39;, $axis2:HTTP_SC)&quot;/&gt;<br>  &lt;/log&gt;<br>&lt;/sequence&gt;</pre><p>What we are doing here is that we are reading the value of HTTP_SC property in default scope and set it to HTTP_SC property in axis2 scope so that it will be sent as the HTTP Status Code to the client.</p><h4>Testing</h4><p>Send the request { “request”: “hello” }with Content-Type: application/json and you will get the response { “response”: “hello” } with 200 HTTP Status Code</p><pre>Rajs-MacBook-Pro:sequences raj$ curl -v -X POST --header &quot;Content-Type: application/json&quot; --header &quot;Accept: application/json&quot; -d &#39;{&quot;request&quot;:&quot;hello&quot;}&#39; &quot;<a href="http://127.0.0.1:8280/utility/1.0/hello">http://127.0.0.1:8280/utility/1.0/hello</a>&quot;<br><br>*   Trying 127.0.0.1...<br>* TCP_NODELAY set<br>* Connected to 127.0.0.1 (127.0.0.1) port 8280 (#0)<br><strong><em>&gt; POST /utility/1.0/hello HTTP/1.1<br>&gt; Host: 127.0.0.1:8280<br>&gt; User-Agent: curl/7.54.0<br>&gt; Content-Type: application/json<br>&gt; Accept: application/json<br>&gt; Content-Length: 19</em></strong><br>&gt;<br>* upload completely sent off: 19 out of 19 bytes<br><strong><em>&lt; HTTP/1.1 200 OK</em></strong><br>&lt; Accept: application/json<br>&lt; Access-Control-Allow-Origin: *<br>&lt; Access-Control-Allow-Methods: POST<br>&lt; Host: 127.0.0.1:8280<br>&lt; Access-Control-Allow-Headers: authorization,Access-Control-Allow-Origin,Content-Type<br>&lt; Content-Type: application/json; charset=UTF-8<br>&lt; Date: Thu, 02 Aug 2018 18:12:31 GMT<br>&lt; Transfer-Encoding: chunked<br>&lt;<br>* Connection #0 to host 127.0.0.1 left intact<br><strong><em>{&quot;response&quot;:&quot;hello&quot;}</em></strong></pre><p>Send the request { “request”: “hello” }with Content-Type: text/plain and you will get the response { “response”: “bad request” } with 400 HTTP Status Code</p><pre>Rajs-MacBook-Pro:sequences raj$ curl -v -X POST --header &quot;Content-Type: text/plain&quot; --header &quot;Accept: text/plain&quot; -d &#39;{&quot;request&quot;:&quot;hello&quot;}&#39; &quot;<a href="http://127.0.0.1:8280/utility/1.0/hello">http://127.0.0.1:8280/utility/1.0/hello</a>&quot;<br><br>*   Trying 127.0.0.1...<br>* TCP_NODELAY set<br>* Connected to 127.0.0.1 (127.0.0.1) port 8280 (#0)<br><strong><em>&gt; POST /utility/1.0/hello HTTP/1.1<br>&gt; Host: 127.0.0.1:8280<br>&gt; User-Agent: curl/7.54.0<br>&gt; Content-Type: text/plain<br>&gt; Accept: text/plain<br>&gt; Content-Length: 19</em></strong><br>&gt;<br>* upload completely sent off: 19 out of 19 bytes<br><strong><em>&lt; HTTP/1.1 400 Bad Request</em></strong><br>&lt; Accept: text/plain<br>&lt; Access-Control-Allow-Origin: *<br>&lt; Access-Control-Allow-Methods: POST<br>&lt; Host: 127.0.0.1:8280<br>&lt; Access-Control-Allow-Headers: authorization,Access-Control-Allow-Origin,Content-Type<br>&lt; Content-Type: application/json; charset=UTF-8<br>&lt; Date: Thu, 02 Aug 2018 18:17:15 GMT<br>&lt; Transfer-Encoding: chunked<br>&lt; Connection: Close<br>&lt;<br>* Closing connection 0<br><strong><em>{&quot;response&quot;:&quot;bad request&quot;}</em></strong></pre><h4>Global Sequence</h4><p>The solution we designed above engages two additional sequences in API level. In other words, we will need to create two new sequences for every prototyped API. Instead (or in addition to this), if we want to have a common sequence for all our prototyped APIs, we can do that too.</p><p>Let’s update the prototype_template.xml as shown below.</p><pre><strong><em>&lt;sequence key=&quot;beforeScript&quot;/&gt;</em></strong><br>#if(!$resource.getMediationScript().equalsIgnoreCase(&quot;null&quot;))<br>    &lt;script language=&quot;js&quot;&gt;<br>        &lt;![CDATA[<br>                        $resource.getMediationScript()<br>                ]]&gt;<br>    &lt;/script&gt;<strong><em><br>&lt;sequence key=&quot;afterScript&quot;/&gt;</em></strong></pre><p>What we are doing here is that we are just removing API name and version from the sequence name. We now have to create two sequences beforeScript.xml and afterScript.xml and deploy to Gateway. When we redeploy our API from Publisher UI, our API definition will be updated, as shown below.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;api xmlns=&quot;<a href="http://ws.apache.org/ns/synapse">http://ws.apache.org/ns/synapse</a>&quot; name=&quot;admin--Utility&quot; context=&quot;/utility/1.0&quot; version=&quot;1.0&quot; version-type=&quot;context&quot;&gt;<br>   &lt;resource methods=&quot;POST&quot; url-mapping=&quot;/hello&quot; faultSequence=&quot;fault&quot;&gt;<br>      &lt;inSequence&gt;<br>         <strong><em>&lt;sequence key=&quot;beforeScript&quot; /&gt;</em></strong><br>         &lt;script language=&quot;js&quot;&gt;var reqPayload = mc.getPayloadJSON();var resPayload = {};if (mc.getProperty(&#39;Content-Type&#39;) == &#39;application/json&#39;) {    resPayload = {&quot;response&quot;: reqPayload.request};    mc.setProperty(&quot;HTTP_SC&quot;, &quot;200&quot;);} else {    resPayload = {&quot;response&quot;: &quot;bad request&quot;};    mc.setProperty(&quot;HTTP_SC&quot;, &quot;400&quot;);}mc.setPayloadJSON(resPayload);mc.setProperty(&#39;CONTENT_TYPE&#39;, &#39;application/json&#39;);&lt;/script&gt;<br>         <strong><em>&lt;sequence key=&quot;afterScript&quot; /&gt;</em></strong><br>         &lt;filter source=&quot;boolean(get-property(&#39;CONTENT_TYPE&#39;))&quot; regex=&quot;false&quot;&gt;<br>            &lt;then&gt;<br>               &lt;property name=&quot;messageType&quot; value=&quot;application/xml&quot; scope=&quot;axis2&quot; /&gt;<br>            &lt;/then&gt;<br>            &lt;else&gt;<br>               &lt;property name=&quot;messageType&quot; expression=&quot;get-property(&#39;CONTENT_TYPE&#39;)&quot; scope=&quot;axis2&quot; /&gt;<br>            &lt;/else&gt;<br>         &lt;/filter&gt;<br>         &lt;respond /&gt;<br>      &lt;/inSequence&gt;<br>      &lt;outSequence&gt;<br>         &lt;send /&gt;<br>      &lt;/outSequence&gt;<br>   &lt;/resource&gt;<br>   &lt;handlers&gt;<br>      &lt;handler class=&quot;org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler&quot;&gt;<br>         &lt;property name=&quot;apiImplementationType&quot; value=&quot;INLINE&quot; /&gt;<br>      &lt;/handler&gt;<br>   &lt;/handlers&gt;<br>&lt;/api&gt;</pre><p>Since these sequences doesn’t have any API name in it, they will be executed for all the prototyped APIs.</p><p>Of course, if we want we can have both global and API level sequences. Let’s update the prototype_template.xml as shown below.</p><pre><strong><em>#set ($beforeScriptSeqKey = &quot;--beforeScript_v&quot;)<br>#set ($beforeScriptSeqKey = &quot;$!apiName$beforeScriptSeqKey$!apiVersion&quot;)<br>&lt;sequence key=&quot;beforeScript&quot;/&gt;<br>&lt;sequence key=&quot;$beforeScriptSeqKey&quot;/&gt;</em></strong><br>#if(!$resource.getMediationScript().equalsIgnoreCase(&quot;null&quot;))<br>    &lt;script language=&quot;js&quot;&gt;<br>        &lt;![CDATA[<br>                        $resource.getMediationScript()<br>                ]]&gt;<br>    &lt;/script&gt;<br><strong><em>#set ($afterScriptSeqKey = &quot;--afterScript_v&quot;)<br>#set ($afterScriptSeqKey = &quot;$!apiName$afterScriptSeqKey$!apiVersion&quot;)<br>&lt;sequence key=&quot;afterScript&quot;/&gt;<br>&lt;sequence key=&quot;$afterScriptSeqKey&quot;/&gt;</em></strong></pre><p>Follow me on Twitter <a href="https://twitter.com/raj10x">@raj10x</a> for latest blogs!</p><figure><a href="https://twitter.com/raj10x"><img alt="" src="https://cdn-images-1.medium.com/max/771/1*ZVSBo3C13iGOU3Ur0J5qXA.png" /></a></figure><p><a href="https://twitter.com/raj10x">Raj Rajaratnam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417fedf4d3f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>