<?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 Aidan O&#39;Gorman on Medium]]></title>
        <description><![CDATA[Stories by Aidan O&#39;Gorman on Medium]]></description>
        <link>https://medium.com/@aidan.ogorman?source=rss-204c28c7071c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4wMLBnjv0iYRYCpd2wzziQ.jpeg</url>
            <title>Stories by Aidan O&amp;#39;Gorman on Medium</title>
            <link>https://medium.com/@aidan.ogorman?source=rss-204c28c7071c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:43:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aidan.ogorman/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[Blue-Green Deployment with Kubernetes]]></title>
            <link>https://medium.com/@aidan.ogorman/blue-green-deployment-with-kubernetes-24fa78fcc2a6?source=rss-204c28c7071c------2</link>
            <guid isPermaLink="false">https://medium.com/p/24fa78fcc2a6</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[blue-green-deployment]]></category>
            <dc:creator><![CDATA[Aidan O'Gorman]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 06:01:50 GMT</pubDate>
            <atom:updated>2022-10-17T06:01:50.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NZ-mbmGIJeeGoDy_" /><figcaption>Photo by <a href="https://unsplash.com/es/@phorgod?utm_source=medium&amp;utm_medium=referral">Abbas Tehrani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>The Blue-Green deployment strategy is a deployment pattern aimed at minimising the risk of downtime and service disruption by running an identical, idle environment in parallel to your existing environment. This gives you the opportunity to test new versions in a live environment and to easily roll back should there be issues.</p><p>The strategy is pretty simple; we deploy another instance of our application running a new version of the code, do some testing to ensure that the application is working as expected, and then switch the route on the load balancer to route all requests to the new deployment. There are additional considerations if your application uses a database, but these are out of scope of this post.</p><p>As a strategy it’s been around for a while, but Kubernetes offers a couple of benefits over the traditional method of deploying on to bare metals or dedicated VMs:</p><ol><li>it’s cheaper: Kubernetes can provision new nodes at deploy-time through its cluster auto-scaling functionality to handle the additional load on the cluster. We don’t have to host the infrastructure which would be required to run a full copy of the application</li><li>it’s self-contained: Kubernetes has native support for ingress and service components, so our load balancer and network can sit alongside our application deployment (and we can deploy, observe and debug it using similar tools)</li></ol><p>In this post, I deploy a simple “Hello, world!” application on k8s and show how we can perform a zero-downtime blue-green deployment, and also rollback to the previous version.</p><h3>Minimum Risk, Maximum Reward</h3><p>For this post, I have set up a local k8s cluster using k3d and enabled ingress to the cluster by following the instructions in this tutorial. The application being deployed is the hello-world app from <a href="https://github.com/GoogleCloudPlatform/kubernetes-engine-samples/blob/main/hello-app/README.md">Google</a>.</p><p>First, I created a new namespace for our application:</p><pre>aidanog@LAPTOP-TH69GHQC:~$ k create ns blue-green &amp;&amp; kns blue-green<br>namespace/blue-green created<br>Context &quot;k3d-k3s-default&quot; modified.<br>Active namespace is &quot;blue-green&quot;.</pre><p>Then we need to create the ‘blue’ deployment of our application on the namespace:</p><pre>aidanog@LAPTOP-TH69GHQC:~$ kubectl create deployment web --image=gcr.io/google-samples/hello-app:1.0<br>deployment.apps/web created<br>aidanog@LAPTOP-TH69GHQC:~$ k get pods<br>NAME                   READY   STATUS    RESTARTS   AGE<br>web-6bf786c76b-vpl26   1/1     Running   0          13s</pre><p>At the moment, this pod is not accessible from the browser, so we need to fix that. In order to do that, we use a combination of k8s <a href="https://kubernetes.io/docs/concepts/services-networking/service/">Service</a> and <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">Ingress</a> objects. The service exposes our pod(s) to traffic within the cluster and the ingress handles routing of requests from outside the cluster. For the purposes of this post, I am only exposing the pods to traffic from <em>localhost.</em></p><pre>aidanog@LAPTOP-TH69GHQC:~$ kubectl expose deployment web --type=NodePort --port=8080<br>service/web exposed<br>aidanog@LAPTOP-TH69GHQC:~$ kubectl get service web<br>NAME   TYPE       CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE<br>web    NodePort   10.43.27.3   &lt;none&gt;        8080:32579/TCP   9s<br>aidanog@LAPTOP-TH69GHQC:~$ kubectl apply -f <a href="https://k8s.io/examples/service/networking/example-ingress.yaml">https://k8s.io/examples/service/networking/example-ingress.yaml</a><br>ingress.networking.k8s.io/example-ingress created<br>aidanog@LAPTOP-TH69GHQC:~$ kubectl get ingress<br>NAME              CLASS    HOSTS              ADDRESS                            PORTS   AGE<br>example-ingress   &lt;none&gt;   hello-world.info   172.21.0.3,172.21.0.4,172.21.0.5   80      5s</pre><p>We know that we need to expose port 8080 by looking at the <a href="https://github.com/GoogleCloudPlatform/kubernetes-engine-samples/blob/main/hello-app/main.go#L33">source code</a> for our hello-world application, which is just a very simple HTTP server written in Golang.</p><p>I mentioned previously that we use k3d commands to enable ingress to our cluster. At a high level, k3d’s API-Server maps to a port on the host system. We then supply a port-mapping construct (8081:80@loadbalancer) in our k3d command which creates a load balancer on the cluster, mapping a host port to port 80 on the LB container. All ports exposed on the load balancer server are proxied to the same ports on all server nodes in the cluster.</p><pre>aidanog@LAPTOP-TH69GHQC:~$ k get svc -n kube-system traefik -o jsonpath=&#39;{.spec.ports}&#39;<br>[<br>   {<br>      &quot;name&quot;:&quot;web&quot;,<br>      &quot;nodePort&quot;:30746,<br>      &quot;port&quot;:80,<br>      &quot;protocol&quot;:&quot;TCP&quot;,<br>      &quot;targetPort&quot;:&quot;web&quot;<br>   },<br>   {<br>      &quot;name&quot;:&quot;websecure&quot;,<br>      &quot;nodePort&quot;:30149,<br>      &quot;port&quot;:443,<br>      &quot;protocol&quot;:&quot;TCP&quot;,<br>      &quot;targetPort&quot;:&quot;websecure&quot;<br>   }<br>]</pre><p>We can now navigate to localhost:8081 to check out our web service:</p><figure><img alt="Screenshot of our web application, version 1.0" src="https://cdn-images-1.medium.com/max/858/1*li6H6Z_9QPIfRpBr--O2Pg.png" /><figcaption>We have liftoff!</figcaption></figure><p>Our web service is now deployed! It works well, but requirements evolve over time and we may reach a point where we want to deploy a new version of the site with additional features. We can use a blue-green deployment to do this in a way that reduces risk of downtime by allowing us to confirm that the new version is operational before promoting it to be the default view.</p><p>Let’s assume that we have made the changes to our codebase, built the image, and tagged and published it to our artifact repository. The next step is to duplicate the deployment which manages v1.0.0 of our application and update a few details:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  generation: 1<br>  labels:<br>    app: web-v2  &lt;-- updated deployment label<br>  name: web-v2   &lt;-- updated deployment name<br>  namespace: blue-green<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: web-v2 &lt;-- updated pod spec label<br>  strategy:<br>    rollingUpdate:<br>      maxSurge: 25%<br>      maxUnavailable: 25%<br>    type: RollingUpdate<br>  template:<br>    metadata:<br>      labels:<br>        app: web-v2 &lt;-- updated metadata label<br>    spec:<br>      containers:<br>      - image: gcr.io/google-samples/hello-app:2.0 &lt;-- new app version<br>        name: hello-app</pre><p>We can then expose the new version of our application in the same way we did before. It’s ok to re-use the port number as services expose the appropriate pod based on labels:</p><pre>kubectl expose deployment web --type=NodePort --port=8080</pre><p>Now we have two services exposing two pods running separate versions of our application simultaneously. The only thing left to do is expose v2.0.0 via the ingress object by adding a new rule to the spec:</p><ul><li>v1.0.0 is reached by navigating to <a href="http://localhost:8080/">http://localhost:8081</a></li><li>v2.0.0 is reached by navigating to <a href="http://localhost:8081/v2">http://localhost:8081/v2</a></li></ul><p>(remember port 8081<em> </em>is the <strong>host port </strong>that we exposed, port 8080 is the port that the services expose our applications on. k3d is doing the load-balancing behind the scenes for us).</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  creationTimestamp: &quot;2022-10-15T18:04:53Z&quot;<br>  generation: 4<br>  name: example-ingress<br>  namespace: blue-green<br>  resourceVersion: &quot;38583&quot;<br>  uid: 9fac35f2-060c-4e7d-832b-e53e0c102c9d<br>spec:<br>  rules:<br>  - host: localhost<br>    http:<br>      paths:<br>      - backend:<br>          service:<br>            name: web<br>            port:<br>              number: 8080<br>        path: /<br>        pathType: Prefix<br>      - backend:<br>          service:<br>            name: web-v2<br>            port:<br>              number: 8080<br>        path: /v2<br>        pathType: Prefix<br>status:<br>  loadBalancer:<br>    ingress:<br>    - ip: 172.21.0.2<br>    - ip: 172.21.0.3<br>    - ip: 172.21.0.5</pre><p>Indeed, navigating to each of these paths should show the appropriate version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*3fHPlQ76B06ucRWbFcWDgg.png" /><figcaption>Shiny new version of our application deployed on a separate path</figcaption></figure><p>When we’re happy that the new version of our site is working as expected, we simply update the ingress to remove v1.0.0 and promote v2.0.0 from /v2 to / . If there is an issue with our new version, we patch it and roll out a fix without affecting the availability of v1.0.0 of the site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*tM2N3mdxT9KSwq6AMtqsRw.png" /></figure><h3>Conclusion</h3><p>Blue-green deployments are a handy way to roll out new versions of an application in a way that minimizes risk of downtime for our application by having both versions running simultaneously. It also gives us complete control over how we roll our application out; we can notify pilot users of this new URL endpoint and then gradually roll it out to other users.</p><p>Recently I have been playing around with Argo Rollouts which allow us to automate the process of deploying new application versions, as well as offering features like canary deployments and gradual rollouts. We’ll focus on these in the next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24fa78fcc2a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Deployment with ArgoCD]]></title>
            <link>https://medium.com/@aidan.ogorman/continuous-deployment-with-argocd-f1ce7b5f6a20?source=rss-204c28c7071c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1ce7b5f6a20</guid>
            <category><![CDATA[argo-cd]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[argo]]></category>
            <dc:creator><![CDATA[Aidan O'Gorman]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 07:01:44 GMT</pubDate>
            <atom:updated>2022-09-12T07:01:44.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>ArgoCD is a declarative, GitOps continuous delivery tool for Kubernetes. It lets you define the desired state of your application infrastructure in k8s manifest files, and tries to converge to that desired state in an automated way in the target environment. The GitOps pattern of using Git repositories as the source of truth means that application states are version controlled, making upgrades and rollbacks simple and transparent.</p><p>ArgoCD achieves this through <em>‘applications’ </em>which are groups of resources defined in a manifest and stored as a CRD on the k8s cluster. Changes to the application are picked up by ArgoCD which then performs a <em>‘sync’ </em>to move the application to its target state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*cWvuk06u067MgoESqL5GYw.png" /><figcaption><a href="https://argo-cd.readthedocs.io/en/stable/operator-manual/architecture/">https://argo-cd.readthedocs.io/en/stable/operator-manual/architecture/</a></figcaption></figure><p>I’ve been trying to get familiar with ArgoCD and how it can be used to create a continuous deployment model for a simple web application. To do this, I forked two repositories:</p><p><strong>openshift-gitops-examples:</strong> <a href="https://github.com/aidan-ogorman-dev/openshift-gitops-examples">https://github.com/aidan-ogorman-dev/openshift-gitops-examples</a></p><p><strong>argocd-tutorial:</strong> <a href="https://github.com/aidan-ogorman-dev/argocd-tutorial">https://github.com/aidan-ogorman-dev/argocd-tutorial</a></p><p>The <em>‘openshift-gitops-examples’</em> repository contains a set of resources which can be deployed on a minikube cluster. There are two branches: <strong>main </strong>and <strong>minikube</strong>; I’ve used the<em> ‘minikube’</em> branch for this example.</p><p>The<em> ‘argocd-tutorial’ </em>repository has a set of example applications, including <em>‘bgd-app’</em>. At a high level, an ArgoCD application is a YAML file which describes a number of things about the target application, including:</p><ul><li>information about the source repository</li><li>how to perform syncs when a new version of the application is detected</li><li>metadata about the application, including things like app name and target namespace</li></ul><p>In addition to these repos, I have set up a Minikube cluster and enabled the ingress add-on. I have also installed the argocd CLI tool. You can check that it’s installed by running the following:</p><pre>$ argocd version<br>argocd: v2.4.11+3d9e9f2<br>BuildDate: 2022-08-22T09:35:38Z<br>GitCommit: 3d9e9f2f95b7801b90377ecfc4073e5f0f07205b<br>GitTreeState: clean<br>GoVersion: go1.18.5<br>Compiler: gc<br>Platform: linux/amd64</pre><h3>Creating the Application</h3><p>First, we need to create the necessary resources for ArgoCD to be able to operate on the cluster:</p><pre>$ kubectl apply -n argocd -f <a href="https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml">https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</a><br>customresourcedefinition.apiextensions.k8s.io/applications.argoproj.io created<br>customresourcedefinition.apiextensions.k8s.io/applicationsets.argoproj.io created<br>customresourcedefinition.apiextensions.k8s.io/appprojects.argoproj.io created<br>...</pre><p>To access the ArgoCD UI, I port-forwarded into the argocd-server service:</p><pre>$ kubectl port-forward svc/argocd-server -n argocd 31353:443 &amp;</pre><p>The default username is <em>‘admin’</em> and the password is retrieved from a secret which was generated in the previous step:</p><pre>$ kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=”{.data.password}” | base64 -d; echo</pre><p>And now we have access to a UI which is very useful for viewing application configuration and keeping track of application synchronization.</p><p>Now we need to create our ArgoCD application. The only change I made to the source repository was to change the <em>‘repoUrl’</em> to point to the forked version. This allows us to make changes to the forked version and watch them being picked up automatically by ArgoCD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MaexCM1t_xcS_Le-1Udf5A.png" /></figure><p>The only thing left to do is apply the changes:</p><pre>$ kubectl apply -f documentation/modules/ROOT/examples/minikube/bgd-app/bgd-app.yaml</pre><p>When this is done, you can view the app and its configuration in the UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JESj4mILl9MjXzhysijeVg.png" /></figure><p>On the cluster, you can see that we now have a set of resources deployed:</p><pre>$ k get pods -n bgd<br>NAME                   READY   STATUS    RESTARTS   AGE<br>bgd-68c5598bcb-ws4xp   1/1     Running   0          98m<br>$ k get svc -n bgd<br>NAME   TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE<br>bgd    NodePort   10.104.168.150   &lt;none&gt;        8080:31363/TCP   3h11m</pre><p>By logging in to the application, we can see that its current status reflects the environment variable set by the environment variable in the deployment manifest file:</p><pre>$ k get deploy -n bgd -o yaml | grep env -A2</pre><pre>  - env:<br>    - name: COLOR<br>      value: blue</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0o4Mf6UyDBoihboIc3cZmg.png" /><figcaption>Initial version of our application is deployed</figcaption></figure><h3>Continuous Deployment</h3><p>I mentioned previously that we specified a path in the ArgoCD app that we created which defines the location in the repository that ArgoCD will watch for changes. For this demo, the path is defined in the file: <em>‘documentation/modules/ROOT/examples/minikube/bgd-app/bgd-app.yaml’</em>.</p><p>Let’s change the value of the environment variable, and see how ArgoCD handles this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aUNfSfxgvFFp0rHz8zeNZQ.png" /></figure><p>When this change is committed to the branch, ArgoCD updates the status of our application to<em> ‘OutOfSync’ </em>which then triggers a <em>‘Sync’</em> action to kick off and try to move our application to the new desired state. After a few seconds, we can refresh the page and see that it was successful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T58aXqcPbOLl42z-v9GTRQ.png" /><figcaption>ArgoCD detects the change made to the source repository</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imNEY0fcoSOgB66Tl9YoRA.png" /><figcaption>New version of the application deployed and visible</figcaption></figure><h3>Deployment History and Rollbacks</h3><p>Sometimes application deployments can fail, and we need to rollback to a previous working version of the code. This is easily achieved in ArgoCD, which tracks deployment history and allows us to rollback or re-deploy a specific version of the application from the UI with a single click:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0tYo7goEGDUjoS0YX1VkQ.png" /><figcaption>Easily view deployment history and implement rollbacks</figcaption></figure><h3>Configuration Drift</h3><p>Configuration drift is the process of deviating from the desired state of an application over time as a result of user actions which are not defined in code and therefore hard to track over time. This can become a serious issue for applications if not managed appropriately as certain changes may incur costs or alter core functionality of the application without being documented or tracked.</p><p>Defining our application in code and enabling automated deployments based on tags or versions allows us to re-deploy the same version of the code continuously, thus ensuring that configuration drift is detected and mitigated immediately.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1ce7b5f6a20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consistent and Reliable Kubernetes Resource Definitions with cdk8s]]></title>
            <link>https://medium.com/@aidan.ogorman/consistent-and-reliable-kubernetes-resource-definitions-with-cdk8s-cad9f875d1eb?source=rss-204c28c7071c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cad9f875d1eb</guid>
            <category><![CDATA[kdb]]></category>
            <category><![CDATA[cdk8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Aidan O'Gorman]]></dc:creator>
            <pubDate>Tue, 01 Mar 2022 18:06:24 GMT</pubDate>
            <atom:updated>2022-03-01T18:09:19.312Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post, I showed how we can use Kubernetes to deploy and manage a fleet of kdb+ HDB processes. This is great and it solves a lot of problems associated with historical database services including query load balancing, auto-scaling, and process management.</p><p>In a modern tick data stack, however, you rarely see just one HDB type — often there are separate HDBs per asset type, reference data DBs, and HDBs segmented across multiple disks. These databases serve different purposes, but from a resource definition perspective they are quite similar in terms of base configuration (it’s a kdb+ process with a disk attached and a command which is run on start-up to memory map the data).</p><p>We could create an almost identical YAML resource definition per HDB, and it would work perfectly well. However, as the number of services grows, it gets harder and harder to maintain all of the YAML files associated with your application. There is also a lot of boilerplate code in Kubernetes which rarely/never changes across the lifetime of an application (think apiVersion, kind, metadata labels). Finally, it tends to result in a lot of copy and pasting if a resource definition already exists for what you need.</p><p>It is possible to achieve the same thing using a Helm template, but this gets quite complex quite quickly and often requires navigating multiple files to debug issues and understand where a wildcard value is being sourced from. cdk8s<strong> </strong>allows developers to define Kubernetes applications using familiar programming languages (in the post I’m using Golang but it also supports Python, Typescript and Java). In addition, once you have defined your resources in code you can share reusable components through code libraries which are easier to maintain and share than templates.</p><p>To create the project, we simply create a directory and run the <em>init</em> command. This does a few things:</p><ol><li>Creates a new project directory</li><li>Installs cdk8s as a dependency</li><li>Imports all Kubernetes API objects</li></ol><pre>~$ mkdir kdb-tick-deployment &amp;&amp; cd kdb-tick-deployment<br>~/kdb-tick-deployment$ cdk8s init go-app<br>Initializing a project from the go-app template<br>Importing k8s v1.22.0...<br>Importing resources, this may take a few moments...<br>========================================================================================================</pre><pre>Your cdk8s Go project is ready!</pre><pre>cat help      Prints this message<br>   cdk8s synth   Synthesize k8s manifests to dist/<br>   cdk8s import  Imports k8s API objects to &quot;imports/k8s&quot;</pre><pre>Deploy:<br>   kubectl apply -f dist/</pre><pre>========================================================================================================</pre><p>We now have the files we need to get started:</p><pre>~/kdb-tick-deployment$ ls -lrth<br>total 28K<br>-rw-r--r-- 1 aidanog aidanog  431 Mar  1 17:26 help<br>-rw-r--r-- 1 aidanog aidanog   44 Mar  1 17:26 cdk8s.yaml<br>-rw-r--r-- 1 aidanog aidanog  556 Mar  1 17:26 main.go<br>drwxr-xr-x 3 aidanog aidanog 4.0K Mar  1 17:26 imports<br>-rw-r--r-- 1 aidanog aidanog 2.0K Mar  1 17:26 go.sum<br>-rw-r--r-- 1 aidanog aidanog  190 Mar  1 17:26 go.mod<br>drwxr-xr-x 2 aidanog aidanog 4.0K Mar  1 17:26 dist</pre><p>For the purposes of this simple post, I’m going to define my resources inside <em>main.go</em>. It already contains some code from when the project is initialized, but we will modify it and add some of our own. The first step is to define the custom fields for our deployment, service and pod:</p><pre>type MyChartProps struct {<br> cdk8s.ChartProps<br> DeployProps DeploymentProps<br> SvcProps    ServiceProps<br> PodProps    PodProps<br>}</pre><pre>type DeploymentProps struct {<br> Replicas                      float64<br> Name                          string<br> Image                         string<br> Ports                         float64<br> Command                       []string<br> TerminationGracePeriodSeconds float64<br>}</pre><pre>type ServiceProps struct {<br> Type       string<br> Port       float64<br> TargetPort float64<br> Name       string<br> Protocol   string<br>}</pre><pre>type PodProps struct {<br> Name  string<br> Image string<br>}</pre><p>Then we define our HDB component which contains a deployment and service resource:</p><pre>func NewHDB(scope constructs.Construct, id string, props *MyChartProps) cdk8s.Chart {<br> var cprops cdk8s.ChartProps<br> if props != nil {<br>  cprops = props.ChartProps<br> }<br> chart := cdk8s.NewChart(scope, jsii.String(id), &amp;cprops)</pre><pre> // define resources here<br> label := map[string]*string{&quot;app&quot;: jsii.String(id)}</pre><pre> k8s.NewKubeDeployment(chart, jsii.String(&quot;deployment&quot;), &amp;k8s.KubeDeploymentProps{<br>  Spec: &amp;k8s.DeploymentSpec{<br>   Replicas: jsii.Number(props.DeployProps.Replicas),<br>   Selector: &amp;k8s.LabelSelector{<br>    MatchLabels: &amp;label,<br>   },<br>   Template: &amp;k8s.PodTemplateSpec{<br>    Metadata: &amp;k8s.ObjectMeta{<br>     Labels: &amp;label,<br>    },<br>    Spec: &amp;k8s.PodSpec{<br>     Containers: &amp;[]*k8s.Container{{<br>      Name:    jsii.String(props.DeployProps.Name),<br>      Image:   jsii.String(props.DeployProps.Image),<br>      Ports:   &amp;[]*k8s.ContainerPort{{ContainerPort: jsii.Number(props.DeployProps.Ports)}},<br>      Command: jsii.Strings(props.DeployProps.Command...),<br>     }},<br>     TerminationGracePeriodSeconds: jsii.Number(props.DeployProps.TerminationGracePeriodSeconds),<br>    },<br>   },<br>  },<br> })</pre><pre> k8s.NewKubeService(chart, jsii.String(&quot;service&quot;), &amp;k8s.KubeServiceProps{<br>  Spec: &amp;k8s.ServiceSpec{<br>   Type: jsii.String(props.SvcProps.Type),<br>   Ports: &amp;[]*k8s.ServicePort{{<br>    Port:       jsii.Number(props.SvcProps.Port),<br>    TargetPort: k8s.IntOrString_FromNumber(jsii.Number(props.SvcProps.TargetPort)),<br>    Name:       jsii.String(props.SvcProps.Name),<br>    Protocol:   jsii.String(props.SvcProps.Protocol),<br>   }},<br>   Selector: &amp;label,<br>  },<br> })</pre><pre> return chart<br>}</pre><p>We also define our <em>demo-query</em> resource:</p><pre>func NewPod(scope constructs.Construct, id string, props *MyChartProps) cdk8s.Chart {<br> var cprops cdk8s.ChartProps<br> if props != nil {<br>  cprops = props.ChartProps<br> }<br> chart := cdk8s.NewChart(scope, jsii.String(id), &amp;cprops)</pre><pre> // define resources here<br> label := map[string]*string{&quot;app&quot;: jsii.String(id)}</pre><pre> k8s.NewKubePod(chart, jsii.String(&quot;pod&quot;), &amp;k8s.KubePodProps{<br>  Metadata: &amp;k8s.ObjectMeta{<br>   Name:   jsii.String(props.PodProps.Name),<br>   Labels: &amp;label,<br>  },<br>  Spec: &amp;k8s.PodSpec{<br>   Containers: &amp;[]*k8s.Container{{<br>    Name:  jsii.String(props.PodProps.Name),<br>    Image: jsii.String(props.PodProps.Image),<br>   }},<br>  },<br> })</pre><pre> return chart<br>}</pre><p>Our <em>main</em> function invokes these functions to create two HDB components and one <em>demo-query</em> component. When the code is executed, it will synthesize the app, and a Kubernetes manifest YAML will be produced for each Chart in the app. These files are written to the dist directory:</p><pre>func main() {<br> app := cdk8s.NewApp(nil)</pre><pre> hdb_eq := &amp;MyChartProps{<br>  DeployProps: DeploymentProps{<br>   Replicas:                      3,<br>   Name:                          &quot;equities-hdb&quot;,<br>   Image:                         &quot;kdb-tick:1.0.0&quot;,<br>   Ports:                         5000,<br>   Command:                       []string{&quot;q&quot;, &quot;/hdb&quot;, &quot;-p&quot;, &quot;5000&quot;},<br>   TerminationGracePeriodSeconds: 10,<br>  },<br>  SvcProps: ServiceProps{<br>   Type:       &quot;ClusterIP&quot;,<br>   Port:       5000,<br>   TargetPort: 5000,<br>   Name:       &quot;tcp&quot;,<br>   Protocol:   &quot;TCP&quot;,<br>  },<br> }</pre><pre> hdb_ref := &amp;MyChartProps{<br>  DeployProps: DeploymentProps{<br>   Replicas:                      3,<br>   Name:                          &quot;reference-hdb&quot;,<br>   Image:                         &quot;kdb-tick:1.0.0&quot;,<br>   Ports:                         5001,<br>   Command:                       []string{&quot;q&quot;, &quot;/hdb&quot;, &quot;-p&quot;, &quot;5001&quot;},<br>   TerminationGracePeriodSeconds: 10,<br>  },<br>  SvcProps: ServiceProps{<br>   Type:       &quot;ClusterIP&quot;,<br>   Port:       5001,<br>   TargetPort: 5001,<br>   Name:       &quot;tcp&quot;,<br>   Protocol:   &quot;TCP&quot;,<br>  },<br> }</pre><pre> NewHDB(app, &quot;kdb-hdb-eq&quot;, hdb_eq)<br> NewHDB(app, &quot;kdb-hdb-ref&quot;, hdb_ref)</pre><pre> pod := &amp;MyChartProps{<br>  PodProps: PodProps{<br>   Name:  &quot;demo-query&quot;,<br>   Image: &quot;kdb-tick:1.0.0&quot;,<br>  },<br> }</pre><pre> NewPod(app, &quot;demo-query&quot;, pod)<br> app.Synth()<br>}</pre><p>Synthesize the app:</p><pre>~/kdb-tick-deployment$ cdk8s synth<br>------------------------------------------------------------------------------------------------<br>A new version 1.0.111 of cdk8s-cli is available (current 1.0.103).<br>Run &quot;npm install -g cdk8s-cli&quot; to install the latest version on your system.<br>For additional installation methods, see <a href="https://cdk8s.io/docs/latest/getting-started">https://cdk8s.io/docs/latest/getting-started</a><br>------------------------------------------------------------------------------------------------<br>dist/demo-query.k8s.yaml<br>dist/kdb-hdb-eq.k8s.yaml<br>dist/kdb-hdb-ref.k8s.yaml</pre><p>We can see that indeed, this has created Kubernetes manifest files in the ./dist directory:</p><pre>~/kdb-tick-deployment$ head dist/kdb-hdb-eq.k8s.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: kdb-hdb-eq-deployment-c875da9c<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: kdb-hdb-eq<br>  template:<br>...</pre><p>Applying these resources to our Kubernetes namespace:</p><pre>~/kdb-tick-deployment$ kubectl apply -f ./dist/<br>pod/demo-query created<br>deployment.apps/kdb-hdb-eq-deployment-c875da9c created<br>service/kdb-hdb-eq-service-c847318d created<br>deployment.apps/kdb-hdb-ref-deployment-c88f5b51 created<br>service/kdb-hdb-ref-service-c8e20b12 created<br>~/kdb-tick-deployment$ k get pods<br>NAME                                              READY   STATUS    RESTARTS   AGE<br>demo-query                                        1/1     Running   0          5s<br>kdb-hdb-eq-deployment-c875da9c-d587b7cfb-6f6zq    1/1     Running   0          5s<br>kdb-hdb-eq-deployment-c875da9c-d587b7cfb-6tndz    1/1     Running   0          5s<br>kdb-hdb-eq-deployment-c875da9c-d587b7cfb-wm2g9    1/1     Running   0          5s<br>kdb-hdb-ref-deployment-c88f5b51-df97966dc-cq2x4   1/1     Running   0          5s<br>kdb-hdb-ref-deployment-c88f5b51-df97966dc-gzl96   1/1     Running   0          5s<br>kdb-hdb-ref-deployment-c88f5b51-df97966dc-kxql2   1/1     Running   0          5s</pre><p>Both HDBs are now running in the namespace, along with our <em>demo-query </em>process. We can test this out by connecting and querying each HDB (in this post, both of them have the same disk attached for ease of demonstration):</p><pre>~/kdb-tick-deployment$ k get svc<br>NAME                           TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE<br>kdb-hdb-eq-service-c847318d    ClusterIP   10.99.189.54     &lt;none&gt;        5000/TCP   4m35s<br>kdb-hdb-ref-service-c8e20b12   ClusterIP   10.108.148.143   &lt;none&gt;        5001/TCP   4m35s</pre><pre>~/kdb-tick-deployment$ k exec -it demo-query bash<br>kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.<br>root@demo-query:/tick# rlwrap q<br>KDB+ 4.0 2021.04.26 Copyright (C) 1993-2021 Kx Systems<br>l64/ 4(16)core 6251MB root demo-query 172.17.0.5 EXPIRE 2022.08.06 <a href="/service/mailto:aidan.ogorman@outlook.com">aidan***@outlook.com</a> #***</pre><pre>q)eq_db:hopen`$&quot;:10.99.189.54:5000&quot;<br>q)eq_db<br>3i<br>q)ref_db:hopen`$&quot;:10.108.148.143:5001&quot;<br>q)(eq_db;ref_db)@\:&quot;.z.h&quot;<br>`kdb-hdb-eq-deployment-c875da9c-d587b7cfb-wm2g9`kdb-hdb-ref-deployment-c88f5b..<br>q)(eq_db;ref_db)@\:&quot;select count i by sym from trades&quot;<br>(`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>(`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430</pre><p>And that’s it! We have a consistent and reliable method for generating YAML manifest files for our Kubernetes resources. The benefits of this method are:</p><ul><li>it’s easily version controlled, so we can build, tag and deploy consistently across distributed systems</li><li>integrates really easily with GitOps and CI/CD tools</li><li>abstracts away most of the boilerplate — simply define the custom fields and synthesize the app</li></ul><p>If you’re already familiar with one of the supported languages, then you might find it easier than Helm templates! Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cad9f875d1eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes for kdb+ Container Orchestration]]></title>
            <link>https://medium.com/@aidan.ogorman/kubernetes-for-kdb-container-orchestration-70b0b5360542?source=rss-204c28c7071c------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b0b5360542</guid>
            <category><![CDATA[kdb]]></category>
            <category><![CDATA[q]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Aidan O'Gorman]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 07:31:10 GMT</pubDate>
            <atom:updated>2022-02-21T07:31:10.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o9qGb7iV6YJ6iYvs" /><figcaption>Photo by <a href="https://unsplash.com/@markwilliamspics?utm_source=medium&amp;utm_medium=referral">Mark Williams</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In the last post, I demonstrated how to containerize kdb+ processes, deploy them via Docker, and how to improve process resilience through replication with Docker in <em>“swarm”</em> mode. In this post, I will introduce Kubernetes (k8s) as an alternative to Docker swarm and demonstrate how it can be used to automate and manage container deployment and orchestration.</p><p>In very broad terms, Docker swarm and k8s are similar in the sense that they are both container orchestration tools. I was introduced to Docker swarm first because it works with the Docker CLI — no need to install a new CLI or software. There are, however, several differences between the two solutions which has resulted in k8s becoming the de-facto standard:</p><ol><li>It is highly available by design, fault tolerant and self-healing, and also has auto-scaling built in</li><li>k8s has a richer feature set</li><li>Docker swarm is tied to Docker’s <em>“containerd”</em> container runtime (software responsible for running containers), k8s offers several options</li><li>k8s has a much larger open-source community</li></ol><p>There are a number of articles which go into greater depth about the similarities and differences:</p><ul><li><a href="https://circleci.com/blog/docker-swarm-vs-kubernetes/">Docker Swarm vs Kubernetes: how to choose a container orchestration tool</a></li><li><a href="https://www.ibm.com/cloud/blog/docker-swarm-vs-kubernetes-a-comparison">Docker Swarm vs. Kubernetes: A Comparison</a></li><li><a href="https://thenewstack.io/kubernetes-vs-docker-swarm-whats-the-difference/">Kubernetes vs. Docker Swarm: What&#39;s the Difference? - The New Stack</a></li></ul><h3>Installation</h3><p>To being my learning, I had to get access to a k8s cluster and k8s CLI. For this, I installed Docker Desktop as it includes a standalone k8s server and client (as well as the Docker CLI for image creation). For installation instructions, see here: <a href="https://docs.docker.com/desktop/kubernetes/">https://docs.docker.com/desktop/kubernetes/</a> (NB. You have to install the ‘kubectl’ CLI tool separately). I am also more comfortable using the Linux OS, so I also installed the Ubuntu 20.04 LTS app on to my Windows machine. To interact with Docker Desktop via Ubuntu for Windows, you also need to install the Windows Subsystem for Linux (WSL) 2: <a href="https://docs.docker.com/desktop/windows/wsl/">https://docs.docker.com/desktop/windows/wsl/</a>.</p><p>And that’s pretty much it! We can now execute k8s commands in Ubuntu for Windows:</p><pre>aidanog@LAPTOP-TH69GHQC:~$ kubectl version<br>Client Version: version.Info{Major:&quot;1&quot;, Minor:&quot;22&quot;, GitVersion:&quot;v1.22.0&quot;, GitCommit:&quot;c2b5237ccd9c0f1d600d3072634ca66cefdf272f&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-08-04T18:03:20Z&quot;, GoVersion:&quot;go1.16.6&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;}<br>Server Version: version.Info{Major:&quot;1&quot;, Minor:&quot;22&quot;, GitVersion:&quot;v1.22.4&quot;, GitCommit:&quot;b695d79d4f967c403a96986f1750a35eb75e75f1&quot;, GitTreeState:&quot;clean&quot;, BuildDate:&quot;2021-11-17T15:42:41Z&quot;, GoVersion:&quot;go1.16.10&quot;, Compiler:&quot;gc&quot;, Platform:&quot;linux/amd64&quot;}</pre><h3>Kubernetes Basics</h3><p>Several core components are deployed when you create a cluster, and these are created for you when you spin up Docker Desktop. At the highest level, a k8s cluster consists of node(s), which host application components (pods), and a control plane which manages the nodes. The control plane consists of:</p><ol><li><strong>kube-apiserver</strong>: the API of the k8s control plane — components communicate state changes via this API, and it also handles operations invoked via ‘<em>kubectl</em>’ CLI</li><li><strong>etcd</strong>: a key-value store for k8s cluster configuration and state data</li><li><strong>kube-scheduler</strong>: watches for creation of new pods and schedules a node for them to run on</li><li><strong>controller manager</strong>: runs controller processes, which will run on a loop and watch the shared state of the cluster via the apiserver</li><li><strong>cloud-controller-manager</strong>: if you’re integrating cloud-specific logic or components, this controller links the cluster into the cloud provider</li></ol><p>Then, on each node you have a set of components:</p><ol><li><strong>kubelet</strong>: an agent which checks status of containers in a pod</li><li><strong>kube-proxy</strong>: enables communication within and between nodes via a set of rules</li><li><strong>container runtime</strong>: this is what runs containers — there are a few options, of which Docker is one</li></ol><p>Finally, you have <strong>pods</strong>. A pod is the smallest deployable unit of computing that you can create and manage in k8s, and they are what we use to run applications in a cluster. Pods are created from a specification which is stored in a configuration file. This has several benefits:</p><ol><li>pod specs can be version controlled which makes it easy to deploy consistent versions or upgrade/roll back to previous versions</li><li>new developers can figure out how resources are configured without bugging the original developers too much</li><li>change history is tracked which makes it easier to identify configuration drift</li></ol><p>There are entire pages of documentation on the k8s site relating to each of the components above. In addition to this, k8s also has the concept of <em>“workloads”</em> which is just another term for an application running on Kubernetes. There are a few different kinds of workloads and I encourage you to check the documentation for complete overviews — for the purposes of this article I am going to use a <strong>Deployment.</strong> A deployment takes a pod spec and it tries to match the <em>actual</em> state to the <em>desired </em>state. To give an example, we can set the <em>desired</em> number of pods = 2 in our pod spec. When we create our deployment (which includes the pod spec), the number of pods initially will be 0 and the controller manager will trigger creation of new pods until the <em>actual</em> number of pods reaches the <em>desired</em> number.</p><p>This makes it relatively simple to create and deploy <em>replicated instances</em><strong><em> </em></strong>of the same process and have Kubernetes manage them for you. In the next section, I will create a fleet of HDB processes, place them behind a load-balancing service and show how we can achieve a more fault tolerant and scalable architecture.</p><h3>Creating a kdb+ Kubernetes Deployment</h3><p>For this demo, I am using the <a href="https://medium.com/@aidan.ogorman/containerizing-kdb-with-docker-2af2574f8fc4">image </a>that I created in the previous article: with one addition; I generate some sample HDB data and mount the directory as a volume in the container’s Dockerfile.</p><p>In a production cluster, we would use a Persistent Volume (PV) with a Persistent Volume Claim (PVC) to bind the volume to a pod in our deployment. This is just to keep things simple (there are quite a few gotchas with mounting volumes in Docker Desktop with WSL2 which we wouldn’t have to deal with in a normal cluster):</p><pre>aidanog ~$ rlwrap q<br>KDB+ 4.0 2021.04.26 Copyright (C) 1993-2021 Kx Systems<br>l64/ 4(16)core 6251MB aidanog 127.0.1.1 EXPIRE 2022.08.06 aidan*** KOD ***</pre><pre>q)n:10000<br>q)trades:([] time:asc n?00:00:00.000; sym:n?`GOOG`MSFT`IBM`AAPL`AMZN; sz:n?100f; px:n?100f)<br>q){[t;x] -1 &quot;Saving data for: &quot;,string[x]; .Q.dpft[`$&quot;:/home/aidanog/kdb_container_2/hdb&quot;;x;`sym;t]}[`trades]&#39;[asc .z.d-1+til 10]<br>Saving data for: 2022.02.10<br>Saving data for: 2022.02.11<br>Saving data for: 2022.02.12<br>Saving data for: 2022.02.13<br>Saving data for: 2022.02.14<br>Saving data for: 2022.02.15<br>Saving data for: 2022.02.16<br>Saving data for: 2022.02.17<br>Saving data for: 2022.02.18<br>Saving data for: 2022.02.19<br>`trades`trades`trades`trades`trades`trades`trades`trades`trades`trades<br>q)\\</pre><p>Then inside the Dockerfile, add the following line and rebuild the image:</p><pre>COPY hdb /hdb</pre><p>The first step is to create our <em>deployment. </em>Most of the deployment template spec is pretty generic, but there are a couple of fields to pay particular attention to:</p><ul><li><strong>spec.replicas</strong>: This specifies the <em>desired</em> number of pods</li><li><strong>spec.template.spec.containers:</strong> defines the spec of the container<br>- <strong><em>command </em></strong>is the command which is run when the pod is initialized<br>- <strong><em>ports.containerPort</em></strong><em>:</em> the port that our container exposes (more informational than anything else, this doesn’t perform the act of exposing the port. More on that later)</li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: kdb-tick-deployment<br>  labels:<br>    app: kdb-hdb<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: kdb-hdb<br>  template:<br>    metadata:<br>     labels:<br>       app: kdb-hdb<br>    spec:<br>      terminationGracePeriodSeconds: 10<br>      containers:<br>      - name: hdb<br>        image: kdb-tick:1.0.0<br>        command: [&quot;q&quot;, &quot;/hdb&quot;, &quot;-p&quot;,&quot;5000&quot;]<br>        ports:<br>        - containerPort: 5000<br>---</pre><p>The second component we need to create is a service which can load balance incoming requests to the resources in our deployment. Again the core functional fields here are:</p><ul><li><strong>metadata.labels.app:</strong> links the service to the deployment (lets the service know which pods are associated with it)</li><li><strong>spec.type</strong>: the type of service to deploy — a clusterIP exposes the service on a cluster-internal IP (ingress from outside the cluster is not possible)</li><li><strong>spec.ports: </strong>specifies the ports we want to expose our service on, the protocol, and a name for this port (names are used to differentiate between multiple exposed ports for different purposes e.g. HTTP, metrics, TCP)</li></ul><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: kdb-hdb<br>  labels:<br>    app: kdb-hdb<br>spec:<br>  type: ClusterIP<br>  ports:<br>  - port: 5000<br>    targetPort: 5000<br>    name: kdb-hdb<br>    protocol: TCP<br>  selector:<br>    app: kdb-hdb<br>---</pre><p>Finally, I define the spec for a “demo-query” pod which I will deploy into the cluster and use to fire queries to the HDB processes (remember we are using a clusterIP service, so all communication must be internal to the cluster):</p><pre>---<br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: demo-query<br>  labels:<br>    purpose: demo-command<br>spec:<br>  containers:<br>  - name: demo-query<br>    image: kdb-tick:1.0.0</pre><p>And that’s it! We can now deploy the resources we have defined into our k8s namespace and watch test it out:</p><pre>aidanog ~$ k apply -f ./kdb-deployment.yaml<br>deployment.apps/kdb-tick-deployment created<br>service/kdb-hdb created<br>pod/demo-query created<br>aidanog ~$ k get pods<br>NAME                                  READY   STATUS    RESTARTS   AGE<br>demo-query                            1/1     Running   0          5s<br>kdb-tick-deployment-d79b96fd8-bbgvm   1/1     Running   0          5s<br>kdb-tick-deployment-d79b96fd8-nlgb7   1/1     Running   0          5s<br>kdb-tick-deployment-d79b96fd8-xxzbg   1/1     Running   0          5s<br>aidanog ~$ k get svc<br>NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE<br>kdb-hdb      ClusterIP   10.99.230.186   &lt;none&gt;        5000/TCP   57s</pre><p>We can connect to our <em>demo-query</em> pod and connect to the HDB processes using the service clusterIP. The k8s service handles load balancing across the back-end services, as you can see by the fact that the pod names are evenly distributed across the 10 connections.</p><pre>$ k exec -it demo-query bash<br>kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.<br>root@demo-query:/tick# rlwrap q<br>KDB+ 4.0 2021.04.26 Copyright (C) 1993-2021 Kx Systems<br>l64/ 4(16)core 6251MB root demo-query 172.17.0.6 EXPIRE 2022.08.06 <a href="/service/mailto:aidan.ogorman@outlook.com">aidan*</a>** KOD ***</pre><pre>q)h:hopen each 10#`$&quot;:10.104.61.238:5000&quot; // open 10 connections<br>q)\c 50 2000<br>q)<br>q)// get the address, port, pod name and HDB summary<br>q)h@\:&quot;`address`container_port`pod_name`hdb_summary!(.z.a;system\&quot;p\&quot;;.z.h;select count i by sym from trades)&quot;<br>address     container_port pod_name                             hdb_summary<br>---------------------------------------------------------------------------------------------------------------------------------------------<br>-1408172031 5000           kdb-tick-deployment-78766bddff-x67nm (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-4k5qx (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-x67nm (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-c5mfh (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-c5mfh (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-4k5qx (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-x67nm (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-c5mfh (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-c5mfh (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430<br>-1408172031 5000           kdb-tick-deployment-78766bddff-4k5qx (`s#+(,`sym)!,`AAPL`AMZN`GOOG`IBM`MSFT)!+(,`x)!,20150 19620 20550 20250 19430</pre><h3>Fault Tolerance and Scalability</h3><p>There are two operational benefits of having Kubernetes manage our resources and deployments:</p><ol><li>Kubernetes is self-healing, so pods will be re-created in the event of a catastrophic failure — we can handle the simultaneous loss of 2 pods before experiencing a full outage</li><li>Kubernetes scales, so we can increase or decrease the number of pods in response to load profiles</li></ol><p>To demonstrate #1, we can set the <em>demo-query </em>to send a query to a pod on a timer. We then kill 2 of the pods and show that all queries go to the remaining live pod. k8s will detect this deviation from the <em>desired</em> state and restart the two pods, at which point normal operation resumes:</p><pre>q)/ on the demo-query pod, we define this function and set it to execute every 1/4 of a second<br>q)query_random_pod:{[] h:hopen`$&quot;:10.104.61.238:5000&quot;; result: h&quot;select from trades where sym=`AAPL&quot;; -1 &quot;Query to &quot;,.Q.s1[h&quot;.z.h&quot;],&quot; returned &quot;,.Q.s1[count result],&quot; records&quot;;}<br>q).z.ts:query_random_pod<br>q)\t 250<br>Query to `kdb-tick-deployment-78766bddff-4k5qx returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-c5mfh returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-4k5qx returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-x67nm returned 20150 records<br>...</pre><p>On the terminal, we kill 2 of the pods:</p><pre>$ k delete pods kdb-tick-deployment-78766bddff-4k5qx kdb-tick-deployment-78766bddff-c5mfh</pre><p>The demo-query process sends all queries to a single pod automatically — we don’t need to implement connection handling or load balancing. Any in-flight requests will be dropped, so you would need to implement some retry logic in your API to avoid “Connection refused” errors being returned to users:</p><pre>Query to `kdb-tick-deployment-78766bddff-4xg7r returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-x67nm returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-c5mfh returned 20150 records<br>&#39;hop. OS reports: Connection refused<br>Query to `kdb-tick-deployment-78766bddff-x67nm returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-x67nm returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-5z47g returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-x67nm returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-5z47g returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-x67nm returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-5z47g returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-b78cv returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-5z47g returned 20150 records<br>Query to `kdb-tick-deployment-78766bddff-b78cv returned 20150 records</pre><p>Similarly, we can modify the number of pods in our deployment in response to load profiles.</p><pre>$ k get deploy<br>NAME                  READY   UP-TO-DATE   AVAILABLE   AGE<br>kdb-tick-deployment   3/3     3            3           19m<br>$ k get pods<br>NAME                                   READY   STATUS    RESTARTS   AGE<br>demo-query                             1/1     Running   0          20m<br>kdb-tick-deployment-78766bddff-5z47g   1/1     Running   0          8m33s<br>kdb-tick-deployment-78766bddff-b78cv   1/1     Running   0          8m33s<br>kdb-tick-deployment-78766bddff-x67nm   1/1     Running   0          20m<br>$ k scale deploy kdb-tick-deployment --replicas=5<br>deployment.apps/kdb-tick-deployment scaled<br>$ k get pods<br>NAME                                   READY   STATUS    RESTARTS   AGE<br>demo-query                             1/1     Running   0          20m<br>kdb-tick-deployment-78766bddff-5z47g   1/1     Running   0          8m51s<br>kdb-tick-deployment-78766bddff-6xr4p   1/1     Running   0          5s<br>kdb-tick-deployment-78766bddff-b78cv   1/1     Running   0          8m51s<br>kdb-tick-deployment-78766bddff-rvsd4   1/1     Running   0          5s<br>kdb-tick-deployment-78766bddff-x67nm   1/1     Running   0          20m</pre><p>It is of course possible to automate the scaling of resources by configuring a Horizontal Pod Autoscaler (HPA) which will scale resources in response to information flowing from the k8s controller manager.</p><h3>Further Considerations</h3><p>The aim of this post was to show how we can use Kubernetes to define, deploy and manage kdb+ HDB processes, and to demonstrate some of the “out-of-the-box” benefits of using k8s such as fault tolerance and scaling. I also mentioned a few additional components and concepts that are key if we were deploying this in a production environment:</p><ul><li>Horizontal Pod Autoscaler (HPA) component for scaling functionality</li><li>Metrics server (e.g. Prometheus + Grafana) for tracking resource consumption</li></ul><p>In addition, I only discuss the historical DB component of a kdb+ tick system as it is most easily migrated to a containerized solution. There are a bunch of additional considerations when it comes to managing real-time and stateful components:</p><ul><li>how do real-time components scale up/down?</li><li>how do we keep replicated instances of real-time components in sync?</li><li>how do we manage subscriptions to replicated real-time publisher components?</li></ul><p>I will aim to address some of these in future posts. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b0b5360542" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerizing kdb+ with Docker]]></title>
            <link>https://medium.com/@aidan.ogorman/containerizing-kdb-with-docker-2af2574f8fc4?source=rss-204c28c7071c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2af2574f8fc4</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[q]]></category>
            <category><![CDATA[kdb]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Aidan O'Gorman]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 19:54:24 GMT</pubDate>
            <atom:updated>2021-11-14T19:56:15.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i29mWyocX246bAVH" /></figure><h3>Introduction</h3><p>In this post, I create a container image for a simple kdb+ process and deploy it using Docker, then deploy replicated instances using Docker swarm. It’s the first post about how open-source tools can be used to make kdb+ conform to modern standards in software design and architecture.</p><p>kdb+ is a column-based relational time series database with in-memory abilities and is used widely in the fintech and banking sector due to its real-time data processing capabilities. The language consists of a SQL-like query language called<em> ‘qSQL’</em>, and a concise, expressive programming language called <em>‘q’</em>. It is interpreted, dynamically typed, table (and column) oriented, and expressions are evaluated in right-to-left order.</p><p>The initial learning curve is steep, but once you get your head around the <a href="https://www.pierrebeaucamp.com/trying-to-demystify-k-slash-q-slash-kdb-plus">terse syntax</a>, <a href="https://code.kx.com/q4m3/B_Error_Messages/">concise error messages</a> and <a href="https://code.kx.com/q/ref/overloads/">overloaded glyphs</a>, you can do some powerful things very quickly. One of the downsides is the decision by the creators of the language to make it proprietary. Commercial licenses are prohibitively expensive for many and this has probably contributed to a lack of adoption in industries outside fintech and investment banking. As a result, there are very few frameworks or universal kdb+ tick solutions, and many kdb+ stacks are built bespoke and maintained by dedicated in-house teams.</p><p>I developed an interest in how open-source tools could be leveraged with a bespoke application to achieve some of the features that often ship as standard with enterprise grade software solutions written in other languages:</p><ul><li>Fault tolerance/resiliency</li><li>Disaster recovery</li><li>Scalability in response to variable workloads</li><li>Zero-downtime upgrades</li><li>Infrastructure and operations as code</li></ul><p>For the last few months, I’ve been focusing on a couple of technologies which can help solve some of the above issues:</p><ol><li>Docker for containerization of application code</li><li>Kubernetes for container orchestration, automated deployment, and application scaling</li></ol><p>It should be noted at this point that Docker and Kubernetes are two distinct but complementary technologies, and there are plenty of articles devoted to the differences between the two. In this post, I demonstrate how I used them to deploy a highly available (HA), scalable instance of a basic kdb+ process.</p><h3>Containerizing kdb+</h3><p>A container is a standard unit of software that contains all code and dependencies required to run reliably on any computing environment. Containers are built from container images; lightweight, standalone, executable packages which are OS agnostic and can therefore be deployed anywhere and will work uniformly.</p><p>A vanilla kdb+ process requires three files:</p><ul><li><em>q.k</em>: contains functions which are loaded as part of the ‘bootstrap’ of kdb+</li><li><em>kc.lic</em>: license file for kdb+ (I’m using the non-commercial 64-bit license)</li><li><em>q</em>: the q binary file</li></ul><pre>aidanog: ~/kdb_container/kdb $ ls -lrth<br>total 832K<br>-rw-r--r-- 1 aidanog aidanog  24K Nov 13 17:34 q.k<br>-rwxr-xr-x 1 aidanog aidanog 797K Nov 13 17:34 q<br>-rw-r--r-- 1 aidanog aidanog  363 Nov 13 17:34 kc.lic<br>-rw-r--r-- 1 aidanog aidanog   35 Nov 13 18:01 example.q</pre><p>I then added a fourth file, <em>example.q</em> which contains a simple <em>Hello” </em>function.</p><p>Now that we have everything required to run q locally, we need a way to recreate these conditions procedurally; this is where the <em>‘Dockerfile’ </em>comes in. A <em>‘Dockerfile’</em> contains a list of commands which are executed in sequence to build our container:</p><ol><li>Define a base image on which to build</li><li>Set some environment variables required to run <em>‘q’</em></li><li>Load some useful libraries like <em>‘rlwrap’</em> for enabling line-wrap on the <em>‘q’</em> REPL</li><li>Copy our kdb+ files in and set the working directory</li><li>Execute a command which will start a q process running and load <em>‘example.q’</em></li></ol><pre>FROM debian:9 AS base</pre><pre># do not clean here, its cleaned later!<br>RUN apt-get update \<br>        &amp;&amp; apt-get -yy --option=Dpkg::options::=--force-unsafe-io upgrade</pre><pre>MAINTAINER Aidan O&#39;Gorman</pre><pre># Set env variables for q<br>ENV QHOME /kdb<br>ENV PATH ${PATH}:${QHOME}<br># This should point to the license file location<br>ENV QLIC /kdb</pre><pre># Refresh / Update the base image using alpine&#39;s package manager &quot;apk&quot;, and binutils to allow use of e.g. tar/ar while building<br>RUN apt-get -yy --option=Dpkg::options::=--force-unsafe-io --no-install-recommends install \<br>                ca-certificates \<br>                curl \<br>                rlwrap \<br>                runit \<br>                unzip \<br>        &amp;&amp; apt-get clean \<br>        &amp;&amp; find /var/lib/apt/lists -type f -delete</pre><pre>COPY kdb /kdb<br>WORKDIR kdb<br>CMD [&quot;q&quot;, &quot;example.q&quot;, &quot;-p&quot;,&quot;1234&quot;]</pre><h3>Deploying kdb+ from a Container Image</h3><p>Now that’s done, we simply build our container image and create our container in Docker:</p><pre>aidanog: ~/kdb_container $ docker build -t kdb-in-container/1.0 .<br>...<br>[+] Building 35.2s (11/11) FINISHED</pre><pre>aidanog: ~/kdb_container$ docker image ls<br>REPOSITORY                              TAG                                                     IMAGE ID       CREATED              SIZE<br>kdb-in-container/1.0                    latest                                                  536358b12c76   About a minute ago   183MB</pre><pre>aidanog: ~/kdb_container $ docker create kdb-in-container/1.0<br>e7f268521248e8078ecd8c73c74aa9dffc953b3df3726e1fe227e1210bdbb5d8</pre><pre>aidanog: ~/kdb_container $ docker start e7f268521248e8078ecd8c73c74aa9dffc953b3df3726e1fe227e1210bdbb5d8<br>doe7f268521248e8078ecd8c73c74aa9dffc953b3df3726e1fe227e1210bdbb5d8</pre><pre>aidanog: ~/kdb_container $ docker ps -a<br>CONTAINER ID   IMAGE                  COMMAND                 CREATED         STATUS        PORTS     NAMES<br>e7f268521248   kdb-in-container/1.0   &quot;q example.q -p 1234&quot;   6 seconds ago   Up 1 second             magical_cerf</pre><pre>aidanog: ~/kdb_container $ docker exec -it e7f268521248 sh</pre><pre># q<br>KDB+ 4.0 2021.04.26 Copyright (C) 1993-2021 Kx Systems<br>l64/ 4(16)core 6251MB root e7f268521248 172.17.0.2 EXPIRE 2022.08.06 aidan.ogorman@outlook.com KOD #4177517</pre><pre>q)<br>q)conn:hopen`::1234<br>q)conn(`hello;&quot;Aidan&quot;)<br>&quot;Hello \&quot;Aidan\&quot;!&quot;</pre><h3>Horizontal Scaling in Docker</h3><p>Now that we have an image which contains everything that is required to run our q process, we can easily create replicas of our process using a service and Docker swarm (a container orchestrator tool). I use Docker swarm here to keep things in Docker, but I prefer to use Kubernetes as a container orchestrator and will introduce it in future posts.</p><pre>aidanog: ~/kdb_container $ docker swarm init<br>...</pre><pre>aidanog: ~/kdb_container $ docker service create kdb-in-container/1.0</pre><pre>loj5lp019g8haom00foxydpr2<br>overall progress: 1 out of 1 tasks<br>1/1: running   [==================================================&gt;]<br>verify: Service converged</pre><pre>aidanog: ~/kdb_container $ docker service ls<br>ID             NAME            MODE         REPLICAS   IMAGE                         PORTS<br>loj5lp019g8h   adoring_yalow   replicated   1/1        kdb-in-container/1.0:latest</pre><pre>aidanog: ~/kdb_container $ docker scale service adoring_yalow=5<br>docker: &#39;scale&#39; is not a docker command.<br>See &#39;docker --help&#39;</pre><pre>aidanog: ~/kdb_container $ docker service scale adoring_yalow=5<br>adoring_yalow scaled to 5<br>overall progress: 5 out of 5 tasks<br>1/5: running   [==================================================&gt;]<br>2/5: running   [==================================================&gt;]<br>3/5: running   [==================================================&gt;]<br>4/5: running   [==================================================&gt;]<br>5/5: running   [==================================================&gt;]<br>verify: Service converged</pre><pre>aidanog: ~/kdb_container $ docker service ls<br>ID             NAME            MODE         REPLICAS   IMAGE                         PORTS<br>loj5lp019g8h   adoring_yalow   replicated   5/5        kdb-in-container/1.0:latest</pre><p>Et voila, we now have 5 replicas of our process running on our node. If we were running a typical kdb+ tick stack with historical data services, we could easily scale the number of available services in response to varying query load throughout the day.</p><p>This is a trivial example to show how Docker can help solve issues around scalability and availability of services. There are a couple of things to note:</p><ul><li>these processes are not associated with a network and have no exposed ports, so are not accessible to ingress traffic</li><li>all processes are deployed on a single docker swarm node — if the node goes down, all of the processes go down with it</li></ul><p>In the next article, I will show how we can leverage Kubernetes to automate the deployment and orchestration of containers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2af2574f8fc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>