<?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 Jeff Vincent on Medium]]></title>
        <description><![CDATA[Stories by Jeff Vincent on Medium]]></description>
        <link>https://medium.com/@jeff.d.vincent?source=rss-5ec8ee696037------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aj2H93zdE78gbOSyrfX6JA.jpeg</url>
            <title>Stories by Jeff Vincent on Medium</title>
            <link>https://medium.com/@jeff.d.vincent?source=rss-5ec8ee696037------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:36:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeff.d.vincent/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[Bare Metal K8s on Ubuntu 24.04]]></title>
            <link>https://medium.com/@jeff.d.vincent/bare-metal-k8s-cluster-for-dummies-fc3616b2debb?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3616b2debb</guid>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 00:04:48 GMT</pubDate>
            <atom:updated>2026-01-18T02:13:12.791Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve worked with K8s in various settings for years, and I’ve never felt any real desire to get a certification. It was always more important to me to know K8s than to get a piece of paper that says I know K8s, but a new year is upon us, and well, why not? So, I figure I’ll jot down some notes as I prep for the Certified Kubernetes Admin exam, and maybe this will be helpful for other folks who endeavor to get a piece of paper with K8s in the title.</p><p>My experience has always been with either managed clusters or locally provisioned clusters like KinD or Minikube, so my node admin skills are the first place I’m going to drill. In the interest of doing so in a way that parallels the exam format, I’m spinning up a bare metal K8s cluster in Digital Ocean specifically because it is the cheapest way to spin up the bare metal Ubuntu machines I’ll be using as nodes in my cluster without having to spend precious time and thinkin’ powers on the VMs themselves.</p><p>Anyhow, this will be a two node cluster running on Ubuntu 24.04 nodes. Each node will have 2 vCPUs (the install process with kubeadm requires 2 CPUs for the control plane, FYI).</p><blockquote>Shout out to <a href="https://medium.com/@subhampradhan966?source=post_page---byline--f6a5fc67f0df---------------------------------------">Subham Pradhan</a> for his very helpful <a href="https://medium.com/@subhampradhan966/kubeadm-setup-for-ubuntu-24-04-lts-f6a5fc67f0df">blog post on the topic</a>.</blockquote><p>And I’ll name my nodes control-plane and worker respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpf6b8JtQlcEuU80wgYVJA.png" /></figure><p>And voila!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wfd_6fRGfz6j4MKXi28cw.png" /></figure><h3>Control Plane Stuffs</h3><p>First, we’ll need to SSH into the control plane machnine and get things set up for deploying a new cluster with kubeadm.</p><pre>ssh root@&lt;ip&gt; <br><br>Are you sure you want to continue connecting (yes/no/[fingerprint])? yes<br>Warning: Permanently added &#39;&lt;ip&gt;&#39; (ED25519) to the list of known hosts.<br>root@68.183.173.104&#39;s password: <br>Welcome to Ubuntu 24.04.3 LTS (GNU/Linux 6.8.0-71-generic x86_64)<br><br>blah blah blah ...</pre><p><strong>Install the following:</strong></p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y<br>sudo apt install apt-transport-https curl -y<br><br>sudo apt install containerd -y</pre><p><strong>Configure Containerd:</strong></p><p>NOTE: we’re using containerd (the natively supported container engine) instead of Docker here.</p><pre>sudo mkdir -p /etc/containerd<br>containerd config default | sudo tee /etc/containerd/config.toml &gt; /dev/null<br>sudo sed -i &#39;s/SystemdCgroup = false/SystemdCgroup = true/&#39; /etc/containerd/config.toml<br>sudo systemctl restart containerd</pre><p><strong>Install Kubernetes components:</strong></p><pre>curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.30/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg<br>echo &#39;deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.30/deb/ /&#39; | sudo tee /etc/apt/sources.list.d/kubernetes.list<br>sudo apt update<br>sudo apt install -y kubelet kubeadm kubectl<br>sudo apt-mark hold kubelet kubeadm kubectl</pre><p><strong>Disable swap:</strong></p><p>(This was new to me. Apparently, swap is roughly akin to virtual memory in the Linux kernel that doesn’t play nicely with K8s).</p><pre>sudo swapoff -a<br>sudo sed -i &#39;/ swap / s/^\(.*\)$/#\1/g&#39; /etc/fstab</pre><p><strong>Load necessary kernel modules:</strong></p><pre>sudo modprobe overlay<br>sudo modprobe br_netfilter</pre><p><strong>Set required sysctl parameters:</strong></p><pre>cat &lt;&lt;EOF | sudo tee /etc/sysctl.d/k8s.conf<br>net.bridge.bridge-nf-call-iptables  = 1<br>net.bridge.bridge-nf-call-ip6tables = 1<br>net.ipv4.ip_forward                 = 1<br>EOF</pre><pre>sudo sysctl --system</pre><p><strong>Initialize the cluster (run only on master node):</strong></p><pre>sudo kubeadm init --pod-network-cidr=10.244.0.0/16</pre><p><strong>Set up kubeconfig:</strong></p><pre>mkdir -p $HOME/.kube<br>sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config<br>sudo chown $(id -u):$(id -g) $HOME/.kube/config</pre><pre>export KUBECONFIG=$HOME/.kube/config</pre><p><strong>Install Flannel network plugin (run only on master node):</strong></p><pre>kubectl apply -f https://github.com/flannel-io/flannel/releases/latest/download/kube-flannel.yml</pre><p>And voila!</p><pre>root@control-plane:~# kubectl get all<br>NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE<br>service/kubernetes   ClusterIP   10.96.0.1    &lt;none&gt;        443/TCP   23s</pre><h3>Add our Worker Node</h3><p>First things first, SSH into the second VM.</p><pre>ssh root@&lt;worker-ip&gt;<br><br>blah blah blah ...</pre><p>Now, largely rinse and repeat, BUT don’t run kubeadm init on this node. (No worries if you do, but then there are extra steps to revert it…)</p><p><strong>Install the following:</strong></p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y<br>sudo apt install apt-transport-https curl -y<br><br>sudo apt install containerd -y</pre><p><strong>Configure Containerd:</strong></p><pre>sudo mkdir -p /etc/containerd<br>containerd config default | sudo tee /etc/containerd/config.toml &gt; /dev/null<br>sudo sed -i &#39;s/SystemdCgroup = true/SystemdCgroup = false/&#39; /etc/containerd/config.toml<br>sudo systemctl restart containerd</pre><p><strong>Install Kubernetes components:</strong></p><pre>curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.30/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg<br>echo &#39;deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.30/deb/ /&#39; | sudo tee /etc/apt/sources.list.d/kubernetes.list<br>sudo apt update<br>sudo apt install -y kubelet kubeadm kubectl<br>sudo apt-mark hold kubelet kubeadm kubectl</pre><p><strong>Add required Linux modules:</strong></p><pre>sudo modprobe overlay<br>sudo modprobe br_netfilter</pre><p><strong>Disable swap:</strong></p><pre>sudo swapoff -a<br>sudo sed -i &#39;/ swap / s/^\(.*\)$/#\1/g&#39; /etc/fstab</pre><p><strong>Set required sysctl parameters:</strong></p><pre>cat &lt;&lt;EOF | sudo tee /etc/sysctl.d/k8s.conf<br>net.bridge.bridge-nf-call-iptables  = 1<br>net.bridge.bridge-nf-call-ip6tables = 1<br>net.ipv4.ip_forward                 = 1<br>EOF</pre><pre>sudo sysctl --system</pre><h4>Autopilot disengage! The rest of the process is now different for the worker node :)</h4><p><strong>Restart and enable containerd:</strong></p><pre>systemctl restart containerd<br>systemctl enable containerd</pre><p><strong>Enable and start kubelet:</strong></p><pre>systemctl enable kubelet<br>systemctl start kubelet</pre><p><strong>Generate a </strong><strong>kubeadm join token:</strong></p><p>Now, back on the control-plane, run the following to generate the kubeadm join command you need to run from the worker to, well, join the cluster:</p><pre>root@control-plane:~# kubeadm token create --print-join-command<br>kubeadm join 68.183.173.104:6443 --token hhox4h.d82c0ecrxwld0kil --discovery-token-ca-cert-hash sha256:41559eeca5a2beb04554a43d426204753e136ae61fc1fd549e585e0100d15d9a</pre><p><strong>Add the worker node to the cluster:</strong></p><p>And, then, back on the worker, run the output:</p><pre>root@worker:~# kubeadm join 68.183.173.104:6443 --token hhox4h.d82c0ecrxwld0kil --discovery-token-ca-cert-hash sha256:41559eeca5a2beb04554a43d426204753e136ae61fc1fd549e585e0100d15d9a<br>[preflight] Running pre-flight checks<br>[preflight] Reading configuration from the cluster...<br>[preflight] FYI: You can look at this config file with &#39;kubectl -n kube-system get cm kubeadm-config -o yaml&#39;<br>[kubelet-start] Writing kubelet configuration to file &quot;/var/lib/kubelet/config.yaml&quot;<br>[kubelet-start] Writing kubelet environment file with flags to file &quot;/var/lib/kubelet/kubeadm-flags.env&quot;<br>[kubelet-start] Starting the kubelet<br>[kubelet-check] Waiting for a healthy kubelet at http://127.0.0.1:10248/healthz. This can take up to 4m0s<br>[kubelet-check] The kubelet is healthy after 1.00232212s<br>[kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap<br><br>This node has joined the cluster:<br>* Certificate signing request was sent to apiserver and a response was received.<br>* The Kubelet was informed of the new secure connection details.<br><br>Run &#39;kubectl get nodes&#39; on the control-plane to see this node join the cluster.</pre><p>Confirm that it’s a healthy, happy cluster! On the control-plane, run</p><pre>root@control-plane:~# kubectl get nodes<br>NAME            STATUS   ROLES           AGE   VERSION<br>control-plane   Ready    control-plane   23m   v1.30.14<br>worker          Ready    &lt;none&gt;          62s   v1.30.14</pre><p>Fancy!</p><p><strong>Make it prettier:</strong></p><p>Now, let’s get the worker’s ROLE defined as a worker. Back on the control-plane, run the following:</p><pre>kubectl label node worker node-role.kubernetes.io/worker=worker<br><br>kubectl get nodes<br>NAME            STATUS   ROLES           AGE     VERSION<br>control-plane   Ready    control-plane   26m     v1.30.14<br>worker          Ready    worker          3m24s   v1.30.14</pre><p>And like that, we have a working K8s cluster provisioned on bare metal (well, virtual bare metal, but you get my drift).</p><p><strong>One last step on the worker:</strong></p><p>Bypass default Digital Ocean VM DNS to stabilize the Cluster’s DNS resolution.</p><pre>sudo bash -c &#39;cat &lt;&lt;EOF &gt; /etc/kubelet-resolv.conf<br>nameserver 67.207.67.2<br>nameserver 67.207.67.3<br>EOF&#39;<br><br>sudo bash -c &#39;<br>grep -q &quot;^resolvConf:&quot; /var/lib/kubelet/config.yaml \<br>  &amp;&amp; sed -i &quot;s|^resolvConf:.*|resolvConf: /etc/kubelet-resolv.conf|&quot; /var/lib/kubelet/config.yaml \<br>  || echo &quot;resolvConf: /etc/kubelet-resolv.conf&quot; &gt;&gt; /var/lib/kubelet/config.yaml<br>&#39;</pre><p>Hope this is helpful! Happy K8s-ing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3616b2debb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do You Even AI, Bro? GenAI and Transformer Models for Mere Mortals]]></title>
            <link>https://medium.com/@jeff.d.vincent/do-you-even-ai-bro-genai-and-transformer-models-for-mere-mortals-d7575a4407c7?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7575a4407c7</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 03:55:28 GMT</pubDate>
            <atom:updated>2025-02-20T04:25:50.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92lV7Kq30nO5c-uzIai9tw.jpeg" /></figure><p>GenAI is, without a doubt, <em>the</em> big thing in tech. And while there is definitely value in learning how to dial in your prompts to the massive LLMs making headlines, there is at least as much value in learning how these black boxes actually work.</p><p>Whether you intend to actually develop LLMs yourself, maybe in the flavor of Small Language Models, which I myself happen to be particularly interested in, or if you just sense the value in better understanding this transformative technology, this post will walk you through some foundational concepts that will help you to get started.</p><h3>Vectors and Tensors</h3><p>First, you need to wrap your head around how machine learning models generally, and transformer models in particular, understand data. At a very basic level, these models understand representations of human input — not the direct input itself. These representations of human input can be mind bendingly complex if you let them be, or they can just be accepted as abstractions that consist of a sort of grid-like data structure of decimals that range between 0 and 1. Hint hint — we’re starting with the latter :)</p><p>Mathematically speaking, these decimals represent mappings in a highly dimensional space, and the specific points at which the individual values of a given tensor are plotted in that highly dimensional space dictate the ML model’s understanding of a given set of input data. But for us mere mortals, it is enough to know that there are a bunch of numerical values within a dense vector, and the model considers each of these values in combination to infer meaning.</p><p>But how does human input turn into a bunch of decimals, you might ask. Excellent question! The process of converting human input into machine readable data is called “embedding”, which follows on the heels of a process called “tokenization”.</p><p>And that brings us to our next key concept: <strong>tokenizers</strong>.</p><h3>Tokenizers</h3><p>Tokenizers do the work of converting human consumable data into tensors. The process is surprisingly simple, actually. Transformer models have something called a vocabulary that is basically a list of known words, or more likely, word parts and some information about what they mean and so on. Tokenizers simply take human input and map that input to tokens in the model’s vocabulary, which could look something like this:</p><pre>&quot;The cat runs away&quot; -&gt; [&quot;The&quot;, &quot;cat&quot;, &quot;runs&quot;, &quot;away&quot;] -&gt; [23, 4, 576, 1008]</pre><p>For simplicity’s sake, lets imagine that the model’s vocabulary happens to have a 1:1 mapping of each of the words in our input sequence, and the index of each of those entries are [23, 4, 576, 1008]. Boom! We’ve got us some tokens!</p><blockquote><strong>Key takeaway:</strong> different “families” of transformer models have different vocabularies. Some include full words; others include word parts. And some break input down to the byte level. SO… <strong>for the model to understand the tokens you pass to it, you have to generate those tokens with a tokenizer that is compatible with a given model.</strong></blockquote><p><strong>Start simple:</strong> when starting with transformer models, just load the tokenizer stored with the model. For example, for models stored on HuggingFace, your import statement would look something like this:</p><pre># Load model directly<br>from transformers import AutoTokenizer, AutoModelForSeq2SeqLM<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;google/flan-t5-small&quot;)<br>model = AutoModelForSeq2SeqLM.from_pretrained(&quot;google/flan-t5-small&quot;)</pre><p>Alright, now that we have some tokens, let’s move on to the embedding step!</p><h3>Embeddings</h3><p>Once we have our tokens, we need to convert them to a data type that represents all the qualities of a given token that it can recognize. To better understand this concept, think for a second about the word “train” (or any word for that matter) and all the elements of our understanding of the word.</p><p>We know in one sense of the word, it represents a thing that is large, that is mechanical, that has wheels, and that can’t cross oceans. Of course, we also know that in another sense of the word, it represents an action that results in the building or acquisition of new knowledge or skills. We know that if it is the noun, it must perform or receive some action to build a complete thought. And likewise, we know that if it is the verb, some noun must perform or receive some training. And we’ve built all of this understanding, and much much more, based on information we have acquired through interacting with this word “train” in different situations and settings. And over the course of those interactions with the word, we’ve developed an increasingly nuanced understanding of what it represents.</p><p>Turns out, GenAI works very much along those same lines. And the first step in allowing the transformer model to interact with a given token (think, word or word part) is to embed it into a complex data structure that represents those sorts of elements of understanding, which the model will have learned through a training process in which it interacted with that token time and time again in slightly different contexts. And through this process of repeated exposure to a given token, the model will have learned these sorts of aspects of the token, and it represents those elements as — you guessed it — a bunch of decimals!</p><p>And those decimals live in a data structure called a dense embedding. Technically speaking, each value represents a location on a axis in a distinct dimension, and the meaning captured in the data structure is derived from the relative distance between those points across dimensions. Kinda deep, but really, you can just accept that each numerical value in this abstract data structure is meaningful both independently and relative to the other numerical values in the data structure. Basically, <strong><em>the decimals are the meaning</em></strong>.</p><p>Annnnnd now, let’s move on the the process of generating these nifty data structures — the embedding layer. But first, let’s look at what layers in a transformer model are!</p><h3>Model Layers and Inference</h3><p>ML models generally and transformer models specifically are built from a collection of layers. Each layer contains a collection of — you guessed it, decimals! These decimals are called weights or params. And actually, when a GenAI model advertises itself as having <em>N</em> params, it’s these little guys that are being counted.</p><p>In a transformer model, there are basically four types of layers. There’s the embedding layer, which does the work of generating the dense vectors we just looked at. There is another, related layer — the positional embedding layer — which updates the values in that embedding to indicate the relative location of a given token in the input sequence (we’ll look at why this matters for transformers in a bit). Then, there are the transformer layers themselves, which are built from two separate components, a multi-head self-attention mechanism and a forward feed neural network. These pairs constitute the <em>N </em>transformer<em> </em>layers<em> </em>in the “body” of the model. And then there is the output layer, which does the job of converting the dense vectors back to their associated tokens ids.</p><p>Then, once the dense vector is established in the pass through the model, it moves through each of the <em>N</em> transformer layers one at a time. It is in this section that the model interprets the context in which a given token exists. The multi-head self-attention mechanism calculates how much each token should attend to every other token in the sequence. Each of the <em>N</em> heads produces a separate attention-weighted representation, which are then concatenated and linearly projected back into the model’s hidden size. In simpler terms, the attention heads each look at all of the tokens in the input sequence simultaneously, and they know the order of the tokens within the input sequence because of the positional data that was incorporated into the initially created vectors, and a major element of the self-attention mechanism is to calculate the contextual influence on the meaning of the tokens relative to the other tokens in the sequence.</p><p>This refined representation is then passed to a feed-forward neural network (FNN), which applies non-linearity and further transformations to improve the model’s ability to capture relationships between tokens. Finally, LayerNorm is applied before passing the processed vector to the next transformer layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*AK1npF_W-bkBG5-nKr0Wuw.jpeg" /></figure><p>And, again, this process is repeated for each transformer layer in the model, the number of which depends entirely on the architecture of the model itself.</p><p>And then, finally, the output layer takes all this nifty data, contextual learning included, applies a softmax probability function to the logits (ahem… decimals) that represent the model’s predictions, allowing it to select one token from its vocabulary that most likely should appear next in the sequence. Then, with this new token appended to the end of the original sequence of input IDs, the newly elongated sequence is fed back into the model. This process repeats again and again until the model selects a token that represents the end of the sequence or reaches its maximum output length. At that point, the final sequence of token IDs is returned as a tensor.</p><h3>Training</h3><p>Okay, you might be thinking, so there are these layers and each one has some decimals and all that, but what makes the decimals in these layers meaningful? I mean, what if they were just random decimals — would the model be able to infer anything from some input text?</p><p>And the answer is, nope. You’re totally right. The params in the model have to be adjusted to become meaningful. In fact, when a model is first created, the params <em>are random. </em>So, the “meaning” they infer is complete gibberish. And the process of adjusting the params in the model only comes with training. Lots and lots of training.</p><p>Interestingly, training is actually very similar to running an inference process with a model in in a lot of ways. The human generated data is fed into the model in the same way, and that data is embedded into a dense vector in the same way. That dense vector moves through each of the layers in the model, and ultimately a probability function drives the selection of the model’s interpretation of the best next token to add to the input sequence — again, all the same so far. But then the workflow diverges from the inference flow, and instead of continuing to cycle the gradually elongated input sequence through the model or returning it, the training flow involves comparing the model’s output with the expected output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8T17m1UMa8cycoR0IYK12w.jpeg" /></figure><p>This comparison step results in a value referred to as the loss, which represents the relative similarity of the model’s output to the expected output. Then, this loss value is fed backward though the model in such a way that it slightly modifies (the degree of the modification, referred to as the learning rate is user defined) to incrementally adjust the model’s output to better align with the expected output.</p><p>This process is repeated time and again on, generally speaking, enormous amounts of data and on each pass the model gradually “learns” more and more contextual information about a given word. Training is, of course, far more complex than this, but as we’re just getting started, this is the essence of the process.</p><h3>You don’t have to get all that to start!</h3><p>In fact, if you can understand all of that in your first pass, kudos to you. Either way, though, now that you have some sense of the various parts of transformer models and the very basics of how GenAI actually works under the hood, let’s take a small model for a test drive, shall we?</p><p>To get started, open this <a href="https://colab.research.google.com/drive/1dYUhRNrPxUAL8PYkvBJ3haRErVmzxk53?usp=sharing">Google Colabs notebook</a>, and click the “play” button on each code cell. Until next time, happy tinkering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7575a4407c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Why and How of Sync and Async Networking with Microservices (in Python)]]></title>
            <link>https://medium.com/@jeff.d.vincent/the-why-and-how-of-sync-and-async-networking-with-microservices-in-python-635b545c3dd7?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/635b545c3dd7</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[networking-tips]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 01:35:39 GMT</pubDate>
            <atom:updated>2024-11-26T02:58:39.193Z</atom:updated>
            <content:encoded><![CDATA[<p>In any user-facing application, there will be processes that need to return a result to the user as quickly as possible. But as applications add features and become more complex, there will very likely be processes that don’t need to return a result to the end user immediately. And recognizing which services fall into this category and handling them appropriately will enhance your application’s ability to deliver results that the user does expect immediately all that much faster.</p><h3>The project</h3><p>To demonstrate this concept, let’s build a simple blog — I need to build one anyway, so why not :) This blog will have some basic functionality. First, it will serve blog posts requested by the user to the browser. And second, it will store some metrics related to post views and such.</p><p>Our app will have three endpoints (I’ll beef it up before I deploy it for real, but this will be enough to demonstrate this concept). One endpoint will accept a POST request which we can use to upload blog posts. The second will accept a GET request, which a reader can use to request a post by name, and the third will be an “admin” endpoint that will return some basic metrics about blog views.</p><h3>Sync or Async?</h3><p>So, with that, let’s talk about which routes will utilize synchronous networking and which will leverage the power of async networking! As contentious blog folks, we know that our readers expect to see a blog post when they request one. And to facilitate that, we’ll use synchronous networking from our “main” API service directly to the database where we’ll be storing the uploaded posts.</p><p>On the other hand, we don’t need metrics to be delivered immediately, cause we’re patient blog admins. Moreover, we’ll need to update our records of post views on every view, but we won’t very likely be accessing metrics nearly as often. So, we’ll leverage some nifty async networking with our old friend Redis and a database worker service in addition to our “main” API service.</p><p>It will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ByNds7WSy0NFt3Ezr8DiWQ.png" /></figure><p>So, our routes to add a blog post, read a blog post and read metrics data will be handed with direct calls to the database, and thus synchronous networking (because we’re keeping everything sync in our code to keep the illustration simple). And every time a reader requests a given blog post, we will run an async workflow which will update the blog metrics we’re also storing in the database.</p><h3>Cool, now let’s write some code already!</h3><p><em>For those who prefer to tinker with a built app, you can </em><a href="https://github.com/jeff-vincent/fastapi-redis-blog"><em>clone the project here</em></a><em>.</em></p><p>First, let’s write our “main” API as a simple FastAPI app. We’ll write some basic CRUD functionality, and a slightly more interesting helper function _update_post_metrics that we’ll pass the FastAPI’s built in BackgroundTasks, which spawns a new <a href="https://docs.python.org/3/library/asyncio.html">Asyncio</a> <a href="https://docs.python.org/3/library/asyncio-eventloop.html">event loop</a>, so as to run that process concurrently. And, aside from the Asyncio goodness, the cool part of this helper function is the <a href="https://redis.io/docs/latest/commands/rpush/">Redis RPUSH functionality</a> that allows us to push data to a Redis message queue channel we’re calling “metrics”.</p><pre>import json<br>from fastapi import FastAPI, Request, BackgroundTasks<br>from redis import Redis<br>from db import posts_collection, metrics_collection<br>from utils import process_metrics<br>from bson import json_util<br><br>from fastapi.middleware.cors import CORSMiddleware<br>from fastapi.encoders import jsonable_encoder<br><br>origins = [<br>    &quot;http://localhost&quot;,<br>    &quot;http://localhost:3000/&quot;,<br>    &quot;http://localhost:3000&quot;,<br>    &quot;http://localhost:3000/create&quot;,<br>]<br><br>app = FastAPI()<br><br># Add CORS middleware to the application<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br>redis = Redis()<br><br>@app.post(&#39;/api/v1/post&#39;)<br>async def create_post(request: Request):<br>    data = await request.json()<br>    posts_collection.insert_one(data)<br>    return {&quot;message&quot;: &quot;Post created successfully&quot;}<br><br>@app.get(&#39;/api/v1/posts&#39;)<br>def get_all_posts():<br>    posts = posts_collection.find({})<br>    result = json.loads(json_util.dumps(list(posts)))<br>    print(result)<br>    return result<br><br>@app.get(&#39;/api/v1/post/{id}&#39;)<br>def get_post_by_id(request: Request, id: int, backgroundtasks: BackgroundTasks):<br>    post = posts_collection.find_one({&quot;id&quot;: id})<br>    if post:<br>        backgroundtasks.add_task(_update_post_metrics, request)<br>        result = json_util.dumps(post)<br>        r = json.loads(result)<br>        response = {}<br>        response[&#39;title&#39;] = r.get(&#39;title&#39;)<br>        response[&#39;body&#39;] = r.get(&#39;body&#39;)<br>        response[&#39;author&#39;] = r.get(&#39;author&#39;)<br>        return response<br>    else:<br>        return {&quot;error&quot;: &quot;Post not found&quot;}<br><br>async def _update_post_metrics(request: Request):<br>    data = {<br>        &quot;headers&quot;: request.headers,<br>        &quot;path_params&quot;: request.path_params,<br>    }<br>    json_data = jsonable_encoder(data)<br>    redis.rpush(&quot;metrics&quot;, json.dumps(json_data))<br>    return None<br><br>@app.get(&#39;/api/v1/metrics/{id}&#39;)<br>async def get_post_metrics(id: str):<br>    data = metrics_collection.find({&quot;path_params.id&quot;: id})<br>    if data:<br>        processed_data = process_metrics(data)<br>        print(processed_data)<br>        return processed_data<br>    else:<br>        return {&quot;error&quot;: &quot;No metrics found&quot;}<br>    <br>@app.get(&#39;/api/v1/metrics&#39;)<br>async def get_post_metrics():<br>    data = metrics_collection.find({})<br>    if data:<br>        processed_data = process_metrics(data)<br>        print(processed_data)<br>        return processed_data<br>    else:<br>        return {&quot;error&quot;: &quot;No metrics found&quot;}<br></pre><p>Next, we’ll need to write db.py, which will contain our MongoDB connection details and such.</p><pre>import os<br>import pymongo<br><br><br>MONGO_PASSWORD = os.environ.get(&#39;MONGODB_PASSWORD&#39;)<br><br>def init_db():<br>    client = pymongo.MongoClient(f&quot;mongodb+srv://&lt;username&gt;:{MONGO_PASSWORD}@&lt;IP Address&gt;&quot;)<br>    db = client.admin_database<br>    posts_collection = db.posts<br>    metrics_collection = db.metrics<br><br>    try:<br>        posts_collection.create_index(&quot;title&quot;, unique=True)<br>    except Exception as e:<br>        print(f&quot;Error creating indexes: {e}&quot;)<br><br>    <br>    return posts_collection, metrics_collection<br><br>posts_collection, metrics_collection = init_db()</pre><p>Notice that we’re creating a <a href="https://www.mongodb.com/docs/manual/core/index-unique/">unique index</a> on the title field in our posts collection, which allows us to enforce a unique value rule here — i.e. titles have to be unique.</p><p>And then, we’ll need to go ahead and define our worker instance that will listen to the Redis message queue and will process data in a first in first out (FIFO) manner. Moreover, when it reads from the “metrics” queue, it will pop the item from the queue (with the <a href="https://redis.io/docs/latest/commands/blpop/">Redis BLPOP functionality</a>), so that if we have multiple workers listening to the queue, each job will be processed once and only once.</p><pre>import json<br>import time<br>from redis import Redis<br>from db import metrics_collection, posts_collection<br>from bson import json_util<br><br>redis = Redis()<br><br>def get_post_info(id):<br>    post = posts_collection.find_one({&quot;id&quot;: int(id)})<br>    data = json.loads(json_util.dumps(post))<br>    return data<br><br>while True:<br>    key, data = redis.blpop(&quot;metrics&quot;, timeout=0)<br>    if data:<br>        print(f&quot;Processing data from {key}&quot;)<br>        data = data.decode(&quot;utf8&quot;)<br>        data = json.loads(data)<br>        data[&#39;time&#39;] = time.time()<br>        post_data = get_post_info(data[&#39;path_params&#39;][&#39;id&#39;])<br>        data[&#39;author&#39;] = post_data[&#39;author&#39;]<br>        data[&#39;title&#39;] = post_data[&#39;title&#39;]<br>        metrics_collection.insert_one(data)</pre><p>And the worker will also need a MongoDB client, so let’s define that next.</p><pre>import os<br>import pymongo<br><br><br>MONGO_PASSWORD = os.environ.get(&#39;MONGODB_PASSWORD&#39;)<br><br>def init_db():<br>    client = pymongo.MongoClient(f&quot;mongodb+srv://jeffdvincent:{@cluster0.8xe9o.mongodb.net&quot;&gt;MONGO_PASSWORD}@cluster0.8xe9o.mongodb.net/?retryWrites=true&amp;w=majority&amp;appName=Cluster0&quot;)<br>    db = client.admin_database<br>    metrics_collection = db.metrics<br>    posts_collection = db.posts<br>    <br>    return metrics_collection, posts_collection<br><br>metrics_collection, posts_collection = init_db()</pre><p>Notice that even though we’re just writing our metrics data to the metrics_collection we also have our posts_collection defined here. This is an optimization for processing the metrics data that allows us to query the posts_collection for some additional metadata we want to store with the metrics data as the data is written, rather than bulk querying when we request the metrics data from the browser (makes for a much better UX if I do say so myself :) ).</p><p>And finally, we need a frontend to do all the things. For this, I created a simple React app with React-Router routes for creating a blog post, viewing all posts, viewing a single post and viewing metrics data. It’s a bit much to include all the code in this post, but do feel free to check out the repo.</p><p>As a sample of the React app portion of this project, here’s the App.js file with the React-Router routes defined.</p><pre>import React from &#39;react&#39;;<br>import { BrowserRouter as Router, Route, Routes } from &#39;react-router-dom&#39;;<br>import Posts from &#39;./components/posts&#39;;<br>import Post from &#39;./components/post&#39;;<br>import Editor from &#39;./components/textEditor&#39;;<br>import MetricsDashboard from &#39;./components/metricsDashboard&#39;;<br><br>const App = () =&gt; {<br>  return (<br>      &lt;Router&gt;<br>        &lt;div&gt;<br>          &lt;Routes&gt;<br>            &lt;Route exact path=&quot;/&quot; element={&lt;Posts /&gt;} /&gt;<br>            &lt;Route exact path=&quot;/post/:id&quot; element={&lt;Post /&gt;} /&gt;<br>            &lt;Route exact path=&quot;/create&quot; element={&lt;Editor /&gt;} /&gt;<br>            &lt;Route exact path=&quot;/metrics&quot; element= {&lt; MetricsDashboard /&gt;} /&gt;<br>          &lt;/Routes&gt;<br>        &lt;/div&gt;<br>      &lt;/Router&gt;<br>  );<br>};<br><br>export default App;</pre><p>And here’s the Posts component for good measure:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import { Link } from &#39;react-router-dom&#39;;<br>import Header from &#39;./header.js&#39;;<br><br>const Posts = () =&gt; {<br>  // Fetching data from an API<br>  const [posts, setPosts] = useState([]);<br><br>  useEffect(() =&gt; {<br>    fetch(&#39;/api/v1/posts&#39;)<br>      .then((response) =&gt; response.json())<br>      .then((data) =&gt; setPosts(data))<br>      .catch((error) =&gt; console.error(&#39;Error:&#39;, error));<br>  }, []);<br><br>  console.log(posts);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        &lt; Header/&gt;<br>      &lt;/div&gt;<br>    &lt;div className=&quot;bg-gray-100 min-h-screen py-12&quot;&gt;<br>      &lt;div className=&quot;container max-w-6xl mx-auto px-6&quot;&gt;<br>        &lt;div className=&quot;grid gap-8 grid-cols-1 md:grid-cols-2 lg:grid-cols-3&quot;&gt;<br>          {posts.map((post) =&gt; {<br>            return post.redirect_url ? (<br>              &lt;Link<br>                to={post.redirect_url}<br>                key={post.id}<br>                className=&quot;bg-white rounded-xl shadow-md p-6 hover:shadow-lg transition-shadow duration-300 cursor-pointer block&quot;<br>              &gt;<br>                &lt;h2 className=&quot;text-2xl font-bold text-gray-800 mb-4&quot;&gt;{post.title}&lt;/h2&gt;<br>                &lt;p className=&quot;text-gray-700&quot; dangerouslySetInnerHTML={{ __html: post.summary }} /&gt;<br>              &lt;/Link&gt;<br>            ) : (<br>              &lt;Link<br>                to={`/post/${post.id}`}<br>                key={post.id}<br>                className=&quot;bg-white rounded-xl shadow-md p-6 hover:shadow-lg transition-shadow duration-300 cursor-pointer block&quot;<br>              &gt;<br>                &lt;h2 className=&quot;text-2xl font-bold text-gray-800 mb-4&quot;&gt;{post.title}&lt;/h2&gt;<br>                &lt;p className=&quot;text-gray-700&quot; dangerouslySetInnerHTML={{ __html: post.summary }} /&gt;<br>              &lt;/Link&gt;<br>            );<br>          })}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};  <br><br>export default Posts;</pre><p>Annnd finally, we need our MongoDB and Redis instances. For these, we can simply navigate to <a href="https://www.mongodb.com/">mongodb.com</a> and <a href="https://redis.io/">redis.io</a> respectively and spin up free cloud resources. Once you create your resources, you’ll just need to update the main.py and db.py files for both the api and the worker.</p><p>And with those pieces in place, we have a working example of both syncronous and asynchronous networking in a web application — and why you would use each of these approaches.</p><h3>Learning Summary</h3><p>To wrap up, we covered why you would use sync vs. async networking. Basically, some processes need to run and be returned to the user immediately, and some don’t. Moreover, by not running all processes synchronously, we free up our application to run those processes that <em>do </em>need to return results all that much faster, as they aren’t waiting for all processes to complete first.</p><p>To accomplish this, we leveraged Redis as a message queue and we used the RPUSH and BLPOP functionality to ensure that each job (page view in our case) is processed by our async worker in the order it was received and that each job is processed only once. This bit becomes important in complex architectures with elastic pools of worker instances (like you would find in a K8s deployment, for example).</p><p>And finally, we wrote a nice looking frontend to demonstrate the functionality from the comfort of the browser :)</p><p>To see the app in action and to tinker to your heart’s content, <a href="https://github.com/jeff-vincent/fastapi-redis-blog">check out the repo</a>. It has all the info you need to run the app locally :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=635b545c3dd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Intro to Kubernetes Native Applications (with Python)]]></title>
            <link>https://medium.com/@jeff.d.vincent/an-intro-to-kubernetes-native-applications-with-python-a5fe63ac1593?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5fe63ac1593</guid>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 01:27:27 GMT</pubDate>
            <atom:updated>2024-11-20T16:02:51.022Z</atom:updated>
            <content:encoded><![CDATA[<p>Just about any application can be run in Kubernetes. If it runs on Linux, or — with infrastructure extensions deployed to your K8s cluster — even if it doesn’t, it can probably run in Kubernetes. So, what makes an application Kubernetes native?</p><p>To understand this, you have to have a basic understanding of how Kubernetes works. Namely, Kubernetes clusters expose an API — most commonly interacted with via the command line tool kubectl. It is fancy to be sure, but as this is still just an API, you can interact with it in just about any programming language. Moreover, the Kubernetes community maintains various software development kits (SDKs) that streamline developing applications that interact with the Kubernetes API.</p><p>So, now, we have two distinct qualities that — when combined — result in a K8s native application. First, the app has to run in Kubernetes. And second, it has to interact programmatically (from within a deployed K8s cluster) with the Kubernetes API. This way, an application that is running in K8s can programmatically manage the infrastructure on which it runs. Super meta, I know.</p><h3>Sounds cool, but why build an app this way?</h3><p>Good question! There are a variety of reasons to build an app this way, but one of the most interesting centers around the idea of running processes within your application in isolation. Because Kubernetes is really just a system for dividing and subdividing a pool of compute resources and networking between the resources that constitute those sub-pools, Kubernetes-native applications are an excellent way to run specific application processes that cannot run alongside the “core” of your application. This could be for security reasons, application requirements generally or anything really.</p><p>For example, consider an application that provides end users with personalized cloud environments for running processes that they create via your application. By design, these processes need to be run in a distinct and isolated environment from the application processes that are responsible for spinning up and maintaining each individual user’s cloud environment itself.</p><p>To solve this problem of isolating application processes, we can turn to Kubernetes native application design in which the “core” backend of our app spins up isolated environments for each user, and forwards requests from the end user to the specific K8s object that houses their personal compute environment. That way, we can have granular control of what processes can run in each user’s environment, and we have a way to run them entirely independently from the “core” of our application. Moreover, when a user in such an application completes a session, we can pause or tear down the isolated user env with a relatively simple call to the Kubernetes API from within the cluster. Pretty neat, huh!?!</p><h3>Umm… how about a real world example?</h3><p>As a matter of fact, I just happen to have one that you can dig through. Here’s <a href="https://github.com/jeff-vincent/PyProdigy">the repo</a>, and here’s <a href="https://pyprodigy.dev/">the app deployed to production</a>.</p><p>And to get a better sense of how it works, let’s build a simple version of our own. First, let’s define a simple FastAPI app that will have two endpoints — one for spinning up a Pod (just an arbitrary example) in K8s, and another for tearing that Pod down.</p><pre>import fastapi<br>import os<br><br>from kubernetes import client, config<br><br>app = fastapi.FastAPI()<br><br># Initialize a Kubernetes client<br># Check if running inside a Kubernetes cluster<br>if &#39;KUBERNETES_SERVICE_HOST&#39; in os.environ and &#39;KUBERNETES_SERVICE_PORT&#39; in os.environ:<br>    # Load the in-cluster configuration<br>    config.load_incluster_config()<br>else:<br>    # Load the kubeconfig file<br>    config.load_kube_config()<br><br># Create the Kubernetes API client<br>k8s_client = client.ApiClient()<br><br>@app.get(&#39;/create-pod/{pod_name}&#39;)<br>async def create_pod(pod_name: str):<br>    pod_manifest = _create_pod_manifest(pod_name)<br>    api_instance = client.CoreV1Api(k8s_client)<br>    api_instance.create_namespaced_pod(namespace=&quot;default&quot;, body=pod_manifest)<br><br>@app.get(&#39;/delete-pod/{pod_name}&#39;)<br>async def delete_pod(pod_name: str):<br>    api_instance = client.CoreV1Api(k8s_client)<br>    api_instance.delete_namespaced_pod(name=pod_name, namespace=&quot;default&quot;)<br><br>def _create_pod_manifest( pod_name: str) -&gt; client.V1Pod:<br>    main_container = client.V1Container(<br>        name=pod_name,<br>        image=&quot;ubuntu&quot;,<br>        command=[&quot;tail&quot;, &quot;-f&quot;, &quot;/dev/null&quot;],  # Keep the main container running indefinitely<br>        resources=client.V1ResourceRequirements(<br>            requests={&quot;cpu&quot;: &quot;10m&quot;, &quot;memory&quot;: &quot;32Mi&quot;},<br>            limits={&quot;cpu&quot;: &quot;40m&quot;, &quot;memory&quot;: &quot;64Mi&quot;},<br>        ),<br>    )<br><br>    pod_spec = client.V1PodSpec(<br>        containers=[main_container],<br>        restart_policy=&quot;Never&quot;,<br>        service_account_name=&quot;default&quot;,<br>    )<br><br>    pod_manifest = client.V1Pod(<br>        metadata=client.V1ObjectMeta(name=pod_name),<br>        spec=pod_spec,<br>    )<br><br>    return pod_manifest</pre><p>Now let’s quickly Dockerize it and deploy it to a local Kubernetes cluster.</p><p>First, we’ll need to define a Dockerfile , like so:</p><pre>FROM python<br><br>COPY . . <br><br>RUN pip install -r requirements.txt<br><br>CMD uvicorn main:app --port 8080</pre><p>Then we’ll need to build and push the Docker image to a registry, like so:</p><pre>docker buildx build --platform linux/amd64 -t &lt;username&gt;/k8s-example:latest . --push</pre><p>Then, we’ll need to define a K8s Deployment in a file called deployment.yaml that will run our new image, like so:</p><pre>apiVersion: v1<br>kind: List<br>items:<br>  - apiVersion: apps/v1<br>    kind: Deployment<br>    metadata:<br>      name: k8s-native<br>      labels:<br>        api: k8s-native<br>    spec:<br>      selector:<br>        matchLabels:<br>          api: k8s-native<br>      replicas: 1<br>      template:<br>        metadata:<br>          labels:<br>            api: k8s-native<br>        spec:<br>          containers:<br>            - name: k8s-native<br>              image: jdvincent/k8s-example:latest<br>              imagePullPolicy: Always<br>              ports:<br>                - name: k8s-native<br>                  containerPort: 8080<br>                  protocol: TCP</pre><p>Annnd we’ll need to give it permission to create the resources we’re requesting by creating a Role and RoleBinding and such, like so:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: pod-creator-role<br>  namespace: default<br>rules:<br>- apiGroups:<br>  - &quot;&quot;<br>  resources:<br>  - pods<br>  verbs:<br>  - create<br>  - delete<br>  - list<br>  - get<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: pod-creator-role-binding<br>  namespace: default<br>subjects:<br>- kind: ServiceAccount<br>  name: default<br>  namespace: default<br>roleRef:<br>  kind: Role<br>  name: pod-creator-role<br>  apiGroup: rbac.authorization.k8s.io<br>---<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: default<br>  namespace: default</pre><p>You can name the above permissions.yaml and apply it to the cluster by running kubectl apply -f permissions.yaml.</p><p>And now that our little app is running, we can go ahead and exec into its Pod and hit the create-pod endpoint to spin up a new pod programmatically from within the cluster, like so:</p><pre>kind create cluster<br>kubectl apply -f deployment.yaml</pre><p>And once it’s in a RUNNING state, we can exec in and hit the create pod endpoint, like so:</p><pre>kubectl exec -it &lt;pod-full-name&gt; -- /bin/bash<br><br>python<br><br>&gt;&gt;&gt;import requests<br>&gt;&gt;&gt;r = requests.get(&#39;http://localhost:8080/create-pod/test&#39;)<br>&gt;&gt;&gt;</pre><p>Then, from a second terminal window, run the following to see your new pod up and running:</p><pre>kubectl get pods</pre><pre>NAME                              READY   STATUS        RESTARTS   AGE<br>pod/k8s-native-7747b9bf8d-5487z   1/1     Running       0          1m<br>pod/test  </pre><p>And there you have it! An API running in Kubernetes that can interact with the Kubernetes API to manage the infrastructure on which our little app runs! Pretty neat, huh!?!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5fe63ac1593" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Up your K8s Game with Multi-Cluster Deployments Networked via an Istio Service Mesh]]></title>
            <link>https://medium.com/@jeff.d.vincent/up-your-k8s-game-with-multi-cluster-deployments-networked-via-an-istio-service-mesh-13fe40b57b4b?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/13fe40b57b4b</guid>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 01:22:48 GMT</pubDate>
            <atom:updated>2024-11-18T03:58:33.349Z</atom:updated>
            <content:encoded><![CDATA[<p>Kubernetes is inherently fault-tolerant, but for teams that require increased resilience in their deployments, deploying a service mesh that allows K8s services to be networked with each other across clusters can be a powerful approach.</p><h4>What you get</h4><p>By deploying applications or cloud resources across multiple clusters, you have the ability to increase uptime in the event of a cloud provider’s regional outage. Moreover, you have the ability to deploy resources with granular control geographically, which can serve to reduce latency and thereby improve perceived application performance. And finally, by deploying a service mesh as we are, all traffic will be secure as it will be HTTPS, and thus encrypted while in transit.</p><h4>Where to start</h4><p>Today, we’ll walk through deploying an Istio service mesh across two locally deployed clusters. To spin up two clusters on our local machine easily, we’ll spin up one Kind cluster and a separate Minikube cluster — each of which will be running in Docker on our local machine.</p><p>If you’re working on a Mac and you don’t have either of these resources installed, you can simply install with HomeBrew as follows:</p><pre>brew instsall kind<br>brew install minikube</pre><p>Then, to spin up your clusters, you’ll need to run the following:</p><pre>kind create cluster<br>minikube start</pre><p>If you open the Docker dashboard (or run docker ps in a terminal window) you’ll see that two Docker containers are running — each of which contains a running instance of Kubernetes.</p><p>In order to point kubectl at each cluster respectively, you can run the following:</p><pre>kubectl config get-contexts</pre><p>This should return the contents of your kubeconfig file, which should now contain at least these two clusters. If you ran the above commands exactly, the clusters will be named `minikube` and `kind-kind` respectively.</p><p>To submit commands to the kind cluster, simply set your Kubernetes context to that cluster, like so:</p><pre>kubectl config use-context kind-kind</pre><p>And to submit commands to the Minikube cluster, simply run the following:</p><pre>kubectl config use-context minikube</pre><p>Next, set the following environment variables, download, and install Istio on your local machine:</p><pre>export CTX_CLUSTER1=minikube<br>export CTX_CLUSTER2=kind-kind<br>export CLUSTER1_SERVER=http://127.0.0.1:50375/ # Update with the Container IP of your Minikube Cluster<br>export CLUSTER2_SERVER=http://127.0.0.1:50370/ # Update with the Container IP of your Kind Cluster<br>export ISTIO_VERSION=1.24.0<br><br>curl -L https://istio.io/downloadIstio | ISTIO_VERSION=${ISTIO_VERSION} sh -</pre><p>Next change directories into the newly created Istio directory, and create a directory to house your required <a href="https://istio.io/latest/docs/tasks/security/cert-management/plugin-ca-cert/">CA certs</a>:</p><pre>cd istio-1.24.0<br>mkdir -p certs &amp;&amp; cd certs</pre><p>And use the Istio-supplied Makefile to create the certs:</p><pre>make -f ../tools/certs/Makefile.selfsigned.mk root-ca<br>make -f ../tools/certs/Makefile.selfsigned.mk ${CTX_CLUSTER1}-cacerts<br>make -f ../tools/certs/Makefile.selfsigned.mk ${CTX_CLUSTER2}-cacerts</pre><p>Then, you’ll need to create a Kubernetes namespace in each of your clusters for Istio resources. We’ll call it istio-system. And then, we’ll go ahead and add our newly generated CA certs as K8s Secrets to each of our clusters, like so:</p><pre>kubectl --context=&quot;${CTX_CLUSTER1}&quot; create ns istio-system<br>kubectl --context=&quot;${CTX_CLUSTER1}&quot; create secret generic cacerts -n istio-system \<br>    --from-file=${CTX_CLUSTER1}/ca-cert.pem \<br>    --from-file=${CTX_CLUSTER1}/ca-key.pem \<br>    --from-file=${CTX_CLUSTER1}/root-cert.pem \<br>    --from-file=${CTX_CLUSTER1}/cert-chain.pem<br><br>kubectl --context=&quot;${CTX_CLUSTER2}&quot; create ns istio-system<br>kubectl --context=&quot;${CTX_CLUSTER2}&quot; create secret generic cacerts -n istio-system \<br>    --from-file=${CTX_CLUSTER2}/ca-cert.pem \<br>    --from-file=${CTX_CLUSTER2}/ca-key.pem \<br>    --from-file=${CTX_CLUSTER2}/root-cert.pem \<br>    --from-file=${CTX_CLUSTER2}/cert-chain.pem</pre><p>With our certs in place, we can now deploy our Istio operators to each cluster. Note that we are deploying our service mesh in a primary-primary configuration.</p><pre>cd .. # change directories</pre><pre><br>kubectl --context=&quot;${CTX_CLUSTER1}&quot; get namespace istio-system &amp;&amp; \<br>    kubectl --context=&quot;${CTX_CLUSTER1}&quot; label namespace istio-system topology.istio.io/network=network1    <br><br>cat &lt;&lt;EOF &gt; cluster1.yaml<br>apiVersion: install.istio.io/v1alpha1<br>kind: IstioOperator<br>spec:             <br>  meshConfig:                      <br>    defaultConfig:  <br>      terminationDrainDuration: 30s         <br>      proxyMetadata:                  <br>        ISTIO_META_DNS_AUTO_ALLOCATE: &quot;true&quot;<br>        ISTIO_META_DNS_CAPTURE: &quot;true&quot;<br>  values:          <br>    global:        <br>      meshID: mesh1          <br>      multiCluster:    <br>        clusterName: cluster1<br>      network: network1                                             <br>EOF<br><br>bin/istioctl install --context=&quot;${CTX_CLUSTER1}&quot; -f cluster1.yaml -y</pre><pre>kubectl --context=&quot;${CTX_CLUSTER2}&quot; get namespace istio-system &amp;&amp; \<br>    kubectl --context=&quot;${CTX_CLUSTER2}&quot; label namespace istio-system topology.istio.io/network=network1<br><br><br>cat &lt;&lt;EOF &gt; cluster2.yaml<br>apiVersion: install.istio.io/v1alpha1<br>kind: IstioOperator<br>spec:<br>  meshConfig:<br>    defaultConfig:<br>      terminationDrainDuration: 30s<br>      proxyMetadata:<br>        ISTIO_META_DNS_AUTO_ALLOCATE: &quot;true&quot;<br>        ISTIO_META_DNS_CAPTURE: &quot;true&quot;<br>  values:<br>    global:<br>      meshID: mesh1<br>      multiCluster:<br>        clusterName: cluster2<br>      network: network1<br>EOF<br><br>bin/istioctl install --context=&quot;${CTX_CLUSTER2}&quot; -f cluster2.yaml -y</pre><p>In the above, we have defined two Kubernetes objects of the kind IstioOperator and deployed one to each of our two local Kubernetes clusters. Also note that we have labeled the istio-system namespace in each of our clusters as follows: topology.istio.io/network=network1.</p><p>Next, we’ll need to deploy the resources defined in the Istio-provided expose-services.yaml to each cluster, like so:</p><pre>kubectl --context=&quot;${CTX_CLUSTER1}&quot; apply -n istio-system \<br>    -f samples/multicluster/expose-services.yaml<br><br>kubectl --context=&quot;${CTX_CLUSTER2}&quot; apply -n istio-system \<br>    -f samples/multicluster/expose-services.yaml</pre><p>Then, we’ll need to run the provided gen-eastwest-gateway.sh for each cluster:</p><pre>samples/multicluster/gen-eastwest-gateway.sh \<br>    --mesh mesh1 --cluster cluster1 --network network1 | \<br>    bin/istioctl --context=&quot;${CTX_CLUSTER1}&quot; install -y -f -<br><br>samples/multicluster/gen-eastwest-gateway.sh \<br>    --mesh mesh1 --cluster cluster1 --network network1 | \<br>    bin/istioctl --context=&quot;${CTX_CLUSTER2}&quot; install -y -f -</pre><p>And, finally, we can go ahead and deploy the CA cert secrets each cluster will need to validate traffic from the other for HTTPS networking:</p><pre>bin/istioctl create-remote-secret \<br>    --context=&quot;${CTX_CLUSTER2}&quot; -n istio-system \<br>    --server=&quot;${CLUSTER2_SERVER}&quot; --name=&quot;cluster2&quot; | \<br>    kubectl apply -f - --context=&quot;${CTX_CLUSTER1}&quot;<br><br>bin/istioctl create-remote-secret \<br>    --context=&quot;${CTX_CLUSTER1}&quot; -n istio-system \<br>    --server=&quot;${CLUSTER1_SERVER}&quot; --name=cluster1 | \<br>    kubectl apply -f - --context=&quot;${CTX_CLUSTER2}&quot;</pre><h4>Let’s test it out!</h4><p>Now that we have all of the above in place, we should be able to send a Curl request from each cluster to the other just as if the services handling the requests were deployed to the same cluster.</p><p>First, let’s go ahead and create a namespace in each cluster to house our test services:</p><pre>kubectl create --context=&quot;${CTX_CLUSTER1}&quot; namespace sample<br>kubectl create --context=&quot;${CTX_CLUSTER2}&quot; namespace sample</pre><p>Then, we’ll need to deploy a couple of services to each cluster — namely a curl application and service and a hello-world application and service to send and handle requests to and from each Kubernetes cluster respectively.</p><pre>kubectl apply --context=&quot;${CTX_CLUSTER1}&quot; \<br>    -f samples/helloworld/helloworld.yaml \<br>    -l service=helloworld -n sample<br><br>kubectl apply --context=&quot;${CTX_CLUSTER2}&quot; \<br>    -f samples/helloworld/helloworld.yaml \<br>    -l service=helloworld -n sample</pre><pre>kubectl apply --context=&quot;${CTX_CLUSTER1}&quot; \<br>    -f samples/helloworld/helloworld.yaml \<br>    -l version=v1 -n sample<br><br>kubectl apply --context=&quot;${CTX_CLUSTER2}&quot; \<br>    -f samples/helloworld/helloworld.yaml \<br>    -l version=v2 -n sample</pre><pre>kubectl apply --context=&quot;${CTX_CLUSTER1}&quot; \<br>    -f samples/curl/curl.yaml -n sample<br><br>kubectl apply --context=&quot;${CTX_CLUSTER2}&quot; \<br>    -f samples/curl/curl.yaml -n sample</pre><p>And then we’ll need to enable Istio to inject sidecar containers into our running K8s Pods:</p><pre>kubectl label --context=&quot;${CTX_CLUSTER1}&quot; namespace sample \<br>    istio-injection=enabled<br><br>kubectl label --context=&quot;${CTX_CLUSTER2}&quot; namespace sample \<br>    istio-injection=enabled</pre><h4>And now for the test!</h4><p>To verify traffic can pass from cluster1 to cluster2, run the following:</p><pre>kubectl exec --context=&quot;${CTX_CLUSTER1}&quot; -n sample -c curl \<br>    &quot;$(kubectl get pod --context=&quot;${CTX_CLUSTER1}&quot; -n sample -l \<br>    app=curl -o jsonpath=&#39;{.items[0].metadata.name}&#39;)&quot; \<br>    -- curl -sS helloworld.sample:5000/hello</pre><p>And to verify traffic can pass from cluster2 to cluster1, run the following:</p><pre>kubectl exec --context=&quot;${CTX_CLUSTER2}&quot; -n sample -c curl \<br>    &quot;$(kubectl get pod --context=&quot;${CTX_CLUSTER2}&quot; -n sample -l \<br>    app=curl -o jsonpath=&#39;{.items[0].metadata.name}&#39;)&quot; \<br>    -- curl -sS helloworld.sample:5000/hello</pre><p><strong>And Shazzam!</strong> We’ve got two Kubernetes clusters that can securely discover and deliver HTTPS traffic to and from each other!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13fe40b57b4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy your K8s app with an Ingress on Digital Ocean]]></title>
            <link>https://medium.com/@jeff.d.vincent/deploy-your-k8s-app-with-an-ingress-on-digital-ocean-af6b52f1eb8b?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6b52f1eb8b</guid>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 16:18:20 GMT</pubDate>
            <atom:updated>2023-10-31T18:38:21.024Z</atom:updated>
            <content:encoded><![CDATA[<p>So you built a cool, probably microservices-based, app — or if you haven’t yet you can use <a href="https://github.com/jeff-vincent/go-gin-redis-mongodb">this one</a> to get started — and you’re ready to deploy it in Kubernetes to the interwebs.</p><p>This post will walk you through the process of deploying a Kubernetes app in Digital Ocean with a proper domain name served over HTTPS via a Nginx ingress. So, let’s get started.</p><h3>Buy a domain name</h3><p>First things first, you’ll need to purchase a domain name from a service like <a href="https://www.godaddy.com/">GoDaddy</a> — I recently went with <a href="https://www.namecheap.com/">Namecheap</a>, because, well, the name says it all. Simply select an available domain name, purchase it, and verify your contact information to validate the domain.</p><h3>Spin up a cluster</h3><p>Next, you’ll need to spin up a Kubernetes cluster in Digital Ocean. You can do this by logging into the DO management portal, selecting Kubernetes from the “Create” dropdown, and following the outlined steps.</p><p>Then, you’ll need to connect to your cluster, so you can run commands with the Kubernetes CLI kubectl. You can install the Digital Ocean CLI on mac with homebrew as follows:</p><pre>brew install doctl</pre><p>And then, once you’ve created your cluster you’ll need to run the following to add the cluster to your .kube/config (which is what will allow you to run kubectl commands against the cluster):</p><pre>doctl kubernetes cluster kubeconfig save &lt;your-generated-auth-token&gt;</pre><p>And you can then confirm access by running:</p><pre>kubectl get all</pre><h3>Deploy Cert-manager</h3><p>Now that you have a cluster up and running, the next step is to deploy Cert-manager, a Kubernetes add-on that handles a lot of the complexity of TLS/SSL, which is what will allow you to serve your application with HTTPS.</p><p>You can create a namespace for and install Cert-manager by running the following:</p><pre>kubectl create ns cert-manager<br>kubectl apply -f https://github.com/jetstack/cert-manager/releases/download/v1.7.1/cert-manager.yaml</pre><p>And then, you’ll need to deploy a ClusterIssuer custom resource definition (CRD) that is specific to Cert-manager, which will handle the creation of your SSL/TLS certificate, and store the required data in an autogenerated K8s secret that Cert-manager will be able to consume.</p><pre># prod_issuer.yaml<br><br>apiVersion: cert-manager.io/v1<br>kind: ClusterIssuer<br>metadata:<br>  name: letsencrypt-prod<br>  namespace: cert-manager<br>spec:<br>  acme:<br>    # The ACME server URL<br>    server: https://acme-v02.api.letsencrypt.org/directory<br>    # Email address used for ACME registration<br>    email: &lt;your-email&gt;<br>    # Name of a secret used to store the ACME account private key<br>    privateKeySecretRef:<br>      name: letsencrypt-prod<br>    # Enable the HTTP-01 challenge provider<br>    solvers:<br>    - http01:<br>        ingress:<br>          class: nginx</pre><h3>Deploy an Nginx ingress controller</h3><p>Next, you’ll need to deploy an ingress controller (and later we’ll deploy an ingress object as well). If you aren’t familiar with Kubernetes ingresses, they are basically a way for you to allow HTTP traffic from outside the cluster to hit APIs exposed within your cluster with specific path rules.</p><p>For this, we’ll be using Helm — a package manager for Kubernetes. So, if you don’t yet have Helm installed, you need to install it. On mac it’s as simple as running brew install helm.</p><p>Then, you’ll need to run the following to create a K8s namespace, download the Nginx Helm repo to your local machine, and to then deploy it to your new cluster in that namespace.</p><pre>kubectl create namespace ingress-nginx<br><br>helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx<br>helm repo update<br>helm install nginx-ingress ingress-nginx/ingress-nginx --namespace ingress-nginx</pre><h3>Get the public IP from your ingress controller</h3><p>Next, you’ll need to get the EXTERNAL-IP address of your Nginx ingress controller’s Service resource by running the following:</p><pre>kubectl get service -n ingress-nginx</pre><h3>Add the External-IP to your domain registry</h3><p>Next, you’ll need to go back to the service where you bought your domain name, and find the DNS managment view. In Namecheap, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78ROZnqI-6rVsn16RRXpOw.png" /></figure><p><strong>There, you’ll need to add a new record as follows:</strong></p><ul><li><strong>Type:</strong> A (or A Record)</li><li><strong>Host:</strong> any subdomain you want to add to your domain name. For example, if you wanted to host a blog alongside your app, you could serve it at https://blog.&lt;your-domain&gt; by including blog as the host in this new record you’re creating.</li><li><strong>Target:</strong> and finally, you’ll just need to paste the external IP address you got above into the target field.</li></ul><h3>Define your ingress and deploy your app</h3><p>Finally, you just need to define your ingress object — which is distinct from the controller we deployed above — as follows:</p><pre>---<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: pyprodigy-ingress<br>  annotations:<br>    cert-manager.io/cluster-issuer: &quot;letsencrypt-prod&quot;<br>spec:<br>  ingressClassName: nginx<br>  tls:<br>  - hosts:<br>    - pyprodigy.dev<br>    secretName: pyprodigy-tls<br>  rules:<br>   - http:<br>      paths:<br>        - path: /<br>          pathType: Prefix<br>          backend:<br>            service:<br>              name: frontend<br>              port:<br>                number: 80<br>        - path: /api<br>          pathType: Prefix<br>          backend:<br>            service:<br>              name: users<br>              port:<br>                number: 8000</pre><p>And, of course, you’ll need to update the above example to align with your application structure. So, you’ll need to update the names of the services, the ports on which they are exposed and so on.</p><p><strong><em>Note: you’ll need to include an ingress rule similar to those shown above for any API that you want to be accessible from your frontend.</em></strong></p><h3>Test it out!</h3><p>And voila! You should have a working app deployed in K8s and accessible on the public interwebs! Just head to your newly purchased domain name in your browser and enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6b52f1eb8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spin the Globe with Google Maps API + OpenWeatherMap API]]></title>
            <link>https://medium.com/@jeff.d.vincent/spin-the-globe-with-google-maps-api-openweathermap-api-130fc86bfe4c?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/130fc86bfe4c</guid>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 22:45:22 GMT</pubDate>
            <atom:updated>2023-07-12T22:45:22.495Z</atom:updated>
            <content:encoded><![CDATA[<h4>Generate a random pair of coordinates, then feed them to the Google Maps API &amp; OpenWeatherMap API asynchronously</h4><p>We’ll stick with vanilla JS, CSS, and HTML5 in order to isolate the concepts we’ll be focusing on. And in the interest of time, this tutorial assumes a general understanding of REST APIs — what they are, actors involved — that sort of thing. If you’d like to brush up, give <a href="http://blah.com/">this</a> a look.</p><p>With that out of the way, let’s alllmost get started. First, you’ll need a Google Maps API key. You can get one <a href="https://developers.google.com/maps/documentation/javascript/get-api-key">here</a>. They’re free for this sort of thing.</p><p>Now, let’s get started.</p><p>First, let’s create and enter a project directory. In your console, run:</p><pre>mkdir spin-the-globe &amp;&amp; cd spin-the-globe</pre><p>Next, we’ll create a JavaScript file called main.js. In your console, run:</p><pre>touch main.js</pre><p>Now, let’s make a map! We’ll need to instantiate a new Google Maps Map object. To do so, we’ll first have to create a variable to house this object. I think map makes good sense, but you can call it anything you like. This is just providing us a way to keep track of the object, so to speak.</p><pre>const map = new google.maps.Map(document.getElementById(&#39;map&#39;), <br>{center: {lat: 42.43, lng: -123.05}, zoom: 8});</pre><p>Notice that the constructor takes two arguments: the DOM element where the map will be rendered, and a dict containing the options for the map. Minimum required options are lat and lng values and a zoom value between 1 and ~23. Zoom coverage varies. Also notice that map is a constant variable. To change the map, we’ll have to create a new one.</p><p>Now, let’s create a HTML file called index.html so we’ll have somewhere to put our map. In your console, run:</p><pre>touch index.html</pre><p>In order to access the Google Maps API, we need to ask for it. We do that by adding a script to the head of our HTML. Then, in the &lt;body&gt; create a &lt;div&gt; with the id of map, like so:</p><pre>&lt;head&gt;<br>  &lt;script src=&quot;https://maps.googleapis.com/maps/api/js?key={YOUR_API_KEY}&quot;&gt;<br>&lt;/script&gt;</pre><pre>&lt;body&gt;<br>  &lt;div id=&quot;map&quot;&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;</pre><p>Now, if you were to, say run:</p><pre>python3 -m http.server</pre><p>And then navigate to localhost:8000. Shoot! No map. This is because the map fills the container it is placed in, but only just so. So, we need to give our div some dimensions. Let’s create our third file, style.css to take care of this. In your console, run:</p><pre>touch style.css</pre><p>Then we can select the id #map that we applied to our div in index.html to tell the CSS which element to style, like so:</p><pre>#map {<br>  height: 300px;<br>  width: 650px;<br>  border-radius: 8px;<br>}</pre><p>Now, when you run python3 -m http.server, you should see your map.</p><p>c</p><p>Next, (for the “handling JSON responses” section) you’ll need an OpenWeatherMap API key. They’re free, and you can get one <a href="https://home.openweathermap.org/users/sign_up">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abbb82cd79c523ece2ab53d0c6e3c57b/href">https://medium.com/media/abbb82cd79c523ece2ab53d0c6e3c57b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=130fc86bfe4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sphinx Docs Made Simple]]></title>
            <link>https://medium.com/@jeff.d.vincent/sphinx-docs-made-simple-f541a4e4281c?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/f541a4e4281c</guid>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Sat, 07 Mar 2020 19:18:07 GMT</pubDate>
            <atom:updated>2020-03-08T07:18:31.255Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*k55zm6GMp9tXzlNKM0es8A.png" /></figure><p>I broke into the dev world as a docs person. So, when the company I’m currently doing development work for asked me to generate some docs posthaste, I went right back to <a href="https://samnicholls.net/2016/06/15/how-to-sphinx-readthedocs/">this awesome post</a> by Sam Nicholls that made the process seem pretty straight forward — even then.</p><p>As awesome as the above post is, I figure it might be nice to have an even simpler breakdown of the steps from zero to auto-generated doc goodness. So, here goes.</p><p>Although Sphinx supports a number of <a href="https://pygments.org/languages/">different languages</a>, odds are you are working with Python if you’re here, so let’s start there.</p><ol><li>First things first, install Sphinx: pip install sphinx. <em>(I use</em> <a href="https://pypi.org/project/pipenv/"><em>Pipenv</em></a>, <em>but you don’t have to)</em>.</li></ol><p>2. Then create a docs directory in your repo.</p><p>3. Next, from within that directory, run sphinx-quickstart.</p><p>4. After that, run sphinx-apidoc -o source/ ../&lt;repo root dir&gt; in order to generate the “stubs” that Sphinx will use to actually generate the docs. <em>NOTE: you may need to adjust the </em><em>../&lt;repo root dir&gt; portion according to the actual depth of your file tree.</em></p><p>5. Okay, home stretch. Now in a text editor of your choice, open the auto-generated conf.py file that should now be in your docs directory. Very near to the top of the file, you should find the following line:</p><p>sys.path.insert(0, os.path.abspath(&#39;.&#39;))</p><p><strong>Simply uncomment that line and save.</strong></p><p>6. Finally, still from within the docs directory, run: sphinx-build . _build.</p><p><strong>And Shazzam! You should now have some neat, interactive docs</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f541a4e4281c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrape a Password-Protected Website with Python (Scrapy)]]></title>
            <link>https://medium.com/@jeff.d.vincent/scrape-a-password-protected-website-with-python-scrapy-5056632ab31c?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/5056632ab31c</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Wed, 17 Jul 2019 06:16:12 GMT</pubDate>
            <atom:updated>2019-07-17T23:40:59.385Z</atom:updated>
            <content:encoded><![CDATA[<p>First things first, if you have to log in to a site to gain access to the content you wish to scrape, it warrants asking yourself if it’s a good idea in the first place. That said, legal and ethical use-case in hand, let’s get started.</p><p>For our purposes, we will be grabbing an entire page’s html and writing it to a local file, with which we can then do whatever we like.</p><h4><strong>Prerequisites:</strong></h4><p>You’ll need to install Scrapy, Python’s beloved web scraping module.</p><p>$ pip3 install scrapy will do the trick. Installing within a virtualenv is recommended but certainly not required.</p><h4>Process:</h4><p>First, we’ll create a new Scrapy project, by running:</p><pre>scrapy startproject &lt;project-name&gt;</pre><p>where &lt;project-name&gt; is the name of your project ;).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*4S9KL-htLXwYRjDXNIBfaA.png" /></figure><p>Then, within the spiders directory, create the module you’ll use to define the behavior of your spider. I’ve called mine scraper.py.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*q_4rGo4gjQNapNw3_2B2lg.png" /></figure><p>Withinscraper.py, we’ll have to first import Scrapy. Then, we’ll extend Scrapy’s Spider class with a class of our own. I’ve called mine PracticeSpider.</p><p>Note: name = &#39;practice&#39; on line (4) will allow us to later call the class from the terminal. We can denote which spider we’d like to run at a given time by running scrapy crawl practice.</p><p>Then, we’ll write three class methods. The first, start_requests has a list of urls, which are iterated over and called, one by one.</p><p>Next, parse is called, and although it is defined explicitly here, even if it weren’t it would still run, as parse is the default callback method. Within parse, we’ll handle the response from the login page we’re trying to get past.</p><p>We’ll pass it to Scrapy’s FormRequest.from_response() method along with login credentials (keep an eye peeled for type=&#39;hidden&#39; inputs with a token that may also need to be included).</p><p>From there, we could continue to any other page that is protected by the password we have by calling scrapy.Request(url=&lt;the-protected-url&gt;).</p><p>For the sake of brevity here, we are simply defining a callback self.write(response), which works because we are accessing the method on the instance of the class, rather than on the class itself.</p><p>Finally, we write the html that was returned after our login attempt to verify success or failure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5056632ab31c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Train Your Drag — err… Image Recognition App]]></title>
            <link>https://medium.com/major-league-hacking/how-to-train-your-drag-err-image-recognition-app-a299896fa583?source=rss-5ec8ee696037------2</link>
            <guid isPermaLink="false">https://medium.com/p/a299896fa583</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[clarifai]]></category>
            <dc:creator><![CDATA[Jeff Vincent]]></dc:creator>
            <pubDate>Thu, 20 Dec 2018 15:47:23 GMT</pubDate>
            <atom:updated>2019-01-18T05:53:46.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Train Your Clarifai Image Recognition App</h3><h4>Follow along as we explore Clarafai’s (Beta) Feedback feature.</h4><p>Clarafai, a leader in computer vision technology, is making it easier for developers to integrate visual recognition features into their projects. To get a sense of what’s possible with this powerful tool, check out these <a href="https://devpost.com/software/built-with/clarifai">example projects</a>.</p><p>Today, we’ll be looking at their new Feedback feature. It’s still in beta, but Clarafai makes no bones about promoting its use:</p><blockquote>“The feedback endpoint does not count towards your usage limits. Please use it as much as you can.”</blockquote><p>Why? Well, to train your models, of course! In fact, Clarafai goes on to say that they “highly encourage integrating feedback into your application as this dramatically improves accuracy of models over time.” Sounds good.</p><p>But what’s really happening when you provide feedback, and what kinds of feedback can you provide, and how do you provide it? All this and more will be answered shortly. Let’s get started.</p><p>Feel free to clone the <a href="https://github.com/jeff-vincent/clarifai-example">complete repo</a>, and follow along that way as well.</p><h3>Set up Your Development Environment</h3><p>We’ll be using Node.js and Express to create a simple web app that we can use to explore Clarafai’s Prediction Feedback feature. First, ensure you have Node installed, or <a href="https://nodejs.org/en/download/">download it</a>. Next, create a project directory, cd into the directory, and run npm init to initialize a new project, like so:</p><pre>mkdir clarifai-example &amp;&amp; cd clarifai-example &amp;&amp; npm init</pre><p>Next, we’ll install our dependencies:</p><pre>npm install clarifai express multer pug body-parser</pre><ul><li><a href="https://www.npmjs.com/package/clarifai"><strong>clarifai</strong></a><strong><em> </em>: </strong>Clarifai’s JavaScript client library</li><li><a href="https://expressjs.com/"><strong>express</strong></a><strong><em> </em>:<em> </em></strong>a popular web framework for Node.js</li><li><a href="https://www.npmjs.com/package/multer"><strong>multer</strong></a><strong> : </strong>handles file uploads for Express web servers</li><li><a href="https://pugjs.org/api/getting-started.html"><strong>pug</strong></a><strong><em> </em>:<em> </em></strong>a template engine for Node.js</li><li><a href="https://www.npmjs.com/package/body-parser"><strong>body-parser</strong></a><strong> : </strong>Node.js middleware for POST requests</li></ul><h3>Begin Development</h3><h4>First, we’ll build our Node app.</h4><p>To start, we’ll create a directory called public. We’ll tell Express that this is the stuff that gets sent to the client when they request it.</p><pre>mkdir public &amp;&amp; cd public</pre><p>Next, we need to create a HTML document called index.html. We can do this from the console by running:</p><pre>touch index.html</pre><p>Then we’ll create the structure for our UI with some HTML. You can paste the following directly into index.html in your editor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/228d3bf7d448f4310365824d66dde28a/href">https://medium.com/media/228d3bf7d448f4310365824d66dde28a/href</a></iframe><p>Let’s style it with a little CSS. Create the file:</p><pre>touch style.css</pre><p>The following can be pasted directly into style.css in your editor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e491867756d6a9added4353e11b7bd3/href">https://medium.com/media/8e491867756d6a9added4353e11b7bd3/href</a></iframe><p>Notice that we’ve defined a couple of classes — container and label-button.</p><p>Now we need something to serve this digital masterpiece! Let’s create a JavaScript file called index.js. We’ll want this in our root directory, though. So, from your console:</p><pre>cd .. &amp;&amp; touch index.js</pre><p>Now, we’ll import Express and create our server. Then we’ll set it to listen for a GET request on localhost:3000, and tell it to serve index.html like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/587a32920c6c7bdc1d49a6f13ef2f39f/href">https://medium.com/media/587a32920c6c7bdc1d49a6f13ef2f39f/href</a></iframe><p><strong>Just to make sure we’re all set, your file structure should look like this:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*lMw6F00FMCdaoAe4fyOs3A.png" /></figure><p>To serve our fledgling app, run:</p><pre>node index.js</pre><p>Then we should be able to navigate to localhost:3000 in our web browser and see our styled HTML. It won’t do anything yet, but it’s alive.</p><h3>Create App on Clarafai</h3><p><strong><em>Step one in API world — let’s go </em></strong><a href="https://clarifai.com/developer/account/signup"><strong><em>sign up</em></strong></a><strong><em>.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*_viMsolG2qcQ_DQxpASuOA.png" /></figure><p>It’s pretty painless, as these things go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ML9QSM_d218LMovjtw-v8g.png" /></figure><p>Immediately after login, your primary option will be to create an app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZS4hXvYFPaA-llq7p6R_6w.png" /></figure><p>Then, you’ll select options and click <strong><em>CREATE APP. </em></strong>I’ve called mine <em>Tree Sorter. </em><strong>Feel free to call yours anything you like, of course, but do note that name changes will need to be made in your code as well.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*g8pRFJ7PoaXPDeO9v75w1Q.jpeg" /></figure><p>Then, you’ll pop back out to this view populated with your new app.</p><p>Click the app name to open a manager panel.</p><p>We want to open the <strong><em>EXPLORER </em></strong>feature. For future reference, there’s a shortcut as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*xppYO1FLFYFwIZ7JIVWq7g.jpeg" /></figure><p>Then, we’ll want to create a model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*O64NPgTgoM3uBSvh00Pp8g.png" /></figure><p>I’ll call mine “Trees.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*h9wcg9VpNvfyJNjgG1ffug.png" /></figure><p>Next, we can create our concepts that we will classify our trees by.</p><p>I’ll call mine:</p><ul><li><strong>evergreen</strong></li><li><strong>deciduous</strong></li></ul><p>Now, we just need to upload our images and train our new model by clicking the upload image icon and then clicking <strong><em>TRAIN MODEL.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sM4DNra9tjXzY5dJsPiD_w.jpeg" /></figure><p>Note that you’ll need to add the appropriate concept to each photo. Notice that I gave each of my photos either a “deciduous” or an “evergreen” tag. You will be prompted to do so after each image uploads.</p><p>Now let’s create a view to display Clarifai’s response. We’ll use <a href="https://pugjs.org/api/getting-started.html">Pug</a>.</p><pre>cd public &amp;&amp; touch results.pug</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d8a886474153e19f3cb4fc39fa941dc/href">https://medium.com/media/9d8a886474153e19f3cb4fc39fa941dc/href</a></iframe><p>The above will be compiled to standard HTML when it is run. Notice that we added a script for feedback.js. That’s where we’ll define the logic for this view. Also notice that we have set the id of the &lt;img&gt; to img, so we’ll be able to retrieve its contents easily later. Finally, notice the third button in our UI — it isn’t a button at all. It’s a link that has the label-button class applied, so it looks like its neighbors, but it acts like a link back to our index.html view.</p><p>Let’s add the following to style.css so our resulting image looks a little better.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e501eb8d8903a44a6181b5d1f23822f0/href">https://medium.com/media/e501eb8d8903a44a6181b5d1f23822f0/href</a></iframe><p>Let’s expand index.js so it can do the things we’ve been preparing our UI to display.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68c70e1a0a137c82a62c9b83d843ca6c/href">https://medium.com/media/68c70e1a0a137c82a62c9b83d843ca6c/href</a></iframe><p>Note that you will need to retrieve your API KEY from the Clarifai website.</p><p>Note we are using Multer to upload the image, and we then convert it to a base 64 string and set it to base64string.</p><p>We then pass that to our Clarifai prediction model, Trees. <strong>(Psst… if you didn’t call the model you created on the Clarifai website <em>Trees</em>, change it here.)</strong></p><p>Let’s see if it works. From the root directory:</p><pre>node index.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*7O_FwdeY_mNGG9O8MAmnhw.png" /></figure><h3>Begin Feedback Portion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*pQ8skPU23XEYDd93XqOi0w.png" /></figure><p>Let’s start by creating a JavaScript file called feedback.js. Note that this file, unlike index.js, will go in the public directory.</p><p>For the sake of time, we’ll only focus on Prediction Feedback, although Clarifai offers a parallel service in Search Feedback as well. Either way, feedback — when you strip away the mystique — is pretty simple, really. It is just the reinforcing or correcting of an existing image/concept association. It is also possible to add a novel concept to an image, but that’s beyond the scope of this tutorial.</p><p>Basically, you are adding tags, changing tags, or telling it, “yep, you’re right.” Clarifai will tell us what it thinks is in the image by assigning it a score for each concept it is told to consider. <strong><em>The scores range from 0 to 1, with 1 being the highest possible degree of certainty that it is a good match.</em></strong></p><p>Our feedback will be driven by our hard-earned knowledge of Christmas trees and their cousins and stuff. If we think it is an Evergreen, by golly we’ll click <strong><em>Evergreen. </em></strong>And vice-versa for their leafy brethren.<strong><em> </em></strong>After we’ve made our noble contribution to the lofty vaults of tree knowledge, we can click <strong><em>Next Image</em></strong>, which will cycle us back to our original view.</p><p>Let’s go ahead and write the logic to support these buttons.</p><pre>cd public &amp;&amp; touch feedback.js</pre><p>There are far more elegant ways to do this, but for the sake of illustration, let’s write a separate function to handle each of our feedback options.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ebf2a821f32b983e8dfbb58cfb70728/href">https://medium.com/media/4ebf2a821f32b983e8dfbb58cfb70728/href</a></iframe><p>Notice that evergreen() and deciduous() are acting as intermediaries in the request process. They are building the request object, feedback, and then passing it to sendPost() which fires off the POST request from the client for our index.js file to handle on the server side.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5caf84531ab655a9542ac8afc30fb04/href">https://medium.com/media/f5caf84531ab655a9542ac8afc30fb04/href</a></iframe><p>Our three required values are image, which we’re pulling from the DOM, a boolean value of true to indicate that it is a good match, and finally the id of the concept for which it is a good match — i.e. evergreen or deciduous.</p><p>Note that we are using the built-in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a> to make our POST request.</p><p>On the server side, we’ll need to import body parser for Express to handle our POST request.</p><p>And then tell Express to use it.</p><p><strong>Note: add API KEY here.</strong></p><p>Finally, let’s actually handle that POST request. We can parse our params by accessing request.body[&#39;key&#39;] and setting them equal to variables that we can pass to Clarifai.</p><p><strong>Note, there is a second </strong><strong>id that is associated with the model itself. You’ll need to collect this from the Clarifai website.</strong></p><p>Note that if we have success, ‘Feedback successfully submitted’ will be logged to the console.</p><p>And like that, we’ve created a model, and now we can actively shape its understanding of what it sees by providing feedback. It is worth noting that this won’t change the behavior of your model immediately, but rather will gradually improve the model’s accuracy over time.</p><p>Next steps: check out Clarifai’s <a href="https://clarifai.com/developer/guide/">documentation</a> to firm up all this new knowledge.</p><p>Thanks so much for following along! I am sure that what you create will be amazing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a299896fa583" width="1" height="1" alt=""><hr><p><a href="https://medium.com/major-league-hacking/how-to-train-your-drag-err-image-recognition-app-a299896fa583">How to Train Your Drag — err… Image Recognition App</a> was originally published in <a href="https://medium.com/major-league-hacking">Major League Hacking</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>