<?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 Richard Durso on Medium]]></title>
        <description><![CDATA[Stories by Richard Durso on Medium]]></description>
        <link>https://medium.com/@reefland?source=rss-7e72a89eabe9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w1wk3ksFIUtZI7BRyc7WUA.jpeg</url>
            <title>Stories by Richard Durso on Medium</title>
            <link>https://medium.com/@reefland?source=rss-7e72a89eabe9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:23:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reefland/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[Use K3S Upgrade Controller to Patch Underlying OS]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@reefland/use-k3s-upgrade-controller-to-patch-underlying-os-d066a952e5f9?source=rss-7e72a89eabe9------2"><img src="https://cdn-images-1.medium.com/max/600/1*sZDdRgTP1vOETYZ-HALJlQ.png" width="600"></a></p><p class="medium-feed-snippet">The K3S Upgrade Controller is a Kubernetes-native approach to cluster upgrades.</p><p class="medium-feed-link"><a href="https://medium.com/@reefland/use-k3s-upgrade-controller-to-patch-underlying-os-d066a952e5f9?source=rss-7e72a89eabe9------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@reefland/use-k3s-upgrade-controller-to-patch-underlying-os-d066a952e5f9?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d066a952e5f9</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k3s-upgrade-controller]]></category>
            <category><![CDATA[k3]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 21:51:45 GMT</pubDate>
            <atom:updated>2024-07-14T21:51:45.242Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Reusing Enterprise-Grade PCIe Cards in Home Lab with Active Cooling]]></title>
            <link>https://medium.com/@reefland/reusing-enterprise-grade-pcie-cards-in-home-lab-with-active-cooling-2b42013d3a52?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b42013d3a52</guid>
            <category><![CDATA[pcie]]></category>
            <category><![CDATA[noctua]]></category>
            <category><![CDATA[reuse]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 14:02:47 GMT</pubDate>
            <atom:updated>2023-11-28T14:02:47.364Z</atom:updated>
            <content:encoded><![CDATA[<p>Reusing enterprise-grade <a href="https://en.wikipedia.org/wiki/PCI_Express">PCIe cards</a> in your home lab can be a cost-effective way to enhance your network and storage capabilities. This promotes reusability and reduces <a href="https://en.wikipedia.org/wiki/Electronic_waste">e-waste</a> which are good to do. Just by adding small fans we can address overheating issues; a simple practical solution.</p><blockquote>While this article is not about getting started with a home lab, I feel obligated to have a little blurb on why you should be interested having one. <strong>Home Lab</strong> is simply one or more physical (or virtual) computers traditionally located within your home. This provides an environment isolated from your employer where you can experiment, research and learn technologies. Some tech enthusiast want an environment without the annoyance of a manager looking over your shoulder, where you can safely fail and refine your techniques. A home lab allows you to gain experience in technology which might not align with your job responsibilities which can be extremely useful in career advancement. (There are plenty of non IT activities which might need a home lab such as content creator / video editing work with massive raw video files.)</blockquote><p>Two low hanging fruits for home lab adoption are high(er) speed networking and expanded storage options.</p><p>The enterprise has rapidly progressed to faster and faster networking speeds from 40GbE, 100GbE, 400GbE, etc. making the previous technologies extremely affordable such as 10GbE network cards. This is fast enough to start opening the door for you to experiment with higher capacity storage solutions such as NAS (<a href="https://en.wikipedia.org/wiki/Network-attached_storage">Network Attached Storage</a>) and software defined storage such as <a href="https://en.wikipedia.org/wiki/Ceph_(software)">Ceph</a><a href="https://en.wikipedia.org/wiki/Ceph_(software)].">.</a></p><p>While you can purchase old enterprise servers from places like eBay for use in your home lab (which is perfectly acceptable if such hardware is relevant to your learning path) but most home labers do not do this as enterprise class servers are not <a href="https://www.reddit.com/r/homelab/comments/3t6vdx/question_how_hot_and_loud_do_your_racks_servers/">power efficient and utilize high-speed fans which can be extremely loud</a> resulting in very low Significant Other Acceptance Factor.</p><blockquote>NOTE: There is also a methodology of home lab around using small power efficient computers like <a href="https://www.raspberrypi.com/products/">Raspberry Pi</a> and small form factor mini-PC such as the <a href="https://www.servethehome.com/introducing-project-tinyminimicro-home-lab-revolution/">TinyMiniMicro Project</a>. This article does not apply to these as they tend to have very limited upgradability.</blockquote><p>It is often an easier path of just acquiring 10GbE networking cards and installing them directly into an old desktop which has been promoted to the role of your home lab server. This just needs an available PCIe slot. For a storage server, if your motherboard does not have enough SATA ports and you have another available PCIe slot, you can add a SAS/SATA Controller or RAID Controller allowing you to add 8 or maybe up to 16 SATA drives. <em>[For storage, you’ll need enough drive bays for each SATA drive and confirm your power supply has available power connectors and can support the wattage for the number of drives you are looking at. Again beyond the scope of this article]</em></p><h3>Overheating</h3><p>Once you’ve gone down the <a href="https://en.wikipedia.org/wiki/Down_the_rabbit_hole">rabbit hole</a> of selecting an appropriate enterprise class card it is often overlooked how to cool the card. Remember the enterprise class server was crammed full of high speed fans to move vasts amount of air rapidly to cool the internal components. The enterprise class network and storage cards are typically passively cooled expecting to be installed in a system with high air flow rates.</p><p>Without the active cooling from higher airflow rates these cards can overheat and throttle (reduces performance) or just fail. Unfortunately many of these cards lack a temperature sensor to even determine if you have temperature issues.</p><h3>The Solution</h3><p><a href="https://noctua.at/en/nf-a4x10-pwm">Noctua NF-A4x10 PWM fan</a> is a small 40x40x10mm, 12 volt, 4-pin fan. I have purchased dozens of these small low profile fans for various Home Lab projects. The Noctua fans come with an extension cable, power connector splitter and a 4 pin to 3 pin converter. If you don’t have enough fan header connections on your motherboard or need to convert from 4 to 3 pin connector, everything you need should be in the box.</p><p>For demonstration purpose, I’ll show how to mount this fan on a 10+ year old <em>Solarflare dual SPF+ 10GbE network card</em>. As shown below its a network card with its passive <a href="https://en.wikipedia.org/wiki/Heat_sink">heat-sink</a> and the <em>Noctua NF-A4x10 fan</em> above it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ag-eXP9-VTXW9ugScik-Iw.jpeg" /><figcaption><em>Solarflare dual SPF+ 10GbE network card and Noctua NF-A4x10 fan</em></figcaption></figure><p>As you can see below, when the fan is placed on top of the passive heat sink the brass pins align perfectly to the mounting holes of the fan. This alignment is very common and allows this fan to be used on many different components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2u0yq1zcxClj7R74fnfTw.jpeg" /><figcaption>Noctua fan overlaid on Solarflare heat sink showing pin alignment with two fan holes</figcaption></figure><h4>Removing Heat Sink</h4><p>To remove the two brass pins, flip the network card over and simply squish the two tips together. I used <a href="https://en.wikipedia.org/wiki/Needle-nose_pliers">needle nose pliers</a> for this. The pins are likely spring loaded to apply tension. Once the two tips are together, with a slight downward push, it pops right out with the help of the springs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-oZytmx2E_2iX6-JWPlXCw.jpeg" /><figcaption>Reverse side of Solarflare card, closing pin with pliers</figcaption></figure><p>Don’t be surprised if the heat sink just falls off when the second pin is removed. This is a sign that the thermal paste has completely dried over the years. Even if it doesn’t come off, give it a gentle twisting back and forth to wiggle it off. Fresh thermal paste will allow efficient heat transfer to the heat sink. <em>When reusing equipment with an unknown history just apply some fresh thermal paste, it’s cheap and easy to do. I’ll show you below.</em></p><h4>Clean Up</h4><p>Once the heat sink is removed, with some isopropyl alcohol and a paper towel, or napkin or even cotton ball or cotton swab (q-tip) just gently rub the dried paste with isopropyl alcohol. Keep changing the paper towel around to use clean spot with each pass. You want to remove it, not just smear it around. Shouldn’t take more than a minute or so to get it all off. Then clean the underside of the heat sink as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2WXfPwqYLwQvSpTZx2t8A.jpeg" /><figcaption>Cleaning the Solarflare Network Card controller chip</figcaption></figure><p>If you haven’t done this before, I suggest using Nitrile disposable gloves. The paste can get all over your hands if not careful and then you will get pasty finger prints all over the card; <em>you don’t want that</em>. Most thermal compounds only conduct heat, not electricity. As long as you are using a non-conductive thermal compound it won’t harm anything. Do not use something like liquid metal thermal compound.</p><h4>Replacing Thermal Compound</h4><p>No need for expensive high-end thermal compound used for CPUs (if you have some, then use it). If you have to buy something, grab something cheaper. I happen to have Arctic MX-4 thermal compound, its cheap, should be under $10 (Amazon) for small 4 gram tube (syringe) which will be enough for dozens of cards. It comes with a reusable plastic spatula to thinly spread the paste.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tjnl18HWDoM0CceRL4hv6w.jpeg" /><figcaption>Typical syringe of thermal compound (Arctic MX-4 brand pictured) and applicator spatula</figcaption></figure><p>I use five drops of the paste, one near each corner and a dot in the middle (like the number 5 on a pair of dice). Then use the plastic spatula to even out a <strong><em>very</em></strong> thin layer. You don’t have to really worry about adding too much, but no reason to waste it either. A little goes a long way. If you happen to add too much just use the plastic spatula to lightly scrape off the excess and discard on a paper towel.</p><p>Do not apply any thermal compound on the heat sink itself, that should remain clean. Only apply it to the device the heat sink will attach too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_bY5yxdcLJUBVQw72Bz0w.jpeg" /><figcaption>Solarflare Network Card controller chip with thin layer of thermal compound applied</figcaption></figure><h4>Remounting Heat Sink with Fan</h4><p>The original brass pins cannot be reused as the new fan will need an additional 10mm of length. I use M3 nylon bolts 25mm long and M3 nylon hex nuts to replace the brass pin and springs. The 25mm length is just barely long enough. At best you can hand tighten to get 3 to 5ish threads on the bolt. If you can find something just slightly longer such as 28mm length it would be perfect. Don’t go any shorter than 25mm. You can easily find an assortment of nylon M3 bolt lengths on Amazon (100 or so for under $10).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08C7LoXPwhclmVh0WNxrpQ.jpeg" /><figcaption>M3 25mm nylon bolts and M3 hex nuts</figcaption></figure><p>Place the fan on top of the heat sink with the fan grill down against the heat sink. <em>This should have the fan drawing air away from the heat sink and prevents the fan itself from hitting the heat sink.</em> Place the nylon bolts through the holes. You have the flexibility to rotate the fan as needed to have the power connection oriented in a way that works best for your setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekmPbQOxs0GwqyxG3kZD6A.jpeg" /><figcaption>M3 25mm nylon bolts exposed through heat sink, not much left for thickness of controller ship and card</figcaption></figure><p>Then in one motion, mount the fan &amp; heat sink to the device being careful to align the bolt to the holes in the card. Try to do this in <strong><em>one motion</em></strong> as you do not want the heat sink sliding around on the slick thermal compound paste. If you really mess up, just clean everything again and reapply the thermal compound. This is where you’ll wish you had 3 hands as you need to keep the fan, heat sink, PCIe card and screws all aligned without the screws falling out and with your other hand try to thread the hex nut onto the bolt. There was no way I could do all that and take a picture, it required a 4th hand.</p><p>Remember, you just need to hand tighten the hex nut snug. Applying any more pressure would likely just strip the thread on the soft nylon bolts. If that happens replace the nylon bolt with another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElQkAnunurqxSJSCGmWZdg.jpeg" /><figcaption>Nylon M3 hex nuts attached to nylon bolts. BE CAREFUL to not damage the surrounding components</figcaption></figure><h4>Install Modified PCIe Card</h4><p>Lastly install the PCIe card and plug in the fan to an available fan header on the motherboard. Try not to use a water pump header, it should be fan header. A 4 pin header allows you to set a variable fan speed. As the network card lacks a thermal sensor, I have no way of fine tuning the fan speed. I leave it on max which is about 5000 RPM. Noctua fans are <em>quiet</em>. The fan is rated at 19 dB(a) at max speed which is the <a href="https://www.audicus.com/noise-levels-of-everyday-sounds/">equivalent of someone whispering in a quiet room 5 feet away</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxATqcYfM1yVVsYfk_15-A.jpeg" /><figcaption><em>Solarflare dual SPF+ 10GbE network card with Noctua NF-A4x10 fan installed (top) with power connector plugged into fan header (bottom)</em></figcaption></figure><p>Supply List:</p><ul><li>Noctua NF-A4x10 PWM fan</li><li>Two M3x25mm nylon bolts and (2) M3 nylon Hex nuts (some devices may need 4 pins replaced)</li><li>Small tube of thermal compound paste</li><li>Needle nose pliers for pin removal</li><li>Isopropyl alcohol and a paper towel for cleaning</li></ul><blockquote>If the device you want to use, does not have a way to mount the Noctua NF-A4x10 fan easily, then you can typically hold the fan in-place using thin plastic ties going through the fan holes and around the PCIe card. It’s a bit ugly, but does the job.</blockquote><p>Here are some other uses I’ve had for the Noctua NF-A4x10 fans with:</p><p>Mounted to a PCIe SAS/SATA Disk Controller, I used same technique documented above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dk8kKzchbsXET2hRQXfZ-A.jpeg" /><figcaption>Noctua NF-A4x10 fan mounted to SAS/SATA Disk Controller with nylon bolts and nuts</figcaption></figure><p>Two fans used externally connected via 4 pin to USB conversion cable used to pull hot air out of my MikoTik 10Gib Cloud Router Switch. <em>Pay no attention to the dust buildup. Nobody is supposed to peek inside the network rack.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QPZ6qm7T2tTpSobjR5oPg.jpeg" /><figcaption>Dual Noctua NF-A4x10 fans mounted externally to network router. One held in place by a single screw, the other used 3M Automotive Molding tape</figcaption></figure><p>Two fans used per PC, externally connected via 4 pin to USB conversion cable. Used to push cooler air into small form factor PC. This small PC has M.2 SATA and M.2 NVMe drives, and a 2.5GbE PCIe card (no internal fan header available), and 64GiB RAM. Unfortunately the passive cooling design was not enough. No internal fan headers and no room on the inside for fans. Two external fans blowing cooler air inwards helps keep all the components at acceptable temperature levels. (I have 6 node bare metal Kubernetes Cluster using hardware like this. You can view my Home Lab <a href="https://bit.ly/46Ysktl">Kubernetes real-time Grafana Dashboard</a> and <a href="https://bit.ly/423PISu">Uptime Kuma Monitoring Dashboard</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MA-Z_xZscGu9ARChhuSUw.jpeg" /><figcaption>3 bare metal Kubernetes cluster nodes using dual external Noctua NF-A4x10 fans mounted with 3M Automotive Molding tape</figcaption></figure><p>The fans pictured above are held in place using small bits of <a href="https://www.3m.com/3M/en_US/p/d/b40069527/">3M Automotive Molding tape</a> [a role is under $10 at Amazon].</p><p>In summary, with some easy modifications made to enterprise class PCIe devices to allow them to be used in non-enterprise server grade hardware, it allows you to expand your home lab to new technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b42013d3a52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Kubernetes Node Labeling via Node Feature Discovery]]></title>
            <link>https://medium.com/@reefland/dynamic-kubernetes-node-labeling-via-node-feature-discovery-2c3e9c1879d1?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c3e9c1879d1</guid>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 01:37:32 GMT</pubDate>
            <atom:updated>2023-05-12T13:55:15.193Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Node Labeling via Node Feature Discovery on Kubernetes</h3><h3>Introduction</h3><p>At its core, <a href="https://kubernetes-sigs.github.io/node-feature-discovery/v0.12/get-started/index.html">Node Feature Discovery</a> (NFD) is an application that automatically detects hardware features and system configuration of a node in a Kubernetes cluster. Think of it as a treasure hunter, scouring the nooks and crannies of your cluster to find the hidden gems of hardware and configuration features that can make a big difference in how your workloads are scheduled and run.</p><p>Node Feature Discovery can help the Kubernetes scheduler identify the nodes in your cluster that have specific features, such as GPUs or SSDs, and then schedule workloads to run on those nodes. This can help you make the most of your resources and ensure that your workloads are running as efficiently as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aZkCeQj5pKVvlHXb" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>My Use Case</h3><p>I have a self-hosted <a href="https://k3s.io/">K3s</a> Kubernetes cluster. One application I host is <a href="https://frigate.video/">Frigate NVR</a> which consumes live video feeds from all my security cameras. When Frigate detects motion within a video stream, it isolates that motion into a small clip. The object creating the motion can be identified by off-loading the image to a <a href="https://coral.ai/products/accelerator/">Google Coral TPU USB accelerator</a> such as “Person”, “Dog”, Cat” and this information can be used to make decisions.</p><p>I only want Frigate NVR to be scheduled on nodes that have a Coral TPU USB plugged in and I want to be able to move this USB device around as needed without having to update YAML files and making configuration changes to the cluster. NFD easily solves this for me.</p><h3>About Node Feature Discovery</h3><p>NFD detects hardware features available on each node in a Kubernetes cluster, and advertises those features using <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/">node labels</a>. Of course, you could manually create node labels and schedule pods using them, but why do that if you don’t have to?</p><p>NFD consists of three software components:</p><ol><li><strong>NFD-Master</strong> is a daemon responsible for communication with the Kubernetes API (receives labeling requests from the worker and modifies node objects accordingly).</li><li><strong>NFD-Worker</strong> is a daemon responsible for feature detection. One instance per node within the cluster. It will forward its detections to the <em>NFD-Master</em> to perform the actual node labeling.</li><li><strong>NFD-Topology-Updater</strong> is a daemon responsible for examining allocated resources on a worker node to account for resources available to be allocated to new pod.</li></ol><p>Feature Discovery is based on a wide range of domain-specific sources: CPU, Kernel, Memory, Network, PCI, Storage, System, USB, etc. Each feature source is responsible for detecting its respective features which are turned into node feature labels.</p><h3>Installation</h3><p>The installation can be straight forward:</p><pre>$ kubectl apply -k https://github.com/kubernetes-sigs/node-feature-discovery/deployment/overlays/default?ref=v0.12.2<br><br>  namespace/node-feature-discovery created<br>  serviceaccount/nfd-master created<br>  clusterrole.rbac.authorization.k8s.io/nfd-master created<br>  clusterrolebinding.rbac.authorization.k8s.io/nfd-master created<br>  configmap/nfd-worker-conf created<br>  service/nfd-master created<br>  deployment.apps/nfd-master created<br>  daemonset.apps/nfd-worker created</pre><p>Or installation via Helm:</p><pre>$ export NFD_NS=node-feature-discovery<br><br>$ helm repo add nfd https://kubernetes-sigs.github.io/node-feature-discovery/charts<br>$ helm repo update<br>$ helm install nfd/node-feature-discovery -f &lt;path/to/custom/values.yaml&gt; \<br>  --namespace $NFD_NS --create-namespace</pre><p>Where <strong><em>-f &lt;path/to/custom/values.yaml&gt;</em></strong> specifies a custom configuration to overwrite default values.</p><h4>Check Pods are Running</h4><p>Quick check to see pods are running:</p><pre>$ kubectl -n node-feature-discovery get all  <br><br>  pod/node-feature-discovery-master-6b8f9f4d78-ch9h2          1/1     Running   0              29h<br>  pod/node-feature-discovery-worker-48z7z                     1/1     Running   48 (29h ago)   39d<br>  pod/node-feature-discovery-worker-cx9qd                     1/1     Running   35 (29h ago)   39d</pre><h3>Check Node Labels Created</h3><p>By default the node feature labels are a bit ugly, they will look something like:</p><pre>$ kubectl get nodes -o json | jq .items[].metadata.labels<br><br>  {<br>    &quot;feature.node.kubernetes.io/pci-0106_1022.present&quot;: &quot;true&quot;,<br>    &quot;feature.node.kubernetes.io/pci-0108_144d.present&quot;: &quot;true&quot;,<br>    &quot;feature.node.kubernetes.io/pci-0300_1002.present&quot;: &quot;true&quot;,<br>    &quot;feature.node.kubernetes.io/usb-ef_0e8d_0608.present&quot;: &quot;true&quot;,<br>    &quot;feature.node.kubernetes.io/usb-ff_18d1_9302.present&quot;: &quot;true&quot;,<br>    ...<br>  }</pre><h3>Customized Node Labels</h3><p>One of the best things about NFD is that it’s highly customizable. You can configure it to detect custom features, allowing you to extend its functionality to support your own hardware or software features. This is particularly useful for organizations with unique hardware or software requirements.</p><p>We can limit which nodes devices that NFD should detect by specifying sources with the configuration parameter <strong><em>deviceClassWhitelist</em></strong>. This is used to specify a list of device classes that NFD should scan for on a node.</p><p>We can also create our own custom source, which can be used to map discovered <strong>Class</strong>, <strong>Vendor</strong> and <strong>Device codes</strong> to simpler human readable labels. All of this can be stored neatly within our <strong><em>values.yaml</em></strong> specified during installation.</p><p>As an example, below is the <strong><em>values.yaml</em></strong> file I used to limit NFD to just PCI and USB devices. For each PCI and USB source, a defined <strong><em>deviceClassWhitelist</em></strong> is specified to filter on. I also included comments on websites I used that help me determine what the codes meant. Then based on the <em>class</em>, <em>vendor</em> and <em>device codes</em> are define “custom” human readable label names:</p><pre>worker:<br>  config:<br>    core:<br>      sources: [&quot;custom&quot;, &quot;pci&quot;, &quot;usb&quot;]<br>    sources:<br>      pci:<br>        # https://pci-ids.ucw.cz/read/PD<br>        deviceClassWhitelist: [&quot;01&quot;, &quot;03&quot;, &quot;0b40&quot;, &quot;12&quot;]<br><br>      usb:<br>        # https://www.usb.org/defined-class-codes<br>        deviceClassWhitelist: [&quot;02&quot;, &quot;03&quot;, &quot;0e&quot;, &quot;ef&quot;, &quot;fe&quot;, &quot;ff&quot;]<br><br>      custom:<br>        - name: &quot;intel-gpu&quot; # Intel integrated GPU<br>          matchOn:<br>            - pciId:<br>                class: [&quot;0300&quot;]<br>                vendor: [&quot;8086&quot;]<br>        - name: &quot;amd-gpu-barcelo&quot; # AMD Barcelo Integrated GPU<br>          matchOn:<br>            - pciId:<br>                class: [&quot;0300&quot;]<br>                vendor: [&quot;1002&quot;]<br>                device: [&quot;15e7&quot;]<br>        - name: &quot;amd-gpu-raven-ridge&quot; # AMD Raven Ridge Integrated GPU<br>          matchOn:<br>            - pciId:<br>                class: [&quot;0300&quot;]<br>                vendor: [&quot;1002&quot;]<br>                device: [&quot;15dd&quot;]<br><br>        - name: &quot;google-coral-device&quot; # USB Coral TPU<br>          matchOn:<br>            - usbId:<br>                vendor: [&quot;18d1&quot;, &quot;1a6e&quot;]<br>        - name: &quot;bluetooth-radio&quot; # MediaTek Bluetooth Radio<br>          matchOn:<br>            - usbId:<br>                vendor: [&quot;0e8d&quot;]<br>                device: [&quot;0608&quot;]<br>        - name: &quot;hp-usb-keyboard&quot; # HP Slim Keyboard<br>          matchOn:<br>            - usbId:<br>                vendor: [&quot;03f0&quot;]<br>                device: [&quot;2f4a&quot;]</pre><p>Once this is applied, the node labels start to make more sense:</p><pre>$ kubectl get nodes -o json | jq .items[].metadata.labels<br><br>  {<br>    &quot;feature.node.kubernetes.io/custom-amd-gpu-barcelo&quot;: &quot;true&quot;,<br>    &quot;feature.node.kubernetes.io/custom-bluetooth-radio&quot;: &quot;true&quot;,<br>    &quot;feature.node.kubernetes.io/custom-hp-usb-keyboard&quot;: &quot;true&quot;,<br>    ...<br>    <br>    &quot;feature.node.kubernetes.io/custom-google-coral-device&quot;: &quot;true&quot;,<br>    ...<br>    <br>    &quot;feature.node.kubernetes.io/custom-intel-gpu&quot;: &quot;true&quot;,<br>    &quot;feature.node.kubernetes.io/custom-rdma.capable&quot;: &quot;true&quot;,<br>    ...<br>  }</pre><p>Now the Kubernetes Scheduler can easily determined which nodes have Intel vs AMD GPUs, which node has a Coral TPU USB device, Bluetooth radio, etc. We can even determine which node has the current focus of the <a href="https://en.wikipedia.org/wiki/KVM_switch">KVM Switch</a> by looking at which node has the attached keyboard.</p><h3>How to determine class, vendor and device codes</h3><p>For <strong>USB Devices</strong> we can start with Linux utility lsusb:</p><pre>$ lsusb<br><br>Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub<br>Bus 003 Device 002: ID 0e8d:0608 MediaTek Inc. Wireless_Device<br>Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub<br>Bus 002 Device 003: ID 18d1:9302 Google Inc. </pre><p>Looking at the line with “<strong>Google Inc.</strong>” the column <strong>18d1:9302</strong> contains the <strong><em>vendor</em></strong> and <strong><em>device code</em></strong>. The <strong>18d1</strong> is a vendor code for Google and <strong>9302</strong> is a device code. Being that Google does not make a lot of USB equipment our filter does not need to be that precise. Just filtering on the vendor code will be fine for our detection of the Google Coral TPU USB device:</p><pre>- name: &quot;google-coral-device&quot; # USB Coral TPU<br>  matchOn:<br>    - usbId:<br>        vendor: [&quot;18d1&quot;, &quot;1a6e&quot;]</pre><ul><li>NOTE: I was aware of an alternate vendor code for this device, I included it within the vendor match just in case I happen to get more of these modules.</li></ul><p>For <strong>PCI Devices</strong> we can use lspci Linux utility, and limit our search to VGA devices using grep:</p><pre>$ lspci -nn | grep VGA<br><br>04:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Barcelo [1002:15e7] (rev c2)</pre><p>Within the <strong>[0300]</strong>, the <strong>0300</strong> is the class for VGA compatible controller, and within <strong>[1002:15e7]</strong> the <strong>1002</strong> is vendor code for AMD and <strong>15e7</strong> is the device code. Being that AMD makes a lot of devices, we can be very specific with the device definition:</p><pre>- name: &quot;amd-gpu-barcelo&quot; # AMD Barcelo Integrated GPU<br>  matchOn:<br>    - pciId:<br>        class: [&quot;0300&quot;]<br>        vendor: [&quot;1002&quot;]<br>        device: [&quot;15e7&quot;]</pre><h3>Scheduling Pods Based on Dynamic Labels</h3><p>This is just scratching the surface of what Node Feature Discovery can do. This was sufficient for my needs to determine where Frigate NVR could be scheduled. Within Frigate NVR’s Helm <strong><em>values.yaml</em></strong> file, a <strong>nodeSelector</strong> can be defined using the dynamic labels created by NFD:</p><pre>nodeSelector:<br>  kubernetes.io/role: &quot;worker&quot;<br>  feature.node.kubernetes.io/custom-amd-gpu-barcelo: &quot;true&quot;<br>  feature.node.kubernetes.io/custom-google-coral-device: &quot;true&quot;</pre><h3>Conclusion</h3><p>In conclusion, Node Feature Discovery is a valuable tool for any Kubernetes user looking to optimize their workloads. With its ability to automatically detect hardware and software features, NFD can help you make the most of your resources and ensure that your workloads are running as efficiently as possible. So if you haven’t already, give NFD a try and see how it can help you navigate the waters of Kubernetes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c3e9c1879d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CRI Purge — Kubernetes Cleanup of Cached Images]]></title>
            <link>https://medium.com/@reefland/cri-purge-kubernetes-cleanup-of-cached-images-b7087af3bf1d?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7087af3bf1d</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[homelab]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 16:33:38 GMT</pubDate>
            <atom:updated>2023-06-10T19:41:25.794Z</atom:updated>
            <content:encoded><![CDATA[<h3>CRI Purge — Kubernetes Cleanup of Cached Images</h3><p><strong><em>CRI Purge</em></strong>, is a BASH script I wrote to help cleanup disk space of cached Kubernetes container images. The script interacts with crictl images command to generate a list of cached images. Unlike crictl images —prune option which will simply delete all cached images (requiring all active images to be downloaded again on next pod restart), the <strong><em>CRI Purge</em></strong> script tries to add a little intelligence to how it purges images.</p><figure><img alt="Example of disk space usage as presented by FileLight" src="https://cdn-images-1.medium.com/max/1024/1*2-43rxOBFXLMEoTq6AsD4A.png" /></figure><blockquote>crictl is the CLI for the <a href="https://kubernetes.io/docs/concepts/architecture/cri/">Container Runtime Interface (CRI)</a>, which defines the API used to talk to container engines.</blockquote><p>1) <strong><em>CRI Purge</em></strong> will process each image’s list of cached versions in a best effort to determine <a href="https://semver.org/">semantic version</a> from oldest to newest (v1.7.1, v1.8.0, v1.8.1, v1.8.2, v1.9.0) with the goal to determine and retain only the newest cached version downloaded. Keeping the image most likely to be needed upon pod restart.</p><p>2) Specific tags can be defined for images to skip (do not purge). By default the two image tags that will not be purged are &lt;none&gt; and latest neither of which are version specific.</p><p>3) <strong><em>CRI Purge</em></strong> makes no attempt to determine if the cached images are still deployed. If you have uninstalled an application, its cached image may still be shown. <strong><em>CRI Purge’</em></strong>s job is just to determine the latest of whatever is currently cached, keep the latest and purge the older version(s).</p><p>4) All interactions with images is via crictl. The script does not do any kind of direct manipulation of images stored or any other file system changes.</p><p>Keep in mind the latest cached image downloaded, is only the latest cached image a particular node downloaded. Other nodes may have the same version or newer (or older). Each node’s perspective on what the latest version means will be dependent on how pods were scheduled in the past.</p><p>Lastly, not all containers actually use <a href="https://semver.org/">semantic versioning</a>. Worst case, if <strong><em>CRI Purge</em></strong> gets it wrong and the latest version is purged, then the image is simply downloaded again upon next pod restart. No worse than using crictl images —prune.</p><h3>Installation</h3><p>You can fetch the script:</p><pre>$ wget https://raw.githubusercontent.com/reefland/cri-purge/master/cri-purge.sh<br>$ chmod 750 cri-purge.sh</pre><h4>My Use Case</h4><p>My testing is based on a 5 node self-hosted K3S distribution of Kubernetes where crictl requires root access to execute (the script will detect if its running as root and produce an error message when not). Each of my nodes has 1TB NVMe storage where 120GB is dedicated to the OS (Ubuntu 22.04) and Kubernetes installation. 700GB is dedicated to cluster storage for Rook-Ceph (the remaining NVMe storage is left unused for future use).</p><p>On several occasions I received low disk space alerts from Prometheus’s node-exporter which required my manual intervention to free up disk space. I determined the bulk of the disk space was consumed by cached container images. Some images such as Renovate Bot (used for opening Pull Requests when newer image versions are detected) are over 1GB in size and this application can be updated several times per week.</p><p>My first attempt to free up disk space was to use crictl images —prune which worked, but to my surprise it purged everything in use or not. It even purged the Kubernetes pause container image.</p><h4>About Kubernetes Garbage Collection</h4><p><strong>Kubelet</strong> which is the primary node agent that runs on each node, has <a href="https://kubernetes.io/docs/concepts/architecture/garbage-collection/#containers-images">two parameters</a> which can help maintain disk space:</p><ul><li>—image-gc-high-threshold</li><li>—image-gc-low-threshold</li></ul><p>By default these ranges are set to 85% and 80%, meaning when the disk is 85% full, start garbage collection of images until space drops below 80%. These values are too high for my environment, I reduced them to 75% and 60% to keep them well below Prometheus monitoring levels.</p><p>Configuring Kubernetes<a href="https://kubernetes.io/docs/concepts/architecture/garbage-collection/#containers-images"> Garbage Collection</a> should be your primary way to maintain disk space. However, I still use the <strong><em>CRI Purge</em></strong> script occasionally to review which images are cached and manually execute it when needed, such as while doing node maintenance before applying Ubuntu patches.</p><h3>CRI Purge Script</h3><p>Running the script without any arguments will present the usage statement:</p><pre>$ ./cri-purge.sh<br><br>  cri-purge | Version: 0.07 | 06/10/2023 | Richard J. Durso<br>  <br>  List and Purge downloaded cached images from containerd. <br>  -----------------------------------------------------------------------------<br><br>  This script requires sudo access to CRICTL binary to obtain a list of cached<br>  downloaded images and remove specific older images. It will do best effort to<br>  honor semantic versioning always leaving the newest version of the downloaded<br>  image and only purge previous version(s). <br><br>  -h, --help          : This usage statement.<br>  -l, --list          : List cached images and which could be purged.<br>  -p, --purge         : List cached images and PURGE/PRUNE older images.<br>  -s, --show-skipped  : List images to be skipped (humans to clean up)<br><br>  Following version tags are skipped/ignored (not deleted): &lt;none&gt; latest</pre><h3>To List Cached Images</h3><pre>$ sudo ./cri-purge.sh --list</pre><p>The output will show the Total Images cached (all versions) and Unique Images Names cached:</p><pre>Total Images: 129 Unique Images Names: 67</pre><p>The output will then present the images. It will indicate the version tag to KEEP and indicate which version tags could be purged. Below shows where Grafana is image 7 of 67 Unique Image Names:</p><pre>...<br>7 / 67 : Image: docker.io/grafana/grafana - Keep TAG: 9.3.1 (97.9MB)<br>- Purgeable TAG: 9.1.4 (92.4MB)<br>- Purgeable TAG: 9.2.3 (108MB)<br>- Purgeable TAG: 9.2.4 (106MB)<br>- Purgeable TAG: 9.3.0 (97.8MB)<br>...</pre><p>Images that do not have older versions to purge will simply list the current version to KEEP:</p><pre>62 / 67 : Image: registry.k8s.io/sig-storage/csi-attacher - Keep TAG: v4.0.0 (23.8MB)<br>63 / 67 : Image: registry.k8s.io/sig-storage/csi-node-driver-registrar - Keep TAG: v2.5.1 (9.13MB)<br>64 / 67 : Image: registry.k8s.io/sig-storage/csi-provisioner - Keep TAG: v3.3.0 (25.5MB)<br>65 / 67 : Image: registry.k8s.io/sig-storage/csi-resizer - Keep TAG: v1.6.0 (24.1MB)<br>66 / 67 : Image: registry.k8s.io/sig-storage/csi-snapshotter - Keep TAG: v6.1.0 (23.9MB)</pre><h3>To Purge Cached Images</h3><pre>$ sudo ./cri-purge.sh --purge</pre><p>The output will look much the same as list however, this time it will indicate the version tag(s) PURGED:</p><pre>...<br>7 / 67 : Image: docker.io/grafana/grafana - Keep TAG: 9.3.1 (97.9MB)<br>- Purge TAG: 9.1.4 (92.4MB)<br>- Purge TAG: 9.2.3 (108MB)<br>- Purge TAG: 9.2.4 (106MB)<br>- Purge TAG: 9.3.0 (97.8MB)<br>...</pre><p>Here <strong><em>CRI Purge</em></strong> has instructed crictl to remove older Grafana images 9.1.4, 9.2.3, 9.2.4 and 9.3.0 but keep image tag 9.3.1.</p><p>At the end <strong><em>CRI Purge</em></strong> tries to estimate how much disk space was cleaned up:</p><pre>Disk Space Change:  9.7790G</pre><p>To see if you have any images matching the “do not purge” tags:</p><pre>$ sudo ./cri-purge.sh -s</pre><p>In conclusion, <strong><em>CRI Purge</em></strong> should <em>not</em> be your go-to solution for node disk space cleanup. It should be handled by Kubernetes<a href="https://kubernetes.io/docs/concepts/architecture/garbage-collection/#containers-images"> Garbage Collection</a> configuration. That said, there has been several occasions where I needed more free disk space quickly and this script was a handy way to get it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7087af3bf1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Changing Sealed Secrets Passwords in Kubernetes]]></title>
            <link>https://medium.com/@reefland/changing-sealed-secrets-passwords-in-kubernetes-897ce2a011ac?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/897ce2a011ac</guid>
            <category><![CDATA[passwords]]></category>
            <category><![CDATA[bitnami]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[sealed-secret]]></category>
            <category><![CDATA[argo-cd]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 23:27:33 GMT</pubDate>
            <atom:updated>2022-12-17T23:27:33.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>There are plenty of articles that focus on installing Bitnami’s <em>Sealed Secrets</em> application and creating your first Sealed Secret within Kubernetes. However, most article do not cover how to change passwords defined within a Sealed Secret.</p><p><a href="https://docs.bitnami.com/tutorials/sealed-secrets">Sealed Secrets</a> is a product offered by Bitnami Labs. This allow Kubernetes secrets to be safely committed to Git repositories. Even public ones.</p><p>How to install and configure Sealed Secrets is outside the scope of this article. I’m going to assume you already have a Kubernetes cluster with Sealed Secrets installed, you’ve converted your standard secrets to Sealed Secrets and committed your Sealed Secrets YAML files to your Git repository which are deployed to your cluster via a <a href="https://about.gitlab.com/topics/gitops/">GitOps</a> process such as <a href="https://argo-cd.readthedocs.io/en/stable/">ArgoCD</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PE8T6OMHN8YhIC_N" /><figcaption>Photo by <a href="https://unsplash.com/@moneyphotos?utm_source=medium&amp;utm_medium=referral">regularguy.eth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Password Problem</h3><p>Kubernetes does not store secrets encrypted, it only <a href="https://en.wikipedia.org/wiki/Base64">Base64</a> encodes secrets which is trivial to decode back into clear text. This is analogous to a lock on a glass door; it is only intended to keep the honest people out. Anyone else would use a brick and not worry about the lock.</p><p>Since secrets encoded with Base64 are so trivial to decode, they cannot be included with your application deployment to Git repositories. Even if you use private repositories it is unwise to store your Base64 encoded secrets within. Anyone who has access to the repository will have access to the contents of the secret.</p><p>This is where products such as Sealed Secrets come in. Standard Kubernetes secrets can be encrypted and “converted” into a Sealed Secret which is safe to store in a public repository (I personally still insist on using private repositories for secrets). The Sealed Secret is a <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/">Custom Resource Definition</a> (CDR) installed with Sealed Secrets. These YAML files can be identified by object type <strong>kind: SealedSecret</strong>.</p><p>To be clear, this only protects your secrets stored at rest in the Git Repository. Anyone with access to use <strong>kubectl get secrets</strong> will still see the trivial to decode base64 encoded secret. Anyone with access to <strong>etcdctl get /registry/secrets/…</strong> will see secrets in clear text (by default).</p><h3>Vendor Password Complexity</h3><p>Due to this <em>Password Problem</em>, vendors have tried to address this in various ways such as using <a href="https://en.wikipedia.org/wiki/Bcrypt">bcrypt</a> to store a hash of the password. That hash is then stored within a Kubernetes secret using Base64 encoding.</p><p>This creates a new problem, in that you now have to figure out if the password is stored encoded with a hash or some other method. Then you have to figure out how to encode or hash a new password in a way that can be stored within a Sealed Secret that the application will understand.</p><p>The name of the key within the secret is not standardized. It can really be named anything the developer wants. Hopefully the key name used will have some hint that it is for storing a password.</p><p>Finally once that is done, the new password is pushed to Git. Your GitOps process runs and deploys the new secret. You still have to give the application a nudge in someway to reload the new secret. This often requires figuring out which Pod in the application is responsible for loading secrets and restarting that pod.</p><p>Starting to understand why nobody talks about how to change your passwords?? There is not a universal process that works on all applications. However, once you figure out how an application works, you can document it in your processes and should be able to automate the process fairly easily.</p><blockquote>Sometimes you can ignore all this and just notify your deployment controller that secrets are allowed to differ from their Git repository contents. This allows you to use the “change password” feature within an application. The updated password stored internally will no longer match what is defined by Git. Normally something like ArgoCD would see this difference and rollback the change as Git is the “source of truth”. You can define what is allowed to be different using ArgoCD’s “Spec.<a href="https://argo-cd.readthedocs.io/en/stable/user-guide/diffing/">IgnoreDifferences</a>”.</blockquote><p>I’ll demonstrate changing a Sealed Secret that holds my ArgoCD administrative password. This is the password used to log into the ArgoCD web administration or CLI. ArgoCD stores a bcrypt hash of the password and a timestamp of when the password was changed. Should something go wrong, you simply revert the commit to rollback the change and go back to the original Sealed Secret that has your old password.</p><h3>Tools Needed</h3><p>You probably do not have a tool to create the bcrypt hash. Even if you use a Linux desktop, this is not usually installed by default. The easiest method is to install a python version of it:</p><pre>$ pip3 install bcrypt</pre><p>To generate a bcrypt hash of a new password of value “<strong>newPassw0rd</strong>”:</p><pre>$ python3 -c &quot;import bcrypt; print(bcrypt.hashpw(b&#39;newPassw0rd&#39;, bcrypt.gensalt()).decode())&quot;<br><br>$2b$12$75PyWqCR7WL4HMwkA59dk.9/X9OyLmF0A5gQOHPEv87YCOwnk5sLu</pre><p>You can execute the above command over and over, each time you will get a different bcrypt hash value. It does not matter which one you pick. The “<a href="https://en.wikipedia.org/wiki/Salt_(cryptography)">salt</a>” used within is included as part of the bcrypt hash.</p><p>You will also need the <strong>kubeseal</strong> CLI utility which is part of the Sealed Secret installation process.</p><h3>What does the ArgoCD Sealed Secret Look like?</h3><p>This is simply the file generated previously by “<strong>kubeseal</strong>” utility and stored within the git repository. It looks like the following:</p><pre>apiVersion: bitnami.com/v1alpha1<br>kind: SealedSecret<br>metadata:<br>  creationTimestamp: null<br>  name: argocd-secret<br>  namespace: argocd<br>spec:<br>  encryptedData:<br>    admin.password: AgALADcrA0+eqnUGJRBVtJLpbA8LAWJt0KWaFz82K9H4K2qCQ/SeKBKqYDff/hMfmMgqmzdcbg4TXpOGpeJWbVHDmpUCzWY7T/WqPNuo9PCpk6huBiuPOMV9UF5ei92vZwjYG4IqCJpB13ds9QZPB9aQWfpJGtP9oTddMBBmfkhNZDLXURxQKXfBzUJtIUU86r0NLYRWC2wjcA1h0oq45K6Fa4WU33WeQpWsajRT97ekdsL4QqKw0X+nZ9PdGKoLwU+GZRHZFFxqLxzib28Y8IKWocYf/qEtvT+gAwyZKUMSPPTODTovvBcjoMOb3O244JZn/+HZmox4VfTlK/l3xT1aO+SXbmhZqgBI9ywdD1NduTgHNPIwmHMgqIPrZk0U67XrBgQ4XjNVlm2lOc741ipAf/y4HUIzJBE22lv4lAuU+MsZGSmrHH6fBQ1GiTfwg+toiTcKA/C/rNks5HbuC7WuGTm+DilMU3L0Z5MMwXYOzceS2TDaTGFZp3yhcBqm9rn2VrhXU0bHSJBcImUNpE1ZaaJdkMFELHm6hq15RZ0ghJTR7yzLTmWeEcFcKUbRFJiQuUB1E3PRivr1e964rKu9iQgGExYgwnQzo2w2/A/3C3Wrf4gW+8H7PvheC0w9FcMBdqMHCCaXn7JJgXj7xx6zCpD5yncwYJnikpPbUIZHwT16Y3WVGyb8QE80iON/ZrfNo9lMQx5vrq0Z5J6wmebOmT7wjMqHwJW5XH+H9mQZn6cI/7lDqxvBYMKZRYmoBub5v60whNNM01A789s=<br>    admin.passwordMtime: AgDAriIqkv8SlJj0v1RNWfEVOLopM0mIRvgtZVxRq8ahA9EedJMBQQDQDVE5qeIDmgVKO1FDkZFhDc10iilSLwaHSa+/qx1Rd005TCNPRqjqMY9CXVE59auvfPOd7eCRDfH10RL6HNxdCvMFAg5GQrrvbzH3mTyK7+HEy3OXCO8Ht/YyD/aAv32y8FMm68Ugh/zzGazEv8uftM+KNv/I8lu0c830ukRxrLpT818PVEGbIr0nJo3h93nWv3BVsWmw+QJA3AToUrkXohui2gG6Sw0Yua3oTWDLnM0xCFh555/9NBVZoQiOBRMWzwSK8L8WNlXdn/cX1PTcURU2ED6/Cs12L1X5AJE5tCstyi0/cTlvRTUwwrzM8z2sBPE8g2eHgBxBmxhMkEMdzCZ1h9wABKRyzR3ew0JfVBYvs9UjBWHSVf86qzOg36mkN39T1IHxRg2ffq6GfgBt8Px9Q09vxUMEPTbE/8acMYQVBUsZzoQNBC7YirQdmjNgC7houXj/BdAaD0hZw3ftCitA6IRa+s0LAuZfs8ZorbF1/jgAGnXZYsrC4nU+pJr2ibwLu2Cgr1d/kPJ+x8ZMQfstJv47/mhhb5IeqqYIHV3J7qmDVjrNzrGl6uFJ8MGu5rVudMd2xIEnhoDZMUKCzCVbnIVoeG0lPzehxahZPslXj1utcjssz4B01PnyAZH1JxWwPXtdbIEkul4/oGZUigAjSMOuy4gHWf1LuC6m<br>    server.secretkey: AgBUK9IW7G8vvZD3RQDeAWkcn+TaMlTkOeCSgqaPa9ZDta75BI8GhF3dLprXv2adRAPFEhgKyL4D533lJ5AQQ+VKAqJQvYxPo/5wAmzCyLToVCcg6mgLMBgkkkltJAh+/FwTfl7qZbBJoy8WgvowiI1GyHcVWnWo67pjsATwCDqcBvvKMpizKpBxuI+NlPitaDQNBLum/rXTOmdBtS520a9cm9+BRkHcAwiLL0KHlkvV5YUUnovO24GnX0A3rkLCe4QlGoXQyy8Kc317w4zWbCZ2POsWEQfyP55Ey+y3fFN9en9EbsUxzrZis+fvYwAsRjfHqTYWoNxD24Rzk+VPOYt/jmuWdeTzJEF5+CBISZqzysjbjVVOfprBhOONBPLvNHO6TWpR6myKdPglQE8VsbfZJCejslob0KKn+exhFjBFTHgTa+agJLFqIZegR9IBy6F3x1sffY/ZL+w7vUp+x5/GV3qyoecldyQy68Df5twzL/OQ6JRItQbIWJIHBrQXRq+Xc3tBdwZRY39XGutVEO9IqX1+ttST4ZqgxRhsD26VqLqh7oUfWaDD0a1H33g9/IfDnbkk06kMmVjjDRk6tVBKjrt7OVM7TAehAF5BtORF5u8YCg0qafu0oPHuPU/6IHU3OAHKyL0nMQVid1+8Vevw53flNoZ/b1tV34PeP12x9uoyR/Z175SaG/ZRT/RHB4s=<br>  template:<br>    metadata:<br>      creationTimestamp: null<br>      name: argocd-secret<br>      namespace: argocd<br>    type: Opaque</pre><p>We will be interested in changing the values of the “<strong>admin.password</strong>” and “<strong>admin.passwordMtime</strong>” of this Sealed Secret.</p><h3>The Process</h3><p>In the conclusion of this article I will provide the one shot full set of commands needed for the actual day to day work. But before we get there, I’ll break down the process step by step so you’ll have some understanding on how this works and can apply this to other applications.</p><h4><strong>Store the Password</strong></h4><p>The hashed passwords are rather long. We will store it in a Bash variable named <strong>NEWPASS</strong> to keep the syntax of our command line work more tidy. For simplicity the value of the new password is “<strong>newPassw0rd</strong>”. You will obviously use a much more complex password.</p><pre>$ NEWPASS=$(python3 -c &quot;import bcrypt; print(bcrypt.hashpw(b&#39;newPassw0rd&#39;, bcrypt.gensalt()).decode())&quot;)</pre><h4>Create a Kubernetes Secret Template</h4><p>We will use “<strong>kubectl create secret</strong>” command to generate a generic secret and inject it with our new values. The output of this command will be JSON which “<strong>kubeseal</strong>” can be read as input later on. We will pass three flags to this command:</p><ul><li><strong>— dry-run=client</strong> : which means <strong><em>kubectl</em></strong> will render this locally only. This is not to be submitted to the server for processing.</li><li><strong>— from-literal=admin.password=</strong> : <strong><em>kubectl</em></strong> shall populate the value for “<strong>admin.password</strong>” based on the contents of our <strong>NEWPASS</strong> Bash variable.</li><li><strong>— from-literal=admin.passwordMtime=&quot;$(date +%FT%T%Z)”</strong> : will populate the value based on the current timestamp using the Linux <strong><em>date</em></strong> command.</li></ul><pre>$ kubectl create secret generic tempxxx --dry-run=client \<br>  --from-literal=admin.password=&quot;${NEWPASS}&quot; \<br>  --from-literal=admin.passwordMtime=&quot;$(date +%FT%T%Z)&quot; -o json<br><br>{<br>    &quot;kind&quot;: &quot;Secret&quot;,<br>    &quot;apiVersion&quot;: &quot;v1&quot;,<br>    &quot;metadata&quot;: {<br>        &quot;name&quot;: &quot;tempxxx&quot;,<br>        &quot;creationTimestamp&quot;: null<br>    },<br>    &quot;data&quot;: {<br>        &quot;admin.password&quot;: &quot;JDJiJDEyJDc1UHlXcUNSN1dMNEhNd2tBNTlkay45L1g5T3lMbUYwQTVnUU9IUEV2ODdZQ093bms1c0x1&quot;,<br>        &quot;admin.passwordMtime&quot;: &quot;MjAyMi0xMi0xNlQxMjo1MjoxNkVTVA==&quot;<br>    }<br>}</pre><p>The values of our two keys are simply Base64 encoded at this point. To see the value of the “<strong>admin.passwordMtime</strong>”:</p><pre>$ echo -n &quot;MjAyMi0xMi0xNlQxNDoyMzo0M0VTVA==&quot; | base64 -d<br><br>2022-12-16T14:23:43EST</pre><h4>Convert Secret to Sealed Secret</h4><p>The JSON above can be read directly by <strong><em>kubeseal</em></strong>. We will simply pipe this output as input to <strong><em>kubeseal</em></strong>. We will need to pass <strong><em>kubeseal</em></strong> three flags:</p><ul><li><strong>— controller-namespace=sealed-secrets</strong> : the namespace where Sealed Secrets is installed.</li><li><strong>— controller-name=sealed-secrets</strong> : the name of the Sealed Secrets Controller.</li><li><strong>— format yaml</strong> : how we want the output to be formatted.</li></ul><pre>$ kubectl create secret generic tempxxx --dry-run=client \<br>  --from-literal=admin.password=&quot;${NEWPASS}&quot; \<br>  --from-literal=admin.passwordMtime=&quot;$(date +%FT%T%Z)&quot; -o json | kubeseal \<br>  --controller-namespace=sealed-secrets --controller-name=sealed-secrets \<br>  --format yaml<br><br><br>apiVersion: bitnami.com/v1alpha1<br>kind: SealedSecret<br>metadata:<br>  creationTimestamp: null<br>  name: tempxxx<br>  namespace: default<br>spec:<br>  encryptedData:<br>    admin.password: AgCvgPkdLaRRxX/UTHD1/zE3ozahe0soKrzlilB2kbWqhgI78yDytB+MPXLjDy9A6iB8WetYWcyK5qhUEH03xmO6dWp00oeIOIlgM+X3fJy1bAQEp8K0uHpti9qpWj43HlR2OREqYTBV6z54lkxjNMGQ/4WttEslAMOVVs2v5eQJVhlMbfEFT8PoN6/f4SrA9+VzFF9ZiB2XSaNy5JSPBZxReryBETG0hl0I4iQs8D3s043M7J1NGLI1gtXipeGthW77ZsRYt3d9ynwgNMpqTqK6FlODE6v22+gGXFmUIh8BSlrtIaV3hT2vnMYlViglHjilO9BPFNacxJ3fvsvH+ZCQ0Q8GdmZMD9Fa8ZHC5xcl/3feHv5o7sUingBkZ00/pg6kDlBVMOktU+d9e6M+PAgY2t61KFB0FoyVGzsKjDXjQgVYEXaTLuczX2quVjjCzfxet0kraIImD5lpbaWYcxZwkvudRuphbVG4xLBwUJO01VnVOL2SqaC06GZQIqfXHpXUqKg5/gXV2a7O1xgLnzmB+/ERongYSdvqTulvEHVhOjVv+7/tLlev0o+PMFogW43Agnyy8tOFvS0KTbcvzC9REpk9q28cmAjZ2SxwoYNlfNyt8s12F9vHA4WjK5PAuI/51ZAn17uZ/8wXzauDIBtQvdk2E/X3lZjd4VKKWH8Fs3R7SOOcgTD4p3w6Ft6lEQxI9l6btaOa9EiWVT38zpUsKH3qL4iy3uWLSxFWLoQZIKNzJ0hcIo95UQpLkTl0eo4uRLlB6GtWwz7i58Q=<br>    admin.passwordMtime: AgAqrNjEWuXm7hrV8mJcUZ30J1K7u0201JWDYE638dgrksS0dHNH+6JqybmkvvyWKuN2Vt2Z3kl9mFX928nEIcOcG++cqRZUPg/QIHdRhnk4L9p0WSn40m2gKyxZ6fZgDOzryHm0D7L4qacF5T7Gl6DucRxHftKnXlanqjoWhqMIluthjdBilinKbpVqrJCGQnVb389CYN07vXrG1jEIp0GcfOdgLzKieQl2lU+MiqUH2NEKbEw2DhO4v0mMobrM912wXYRcMZH6dCzrsZyBq7lrN+uJpC85qiAXv5mmcAtt86ppv8zCgSenHrs+EKjYxcXHV53/xPNbQh1f4yKSwb8VgB5jgnnj4lMF9qyRVFc2karnwIJltOpSOMfleMxIitDERmgl+Uu7epT6OC5ni3Z1Ges9zDNNRirmqrOqQug7XUOM7agC3Xb5h84R6TIE7NdVdKkLD1Jotrm9Txt+A2nIOpjsGbxGo3MkrZRXRlwMrTghbNf4cV5dlIJZ+bQWq9jNhJBuloCPE6WVYhfP92Wt5yz515WORNHkKYnTueA+fci8uPP/9MatkBQZ6PWTPajwhNpa0G74uID5ajimRurZcNOMXuVnmvPEebSkdN7sK8MviTVAA6iifJBtfRpMyU7E1ZWOGry0iLlunfVIBPsyI5xtrPSkmbQ195jzX+QQO7cOFtBKkuiIWKWW1rBoZPokvA9prcKMyLsppNFV9tNx3vylGx50<br>  template:<br>    metadata:<br>      creationTimestamp: null<br>      name: tempxxx<br>      namespace: default</pre><p>The YAML is now of “<strong>kind: SealedSecret</strong>” and the two values are encrypted. These values can <strong><em>only</em></strong> be decrypted within the cluster that contains the private encryption key. Even the person who encrypted this using the <strong>kubeseal</strong> utility (with the cluster’s public key), cannot decrypt this without access to the private key.</p><p>At this point you could just cut &amp; paste the two lines of “<strong>admin.password</strong>” and “<strong>admin.passwordMtime</strong>” replacing your old values and save that to Git. Who wants to do that manual work?</p><h4>Merge Updated Values into Existing Secret</h4><p>The workflow to update the Sealed Secret in Git would have a copy of the previous secret. So lets merge our updated vales into the existing secret. We can do this by passing one more flag to <strong><em>kubeseal</em></strong>:</p><ul><li><strong>— merge-into </strong>: specifies the path and name of the existing Sealed Secret YAML file to merge the changes into.</li></ul><pre>$ kubectl create secret generic tempxxx --dry-run=client \<br>  --from-literal=admin.password=&quot;${NEWPASS}&quot; \<br>  --from-literal=admin.passwordMtime=&quot;$(date +%FT%T%Z)&quot; -o json | kubeseal \<br>  --controller-namespace=sealed-secrets --controller-name=sealed-secrets \<br>  --format yaml --merge-into argocd_admin_secret-sealed.yaml</pre><p>The updated “<strong>argocd_admin_secret-sealed.yaml</strong>” file can now be committed into Git for deployment via ArgoCD.</p><blockquote><strong>Adding New Keys Value Pairs to a Sealed Secret:</strong></blockquote><blockquote>During a <strong>merge</strong> if the new key name matches an existing key name then it replaces the old key value with the updated key value. If the new key name <strong>does not</strong> exist then <strong>merge</strong> will add the key name and its value into the new Sealed Secret. For example, if your application does not track a timestamp of when the password was last changed you can still store (add) the “<strong>admin.passwordMtime</strong>” key name and value pair to the secret. You can name the key anything you wish as it is only for your reference.</blockquote><h4>Confirming Updated Secrets</h4><p>You can easily tell if the updated password was applied by checking the contents of the “<strong>admin.password</strong>” to see if it matches the contents of the <strong>NEWPASS</strong> variable we stored it in:</p><pre>$ echo ${NEWPASS}<br><br>$2b$12$75PyWqCR7WL4HMwkA59dk.9/X9OyLmF0A5gQOHPEv87YCOwnk5sLu<br><br>$ kubectl get secrets -n argocd argocd-secret \ <br>  -o jsonpath=&#39;{.data.admin\.password}&#39; | base64 -d<br><br>$2b$12$75PyWqCR7WL4HMwkA59dk.9/X9OyLmF0A5gQOHPEv87YCOwnk5sLu</pre><ul><li>If the two values do not match, then something went wrong. It’s possible ArgoCD has not gotten around to sync the change yet or perhaps you provided <strong><em>kubeseal</em></strong> with the wrong public key and the cluster does not have the respective private key to decrypt it (fetch the public key and try again).</li></ul><h4>Restarting ArgoCD</h4><p>The password change will take effect based on when your application reloads secrets. That typically means the next time the Pod is restarted. We can give ArgoCD a nudge by reducing its ApplicationSet Controller <strong><em>replica</em></strong> to zero:</p><pre>$ kubectl scale -n argocd --replicas=0 \ <br>  replicaset argocd-applicationset-controller-b44754f9d<br><br>replicaset.apps/argocd-applicationset-controller-b44754f9d scaled</pre><p>ArgoCD will see this change and roll it back to the proper number of replica as defined within its Git based “source of truth”.</p><p>At this point you can logout of the ArgoCD and login again using the new password.</p><h3>Conclusion</h3><p>Sometimes passwords are just for the initial installation, and never used again. Perhaps once the application is up and running the user accounts are stored in a database or LDAP.</p><p>However, sometimes you are stuck with a password stored in a Kubernetes Secret and that password has been encrypted and committed to a Git repository. This does not make it immune to regular password rotations. You should still be changing passwords and making sure your encryption keys have defined rotations (changes) etc.</p><p>The main steps to changing the password are pretty simple. This assumes you have already fetched the original Sealed Secret YAML file from Git and you know the key name to update:</p><pre>$ NEWPASS=$(python3 -c &quot;import bcrypt; print(bcrypt.hashpw(b&#39;newPassw0rd&#39;, bcrypt.gensalt()).decode())&quot;)<br><br>$ kubectl create secret generic tempxxx --dry-run=client \<br>  --from-literal=admin.password=&quot;${NEWPASS}&quot; \<br>  --from-literal=admin.passwordMtime=&quot;$(date +%FT%T%Z)&quot; -o json | kubeseal \<br>  --controller-namespace=sealed-secrets --controller-name=sealed-secrets \<br>  --format yaml --merge-into argocd_admin_secret-sealed.yaml</pre><ul><li>Use a better password than “newPassw0rd”. 😝</li><li>Commit the updated the Sealed Secret YAML file to Git (named <strong><em>argocd_admin_secret-sealed.yaml</em></strong> in this example).</li><li>Restart the application to reload the new secret.</li><li>Test the new password (or rollback to previous YAML file version if it does not work).</li></ul><p>Lastly, if your application does not require something like <strong>bcrypt</strong> hash, then simply:</p><pre>$NEWPASS=&quot;newPassw0rd&quot;</pre><blockquote>I’m trying to get past Medium’s minimum follower requirement. If you found this article interesting or helpful then a <strong><em>clap</em></strong> 👏🏻 and <strong><em>follow</em></strong> 🤳🏼 would be appreciated.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897ce2a011ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Over-Provisioning SSD for Increased Performance and Write Endurance]]></title>
            <link>https://medium.com/@reefland/over-provisioning-ssd-for-increased-performance-and-write-endurance-142feb015b4e?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/142feb015b4e</guid>
            <category><![CDATA[etcd]]></category>
            <category><![CDATA[ssd-storage]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[homelab]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Wed, 21 Sep 2022 19:02:22 GMT</pubDate>
            <atom:updated>2022-09-21T19:02:22.247Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This is not a deep dive into SSD technology, however many of the high-level concepts related to performance and write endurance are summarized. Many aspects of SSD technology have been left out for brevity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nw4kton0O7sn23r6KKV9jg.jpeg" /><figcaption>Photo by Samsung Memory on Unsplash</figcaption></figure><p>The goal of this article is to help you understand why SSD fail under heavy write workloads. And how I improved SSD write endurance of my on-premise Kubernetes cluster using etcd on SSD devices. At a high level etcd is the key value database used to store the configuration of the Kubernetes cluster, the actual state of the system and the desired state of the system. The etcd produces a steady steam 24x7x365 of disk writes to storage. This article can apply to any application dealing with heavy write workloads on SSD storage.</p><h4>What Got me Here?</h4><p>The abbreviated story is that I used a popular name-brand consumer grade SSD in a small on-premise Kubernetes cluster being used as a proof of concept (not enterprise grade servers) and experienced 100% failure rate of the six SSDs within 1 week of use. All of them had to be replaced.</p><p>This lead me look more carefully at the SSD brand and research how to improve write endurance. I won’t say which brand failed so quickly as my sample size was not large enough to bad-mouth the vendor, and they refunded me without issue. I will state that I switched to Samsung brand SSDs which I manually over-provisioned and these have been running great for several months.</p><p>I didn’t have access to devices well known for endurance like the Intel Optane or Kioxia SSDs. This experiment is still in progress and being monitored.</p><h4>What is Over-Provisioning?</h4><p>Over-Provisioning an SSD is just an inclusion of extra storage capacity used to increase the endurance of the SSD by distributing the number of writes and erases across a larger population of NAND flash memory <strong>blocks</strong> and <strong>pages</strong> over time. In addition it improves write performance by increasing the probability that a write operation will have immediate access to a pre-erased block.</p><p>All SSDs reserve some amount of space to support write operations (see <strong><em>How SSD are Written</em></strong> below). The reserved space can be used for the controller firmware, reserved space for failed block replacements, etc. The factory determines the minimum amount of space the SSD will have for over-provisioning. However, you can allocate more space for better performance and improved write endurance.</p><h4>How SSD are Written</h4><p>The smallest addressable unit of NAND flash memory is typically a 4KiB page. Then typically 64 of these pages are grouped into a block of 256KiB. While the SSD is able to write one 4KiB page at a time, it can only write to a empty (blank) page.</p><p>It is impossible with NAND flash to directly update an existing page which has data. To update an existing page it has to be erased. However, individual pages cannot be erased. Only an entire block of 64 4KiB pages can be erased at one time. Instead the SSD will write to a different blank page and then update the Logical Block Address (LBA) table. Inside the LBA table, the original page is marked as invalid and the new page is marked as the current location for the new data.</p><h4>Garbage Collecting</h4><p>While the old page is marked as invalid that space is not yet available for reuse. Based on some schedule the SSD will erase all pages marked as invalid. This scheduled process is called <strong>Garbage Collecting</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*Ng8Rx5NH1sdGLeTyTKDEsA.png" /><figcaption>Image from Over-Provisioning Benefits for Samsung Data Center SSDs White Paper</figcaption></figure><ul><li>STEP1 — The SSD controller which manages the NAND flash memory will locate block(s) which have page(s) marked as invalid.</li><li>The controller will read all the valid pages of the block(s) (skipping the invalid pages) and re-write the valid pages to a new block.</li><li>STEP2 —The original block of 64 pages is then erased allowing it to be used for new data.</li></ul><p>Garbage Collecting does not improve performance within a single pass. It will take a number of writing data and garbage collecting cycles to consolidate the freed up spaces to improve performance.</p><h4>Factory Over-Provisioning Basics</h4><p>Most technical people are aware that one gigabyte of storage is not 1,000,000,000 bytes. They know it is some multiplication of 1024 bytes (which would be 1,048,576 * 1024 or more precisely 2³⁰ bytes which is 1,073,741,824 bytes). This is the difference in marketing terms between one gigabyte (GB) and one gibibyte (Gib). There is roughly about 7.37% difference between the two terms. That difference is typically the minimum reserved space for over-provisioning, sometimes called the “built-in” amount, but the actual amount could be higher especially with higher quality SSDs.</p><blockquote>Typically the minimum reserved space for Over-Provisioning is just the difference between binary and decimal naming conventions used to describe how large an SSD is.</blockquote><p>For example, a 128 GB SSD would have a minimum reserved space of 128 * 73,741,824 = 9,438,953,472 bytes of over-provisioning.</p><p>So in theory if you completely filled up the SSD, it will still have that 7.37% of disk space to support disk writes (disk write performance will suffer with such little space to work with).</p><p>To improve the write performance issue, some manufacture will simply reduce the capacity of the SSD. If you see a 100GB SSD, it is probably a native 128GB device with 28GB used for over-provisioning. That would be 28% over-provisioning in addition to the 7.37% minimum built-in.</p><h4>Write Amplifications</h4><p>The SSD writes often require writing data <em>more than once</em>. You have the initial write to save the data the first time and later when moving data during multiple garbage collection cycles. This results in more data being written to the SSD flash memory than was originally issued by the host system. This is known as a write amplification which is not desirable as it increases wear on the flash and reduces available bandwidth to flash memory.</p><p>Many factors contribute to write amplification such as if the data is written randomly vs. sequentially. As less space is available, and less contiguous blocks are available data becomes written to more randomly. Writing to non-sequential LBAs have the largest impact on write amplifications.</p><p>Data compression reduces the number of pages and blocks written and helps reduce write amplifications. Consider using a filesystem that supports compression.</p><h4>TRIM</h4><p>The SSD usually is not aware of which blocks of data are invalid and available for reuse with new data. It is not until the Operating System tries to store new data in a previously used location that the SSD knows that a particular location contains invalid data. Otherwise the SSD can only track free space not consumed by user data, everything else the SSD considers “valid data”.</p><p>The TRIM command enables the Operating System to alert the SSD on file deletions about pages which contain unneeded data to be tagged as invalid. These invalid pages are not copied during the next garbage collection and wear leveling. This all helps to reduce write amplification and improve performance.</p><blockquote>The larger the amount of over-provisioning, the better the SSD will perform over longer periods of time. Especially for workloads with lots of random writes.</blockquote><h4>NAND Cell Write Limits</h4><p>NAND flash memory can only be written to and erased a limited number of times. You would expect this limit to get better with each generation of storage devices, however apparently the opposite has happened as manufactures try to make SSD storage cheaper:</p><ul><li>SLC (Single Level Cell) flash holds 1 bit of data per cell. Depending on brand had a lifetime of about 50,000 to 100,000 write/erase cycles.</li><li>MLC (Multi Level Cell) flash holds 2 bits of data per cell. Lower cost, lower speed, lower lifetime of about 1,000 to 10,000 write/erase cycles.</li><li>TLC (Triple Level Cell) flash holds 3 bits of data per cell with lifetimes between 3,000 and 5,000 write/erase cycles. Other variants of TLC sometimes called 3D NAND or V-NAND (Vertical NAND) the lifetimes dropped as low as 1,000 cycles.</li><li>QLC (Quad Level Cell) flash holds 4 bits of data per cell….</li><li>PLC (Penta Level Cell) flash holds 5 bits….</li></ul><h4>Wear-Leveling</h4><p>This wearing out of cells is responsible for the physical limits on the lifetime of NAND flash memory. When data is repeatedly written in areas of the NAND the respective cells wear out quickly. Wear-leveling is a function of the SSD that helps prevent repeated writes to the same cells. It enables cells to be utilized more evenly by swapping the blocks exposed to high write cycles with free blocks.</p><h4>How Much to Allocate to Over-Provisioning</h4><p>While increasing the space allocated to Over-Provisioning has the advantage of improving the performance and lifetime of the SSD (write durability) it also decreases the available space for the host to use.</p><p>How much to allocate will depend on your storage requirements and types of applications used. I personally do not bother to adjust the over-provisioning area on my laptops or desktops. Nor on my servers where SSDs used for generic file storage which are part of larger storage pools. Once the SSDs are going to host database type applications, high-write transaction logs, then I will adjust the over-provisioned storage area.</p><p>In my case it was planning for the Kubernetes etcd key value database store. The etcd storage is not large. By default the storage limit size is 2GB and something significantly smaller than that is expected. Somewhere around 50MB to 500MB range is typical for small to medium clusters.</p><p>The etcd RAFT consensus protocol depends on persistently storing metadata to a log — the majority of etcd cluster members <strong><em>must</em></strong> write <strong><em>EVERY</em></strong> request to disk. The etcd stores multiple versions of keys, takes snapshots and merges them back with previous on-disk snapshots. It also performs inflight compaction to remove prior key revisions. This constant write, rewrite, and data shuffling 24x7x365 can wear out an SSD quicker than you would expect.</p><p>On my small three etcd master nodes proof of concept cluster at pretty much idle load, Prometheus shows on average 15kB/s sustained writes. That is about 54MB/hour which we can round to 40GB/month being written to a very small amount of SSD space. Excessive wear leveling and failed NAND cells is a valid concern.</p><p>I decided that 240GB of 1TB SSD was enough local storage for my needs. (I use 2 SSDs per node, over-provisioned identically configured as a mirror). That is roughly 760GB (75% of storage) being allocated to over-provisioning (per device). I expect this to provide a few years of service.</p><h4>Determine Current Over-Provisioning</h4><p>The smartctl utility is the Linux version of <a href="https://www.smartmontools.org/">SmartMonTools</a> used to interact with the <strong>S</strong>elf-<strong>M</strong>onitoring, <strong>A</strong>nalysis and <strong>R</strong>eporting <strong>T</strong>echnology (SMART) system built into many disk devices. Before over-provisioning, I used smartctl to show the device information:</p><pre>$ sudo smartctl -i /dev/sda</pre><pre>=== START OF INFORMATION SECTION ===<br>Model Family: Samsung based SSDs<br>Device Model: Samsung SSD 860 EVO M.2 1TB<br>Serial Number: [redacted]<br>LU WWN Device Id: [redacted]<br>Firmware Version: RVT24B6Q<br><strong>User Capacity: 1,000,204,886,016 bytes [1.00 TB]</strong><br>Sector Size: 512 bytes logical/physical<br>Rotation Rate: Solid State Device<br>Form Factor: M.2<br>TRIM Command: Available, deterministic, zeroed<br>Device is: In smartctl database [for details use: -P show]<br>ATA Version is: ACS-4 T13/BSR INCITS 529 revision 5<br>SATA Version is: SATA 3.2, 6.0 Gb/s (current: 6.0 Gb/s)</pre><ul><li>The starting user capacity is 1,000,204,886,016 bytes [1.00 TB]</li><li>Assuming actual capacity is 1,099,511,627,776 bytes [1 TiB]</li><li>Built-in Over-Provisioning is 99,306,761,760 bytes [99.3 GB] (about 10% OP)</li></ul><h4>Calculate Sectors Needed</h4><p>We need to convert the desired usable space into the number of sectors required to hold that space. As stated above, my requirement is about 240GB of disk space.</p><p>240 Gib = 257,698,037,760 bytes. As smartctl output above shows, the sector size of this device is <strong>512</strong> bytes. We then divide the desired byte count by <strong>512</strong> to get 503,316,480 sectors (if your device reports <strong>4096</strong> byte sectors then divide by that instead).</p><p>I now have my magic number of 503316480 sectors. Next we want to instruct the SSD device that this is now the total number of available sectors which can be used for User Storage. All remaining sectors are reserved in the <a href="https://en.wikipedia.org/wiki/Host_protected_area">Host Protected Area</a> (HPA) to be used for Over-Provisioning.</p><h4>How to Adjust Over-Provisioning?</h4><p>Most SSD manufactures provide custom tool for this. However, the standard Linux hdparm disk management tool can be used with SATA based SSDs, and I will demonstrate it below.</p><blockquote>I have seen conflicting information if this can be adjusted on an active working SSD. I personally wouldn’t do that. I suggest adjusting the Over-Provisioning area before creating partitions and formatting the device for use.</blockquote><p>The hdparm utility might not be installed by default. Don’t be surprised if you need to install that manually from your package repository.</p><pre>$ sudo hdparm -Np503316480 --yes-i-know-what-i-am-doing /dev/sda</pre><pre>/dev/sda:<br> setting max visible sectors to 503316480 (permanent)<br> max sectors   = 503316480/1953525168, HPA is enabled</pre><ul><li>The N parameter is used to set the maximum visible number of sectors.</li><li>The p makes the change permanent (you can only issue one permanent change per session, if you need to change this, power off the computer first before attempting again)</li><li>The — yes-i-know-what-i-am-doing is a required flag since this is a destructive operation. If you do not supply this flag you will get an error message about it.</li><li>The /dev/sda is the device name to be updated. Your device name may be different.</li></ul><h4>Over-Provision Verification</h4><p>At this point it is <strong><em>HIGHLY</em></strong> suggest you reboot the system and test the hdparm command again to make sure it is still reported correctly. It’s possible some Linux distributions have HPA <em>disabled</em> by default which will ignore the changed settings.</p><p>You should be able to use hdparm with -N to confirm the HPA has been unlocked:</p><pre>$ sudo hdparm -N /dev/sda</pre><pre>/dev/sda:<br> max sectors   = 503316480/1953525168, HPA is enabled</pre><p>Lastly you can confirm with smartctl that the new User Capacity is reported correctly:</p><pre>$ sudo smartctl -i /dev/sda</pre><pre>=== START OF INFORMATION SECTION ===<br>Model Family:     Samsung based SSDs<br>Device Model:     Samsung SSD 860 EVO M.2 1TB<br>Serial Number:    [redacted]<br>LU WWN Device Id: [redacted]<br>Firmware Version: RVT24B6Q<br><strong>User Capacity:    257,698,037,760 bytes [257 GB]</strong><br>Sector Size:      512 bytes logical/physical<br>Rotation Rate:    Solid State Device<br>Form Factor:      M.2<br>TRIM Command:     Available, deterministic, zeroed<br>Device is:        In smartctl database [for details use: -P show]<br>ATA Version is:   ACS-4 T13/BSR INCITS 529 revision 5<br>SATA Version is:  SATA 3.2, 6.0 Gb/s (current: 6.0 Gb/s)</pre><p>The <strong>User Capacity</strong> is now reported as 257,698,037,760 bytes which is 240 Gib. Now the SSD device is ready to be partitioned and formatted to suit your needs.</p><h4>Conclusion</h4><p>Over-Provisioning is a proven technique that has been used for many years. I’m expecting this to last quiet a while.</p><h4>Notes on NVMe Over-Provisioning</h4><p>In my opinion, the need to over-provision is from the use of NAND flash. Changing the disk interface from SATA to NVMe doesn’t really change the need to over-provision if you expect to have a write heavy application.</p><p>The hdparm utility does not support NVMe devices and the instructions above will not work for NVMe storage devices. However, the utilities provides by the manufacture such as <strong>Samsung Magician</strong> does allow you to change the over-provisioning on their NVMe drives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PON-eCjMCVigdpsajdGqfA.png" /><figcaption>Screen shot of Samsung Magician Over Provisioning</figcaption></figure><h4>Resources:</h4><ul><li><a href="https://www.atpinc.com/blog/over-provisioning-ssd-benefits-endurance-and-performance">https://www.atpinc.com/blog/over-provisioning-ssd-benefits-endurance-and-performance</a></li><li><a href="https://www.seagate.com/tech-insights/ssd-over-provisioning-benefits-master-ti/">https://www.seagate.com/tech-insights/ssd-over-provisioning-benefits-master-ti/</a></li><li><a href="https://www.techtarget.com/searchstorage/definition/overprovisioning-SSD-overprovisioning">https://www.techtarget.com/searchstorage/definition/overprovisioning-SSD-overprovisioning</a></li><li><a href="https://semiconductor.samsung.com/resources/white-paper/S190311-SAMSUNG-Memory-Over-Provisioning-White-paper.pdf">https://semiconductor.samsung.com/resources/white-paper/S190311-SAMSUNG-Memory-Over-Provisioning-White-paper.pdf</a></li><li><a href="https://www.thomas-krenn.com/en/wiki/SSD_Over-provisioning_using_hdparm">https://www.thomas-krenn.com/en/wiki/SSD_Over-provisioning_using_hdparm</a></li><li><a href="https://en.wikipedia.org/wiki/Multi-level_cell#Single-level_cell">https://en.wikipedia.org/wiki/Multi-level_cell</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=142feb015b4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Traefik Share Resources Across Namespaces]]></title>
            <link>https://medium.com/@reefland/traefik-share-resources-across-namespaces-ffe295789db2?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe295789db2</guid>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Thu, 11 Aug 2022 14:53:30 GMT</pubDate>
            <atom:updated>2022-08-11T14:53:30.160Z</atom:updated>
            <content:encoded><![CDATA[<h3>Share Traefik Resources Across Namespaces</h3><p><a href="https://traefik.io/solutions/kubernetes-ingress/">Traefik Ingress Controller</a> for Kubernetes is secure, resilient, reliable and scalable. Let’s take a break from these best practices and have a little fun with Traefik.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*OE69Hi-hq7KDhs4fPab2AA.png" /><figcaption>Image swiped from <a href="https://tferdinand.net/">https://tferdinand.net</a></figcaption></figure><h3>Namespaced Resources</h3><p>When objects are declared in the Traefik configuration, such as middlewares, TLS options and server transports, they reside within the namespace it was declared in.</p><h4>An Example</h4><p>If you create a Traefik middleware for authentication within the app-dev namespace which references a secret traefik-authsecret (which contains the list of usernames and passwords) within that namespace such as:</p><pre>apiVersion: traefik.containo.us/v1alpha1<br>kind: Middleware<br>metadata:<br>  name: traefik-basic-auth<br>  <strong>namespace: app-dev</strong><br>spec:<br>  basicAuth:<br>    <strong>secret: traefik-authsecret</strong></pre><p>Then only applications deployed within that app-dev namespace can make use of this middleware for authentication. If you try to deploy this middleware to another namespace such as app-test and reference the same secret that will not work as secrets cannot be shared across namespaces. (You can use 3rd party applications to duplicate and replicate secrets to many namespaces, but you cannot share just that one.)</p><p>In most scenarios, this is probably the right configuration… <em>but not always</em>.</p><h4>An Alternative Scenario</h4><p>Let’s imagine a cluster that is not multi-tenant, it is not mission critical production, it’s something more casual where using basic authentication is acceptable. A small team of users each want their own ID and Password to access several applications which support basic authentication.</p><blockquote>I use this as a poor-man’s SSO (Single Sign-On) with my Home Kubernetes cluster to allow my ID &amp; Password to login to many applications in different namespaces such as Prometheus, Alertmanager, Longhorn Dashboard, Traefik Dashboard, etc.</blockquote><p>Remember its not just about authentication, you can ignore the shared authentication secret example. Perhaps you want a single common set of middlewares to define standardized host headers, enable compression, define TLS options and you do not want this duplicated to every application namespace. This can be achieved just as easily.</p><h4>allowCrossNamespaces</h4><p><a href="https://doc.traefik.io/traefik/providers/kubernetes-crd/#allowcrossnamespace">Traefik Documentation</a> has the smallest of blurbs about this feature allowCrossNamespace as:</p><blockquote>Optional, Default: false</blockquote><blockquote>If the parameter is set to true, <strong>IngressRoute</strong> are able to reference resources in namespaces other than theirs.</blockquote><p>Very easy to skip right over this setting if you were not looking for it. This is all we need to change within the Traefik configuration to allow sharing across namespaces. Where do you define this? If you install via Helm Chart this will be defined in the additionalArguments section where you enabled the dashboard, set the logging level, etc.</p><pre>additionalArguments:<br>  - &quot;--api.dashboard=true&quot;<br>  - &quot;--log.level=INFO&quot;<br>  <strong>- &quot;--providers.kubernetescrd.allowCrossNamespace=true&quot;</strong></pre><p>Once this has been applied, we can create some simple example middlewares. Since these can now be used in any namespace, we will store them in the same namespace where Traefik is installed, the traefik namespace.</p><pre>---<br># Middleware enables compression</pre><pre>apiVersion: traefik.containo.us/v1alpha1<br>kind: Middleware<br>metadata:<br>  name: compress<br>  namespace: traefik<br>spec:<br>  compress: {}</pre><pre>---<br># Shared Basic Authentication</pre><pre>apiVersion: traefik.containo.us/v1alpha1<br>kind: Middleware<br>metadata:<br>  name: traefik-basic-auth<br>  namespace: traefik<br>spec:<br>  basicAuth:<br>    secret: traefik-authsecret</pre><pre>---<br># Enable X Forwarded HTTPS Protocol</pre><pre>apiVersion: traefik.containo.us/v1alpha1<br>kind: Middleware<br>metadata:<br>  name: x-forward-https-headers<br>  namespace: traefik<br>spec:<br>  headers:<br>    customRequestHeaders:<br>      X-Forwarded-Proto: &quot;https&quot;</pre><p>Now applications deployed to other namespaces can pick and choose which of these middlewares to reuse and they can still define middlewares unique to that application.</p><p>Let’s use Prometheus as an example. The following <strong>IngressRoute</strong> and middleware defined in namespace monitoring will make Prometheus UI available at <a href="https://k3s.example.com/prometheus.">https://k3s.example.com/prometheus.</a></p><pre>---<br>apiVersion: traefik.containo.us/v1alpha1<br>kind: Middleware<br>metadata:<br>  name: prometheus-stripprefix<br>  namespace: monitoring<br>spec:<br>  stripPrefix:<br>    forceSlash: true<br>    prefixes:<br>      - /prometheus<br>      <br>---<br>apiVersion: traefik.containo.us/v1alpha1<br>kind: IngressRoute<br>metadata:<br>  name: prometheus-ingress-route<br>  namespace: monitoring<br>spec:<br>  entryPoints:<br>    - websecure<br>  routes:<br>    - kind: Rule<br>      match: Host(`k3s.example.com`) &amp;&amp; (PathPrefix(`/prometheus`))<br>      middlewares:<br>        - name: <strong>prometheus-stripprefix</strong><br>        - name: <strong>compress</strong><br>          namespace: traefik<br>        - name: <strong>x-forward-https-headers</strong><br>          namespace: traefik<br>        - name: <strong>traefik-basic-auth</strong><br>          namespace: traefik<br>      services:<br>        - kind: Service<br>          name: prometheus-prometheus<br>          port: 9090</pre><p>The important part of the yaml manifest above are the four middlewares referenced:</p><ul><li>prometheus-stripprefix — which is unique to this application and thus defined with the <strong>IngressRoute</strong>, so we don’t need to specify a different namespace to locate it. (It’s function is just to remove the /prometheus from the URI before passing the request to the Prometheus Service which assumes it is running at the root URI. )</li><li>The other three middlewares compress, x-forward-https-headers, traefik-basic-auth are the common middlewares we defined earlier. As these are not deployed within the monitoring namespace, we need to tell Traefik where to find these using namespace: traefik.</li></ul><p>If you wish to store your common middlewares in a different namespace, then adjust this as needed.</p><p>It’s that simple. Now I can login and access my other applications in different namespaces without needing to re-authenticate each time. Plus I only need to change my password in just one secret. I don’t need to setup reflectors to duplicate my authentication secret.</p><blockquote>I’m trying to get past Medium’s minimum follower requirement. If you found this article interesting or helpful then a <strong><em>clap</em></strong> and <strong><em>follow</em></strong> would be appreciated.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe295789db2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access PVC Data without the POD; troubleshooting Kubernetes.]]></title>
            <link>https://medium.com/@reefland/access-pvc-data-without-the-pod-troubleshooting-kubernetes-b28bfdd7502?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b28bfdd7502</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[persistent-volume]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Fri, 22 Jul 2022 15:54:35 GMT</pubDate>
            <atom:updated>2022-07-22T15:54:35.053Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>I recently had a situation where Prometheus was stuck in a crash loop and unable to start. The solution is to delete a file within the <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">Persistent Volume Claim (PVC)</a>. Seemed simple enough, however with the pod in a crash loop the PVC was not mounted within the Prometheus container. How can I deleted the file?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*8u5L8fl9U1MWIu0tLN4Vcg.jpeg" /><figcaption>Photo by Ramón Salinero on Unsplash</figcaption></figure><blockquote>The <strong>goal of this article</strong> is to explain how I resolved this issue and show you how to find and reach the contents of PVC volumes when the respective pod is unavailable.</blockquote><h3>The Issue</h3><p>Sometimes interruptions between Prometheus and the <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">Persistent Volume Claim (PVC)</a> can lead to an empty or corrupt <a href="https://prometheus.io/docs/prometheus/1.8/storage/#chunk-encoding"><em>chunk file</em></a>. This results in Prometheus being stuck in a crash loop. I didn’t know that yet, what I did know was that Prometheus was down and could not start:</p><pre>$ kubectl get pods -n monitoring<br><br>NAME            READY  STATUS           RESTARTS       AGE<br>alertmanager-0  2/2    Running          0              6d20h<br>grafana         3/3    Running          0              6d20h<br>state-metrics   1/1    Running          0              6d20h<br>operator        1/1    Running          0              61m<br>node-exporter   1/1    Running          3 (6d20h ago)  34d<br>node-exporter   1/1    Running          2 (6d20h ago)  34d<br>node-exporter   1/1    Running          3 (6d19h ago)  34d<br><strong>prometheus</strong>-0    1/2    <strong>CrashLoopBackOff</strong> 12 (3m58s ago) 40m</pre><blockquote>NOTE: Output above significantly modified to fit! I will use simpler pod names.</blockquote><p>As can be seen above the Prometheus pod is stuck in state CrashLoopBackOff and had tried to restart 12 times already.</p><blockquote>This article assumes Prometheus is installed in namespace monitoring. While this is common, its not always the case. You may have to adjust steps here to match your setup. Also this Kubernetes installation was using <a href="https://containerd.io/">containerd</a>, a docker based deployment could be different.</blockquote><p>Next logical step is to review the logs for a reason why.</p><pre>$ kubectl logs prometheus-0 -n monitoring</pre><pre>caller=main.go:874 level=info msg=&quot;Scrape manager stopped&quot;<br>caller=main.go:841 level=info msg=&quot;Notify discovery manager stopped&quot;<br>caller=notifier.go:599 level=info component=notifier msg=&quot;Stopping notification manager...&quot;<br>caller=main.go:1103 level=info msg=&quot;Notifier manager stopped&quot;<br>caller=main.go:1112<strong> level=error err=&quot;opening storage failed: /prometheus/chunks_head/000760: invalid magic number 0&quot;</strong></pre><p>The important part is that last line of the log file. We know we have an <em>error</em>. It’s <strong>unable</strong> to <em>open storage</em>. It provides the <em>full path and filename</em> of the file in question and it doesn’t believe in magic today (actual meaning is not relevant to this article).</p><h3>The Solution</h3><p>According to the Prometheus <a href="https://github.com/prometheus/prometheus">GitHub Project</a> the solution to this problem is to locate and delete this file as it is corrupt. Prometheus <strong>will</strong> <em>remain down until you delete this file</em>.</p><blockquote>One could assume that there is a setting to automatically delete/rename a corrupt file to get Prometheus up and running quickly, but apparently this is not a feature yet.</blockquote><p>It’s straightforward to get an interactive shell with Prometheus to try to delete the file:</p><pre>$ kubectl exec -it prometheus-0 -n monitoring -- /bin/sh</pre><p>Normally this will place you in the /prometheus directory which is the database storage (the PVC). However, due to the pod being in stuck in CrashLoopBackOff state the PVC was not mount and it dumped me in the / (root) directory of the pod. Without the PVC mounted there isn’t a way to delete the file.</p><p><em>I really wish it had that auto-delete feature.</em> After a bit more research and reading previous related issues, I found several methods for getting at the PVC contents.</p><h3>The Workaround</h3><p>Each method I reviewed had roughly the same goal but the detailed steps seemed to depend on the type of PVC storage used and how it is mounted on the node. I’ve tried to reduce the number to steps and make it more generic. Be aware there is not a <a href="https://www.dictionary.com/browse/one-size-fits-all"><em>one-size-fits-all</em></a> solution for this.</p><h4>Determine the Prometheus Pod Host</h4><p>First task is to determine which node in the cluster the Prometheus pod is running on. You could simply use kubectl get pods -n monitoring -o wide to determine this but that output will not fit here. So instead, I’ll use <a href="https://kubernetes.io/docs/reference/kubectl/#custom-columns">custom-columns</a> for some fun:</p><pre>$ kubectl get pods -n monitoring \ <br>  -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName<br><br>NAME                                                        NODE<br>alertmanager-kube-prometheus-stack-alertmanager-0           k3s02<br>kube-prometheus-stack-grafana-5c86b6f7cd-mtwlb              k3s02<br>kube-prometheus-stack-kube-state-metrics-54fd8f6c5b-ntj4v   k3s02<br>kube-prometheus-stack-operator-6bd56776b9-6bj4j             k3s01<br>kube-prometheus-stack-prometheus-node-exporter-4rk4j        k3s02<br>kube-prometheus-stack-prometheus-node-exporter-xvm92        k3s03<br>kube-prometheus-stack-prometheus-node-exporter-zvpfw        k3s01<br>prometheus-kube-prometheus-stack-prometheus-0               k3s03</pre><p>As can be seen the real names of the pods just barely fit! More importantly we can see that Prometheus is running on node named k3s03.</p><h4>Determine the Persistent Volume Mount Point</h4><p>Most of the guides I found got lost in a bunch of kubectl get and kubectl describe commands trying to locate where the PVC might be. I think its really more about what are the keywords that might be in the generated name. I started with prometheus and pvc and it worked on the first guess:</p><pre>$ findmnt --raw --output=target | grep prometheus | grep pvc<br><br>/var/lib/kubelet/pods/3bcb4bbb-ed94-4858-92aa-734d285c1f10/volume-subpaths/pvc-69940283-6e0a-4ff3-b2ff-98d08931c3f0/prometheus/2</pre><p>The Linux <a href="https://manpages.ubuntu.com/manpages/xenial/man8/findmnt.8.html"><strong>findmnt</strong></a> command can be used to search for mount points or display a tree structure of all mounted filesystem. It is the proper command to use instead of mount | grep combination as its output is easier to read. In this case either method would work fine.</p><p>Not all <a href="https://kubernetes.io/docs/concepts/storage/storage-classes/#provisioner">Storage Provisioners</a> actually use the letters “<strong>pvc</strong>” in generated names. If you find nothing then just search for prometheus but this might find multiple matches, you will need to determine which is the database one.</p><pre>$ findmnt --raw --output=target | grep prometheus</pre><p>If for some reason you still find nothing, then get the PVC name and search for that:</p><pre>$ kubectl get pvc -n monitoring</pre><blockquote>NOTE: This often shows PVCs for Prometheus Alertmanager, Grafana and the Prometheus DB (database) which is the one we are interested in. Repeat the above search commands with the value you have in the VOLUME name.</blockquote><h4>Become Root and Track Down the File</h4><p>Now that we have an idea where the PVC is mounted on the node hosting the Prometheus pod we can navigate into it as root.</p><pre># Become root user:<br>$ sudo -i</pre><pre># This is just one long line for the PVC mount name:<br>cd /var/lib/kubelet/pods/3bcb4bbb-ed94-4858-92aa-734d285c1f10/volume-subpaths/pvc-69940283-6e0a-4ff3-b2ff-98d08931c3f0/prometheus/2</pre><p>We are now at the equivalent of the /prometheus directory that is reachable inside the pod. Based on the error message we had, we need to look in the chunks_head directory.</p><pre>cd chunks_head</pre><pre># Find the bad file - &quot;000760&quot;:<br>ls<br>000759 000760</pre><p>There is the source of our trouble, a file named 000760. Let’s delete it.</p><pre># Delete the file:<br>rm 000760</pre><p>Simply type exit to quit from the sudo shell and get out of the PVC area.</p><h4>Force a Restart of the Prometheus Pod</h4><p>The easiest way to force a restart of a <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/">Statefulset</a> application is to scale the replicas to zero and then back to one.</p><pre>$ kubectl scale --replicas=0 -n monitoring statefulset \<br>prometheus-kube-prometheus-stack-prometheus</pre><pre>statefulset.apps/prometheus-kube-prometheus-stack-prometheus scaled<br></pre><pre>$ kubectl scale --replicas=1 -n monitoring statefulset \<br>prometheus-kube-prometheus-stack-prometheus</pre><pre>statefulset.apps/prometheus-kube-prometheus-stack-prometheus scaled</pre><h3>Conclusion</h3><p>I monitored the Prometheus log file after being restarted. Prometheus was able to complete its restart without issues. It did not report any additional corrupt file issues.</p><p>I hope you enjoyed this alternative way of getting access to data stored on a Persistent Volume without using the POD. I thought I was going to have to delete the StatefulSet, recover the released PVC in another test pod just to mount and access the volume to delete one file, recover the PVC again and recreate the StatefulSet deployment to get Prometheus back on-line. That would have been a lot of work. This alternate method was much simpler.</p><p>Typically the kubectl cp command is used to transfer files into and out of pods. Unfortunately the kubectl <a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#cp">cp</a> has a requirement of the <a href="https://linux.die.net/man/1/tar">tar</a> utility being available within the pod. I’m wondering if this this method could be an alternate way to bulk load data into a pod… I’ll test this in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b28bfdd7502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring UniFi Network Controller with Prometheus]]></title>
            <link>https://blog.devops.dev/monitoring-unifi-network-controller-with-prometheus-67476b48866?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/67476b48866</guid>
            <category><![CDATA[unpoller]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[pod-monitor]]></category>
            <category><![CDATA[unifi]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 20:32:07 GMT</pubDate>
            <atom:updated>2023-05-26T13:14:31.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In a previous article “<a href="https://medium.com/@reefland/migrating-unifi-network-controller-from-docker-to-kubernetes-5aac8ed8da76">Migrating UniFi Network Controller from Docker to Kubernetes</a>”, we ended with the UniFi Network Controller deployed as a Kubernetes <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/">StatefulSet</a> with <a href="https://longhorn.io/">Longhorn</a> providing persistent storage.</p><p>My UniFi controller has been running for nearly ten months without issue:</p><pre>$ kubectl get statefulset -n unifi</pre><pre>NAME               READY   AGE <br>unifi-controller   1/1     292d</pre><p>And still using less than 1GB of Longhorn persistent storage:</p><pre>$ kubectl exec unifi-controller-0 -n unifi -- \<br>  df -h --output=&quot;source,size,used&quot; /config</pre><pre>Filesystem                                              Size  Used <br>/dev/longhorn/pvc-f59bb75e-7066-4e85-ac3f-be2759d85e63  4.9G  676M</pre><p>The UniFi Network Controller tracks a lot of statistics about the network. However, it does not make this information easily accessible. For example, I have an UniFi Access Point powered by POE on Port 2 of a USW-Lite 16 port switch. This is pretty much all that the UniFi Network Controller will tell me about Port 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*LSHlRvKuyrTL4SySojWgtg.png" /><figcaption>Information Shown with mouse cursor placed over Port 2.</figcaption></figure><p>The goal of this article is to deploy a Prometheus Exporter and PodMonitor which can extract these metrics and make them available to Prometheus and drive a Grafana Dashboard. Afterwards this is now what I have available for Port 2 (shows past 12 hours):</p><figure><img alt="Detailed Grafana dashboard with statisitics on port 2" src="https://cdn-images-1.medium.com/max/1024/1*SZaYlGYVgf2w7FsAnbKNCQ.png" /><figcaption>UnPoller Grafana Dashboard on Port 2</figcaption></figure><h3>Prometheus Exporter</h3><p>A Prometheus Exporter can read metrics provided by another processes which does not expose Prometheus-formatted metrics. The exporter will translate the source metrics into a format that Prometheus can understand and expose these metrics via a URL (an HTTP endpoint) which can be consumed (known as metrics scraping).</p><p>There already exists an excellent Prometheus Exporter for UniFi called <strong>UnPoller</strong> (see <a href="https://github.com/unpoller/unpoller">GitHub Project</a>) written by <em>David Newhall II</em> in Golang.</p><blockquote>The UnPoller project page does not contain any instructions for use with Kubernetes. Looking at how it was intended to be used with Docker, we can get it working perfectly on Kubernetes.</blockquote><h4>UnPoller Prometheus Exporter Configuration</h4><p>The configuration of UnPoller is just a few simple steps:</p><ol><li>Create a Read-Only Admin Account within the UniFi Network Controller.</li><li>Convert the Read-Only Admin credentials into a Kubernetes Secret.</li><li>Define a UnPoller Configuration File to connect to UniFi Network Controller</li></ol><p><strong>Create Read-Only user account in UniFi Network Controller</strong></p><p>Login to the UniFi Network Controller we previously setup under Kubernetes. Navigate to <strong>Settings</strong> &gt; <strong>System</strong> and scroll down to “<strong>Admins</strong>” section. Here you can click “<strong>Add New Admin</strong>”.</p><ul><li>Enter a <strong>Username</strong> such as “unpoller”.</li><li>Enter an <strong>email address</strong>. Annoyingly you will have to complete an email verification process before the account will be activated. This email must also be different from any existing administrative accounts. It will not let you reuse an existing Admin’s email account.</li><li>Set <strong>Role</strong> to be “View Only”.</li><li>Remove any <strong>Site Permissions</strong> assigned such as “Device adaption” or “Device restart”. It should state “Select Read Only permissions”.</li></ul><figure><img alt="Add New Admin Dialog Box within UniFi Network Controller" src="https://cdn-images-1.medium.com/max/389/1*c3iJ20Zz8fS04fQfudwTVw.png" /></figure><ul><li>Click [Invite] to start the email verification process.</li></ul><p>Once the email verification process has been completed, the new admin account will be marked as verified. <em>You should then log into the UniFi Network Console with this account and confirm it is </em><strong><em>unable</em></strong><em> to make any changes.</em></p><figure><img alt="New Admin Marked as Verified" src="https://cdn-images-1.medium.com/max/790/1*SNc4xqBVgdAtj0ibomNWTw.png" /><figcaption>New Admin “<strong>unpoller</strong>” marked as <strong>verified</strong> and role “<strong>View Only</strong>”</figcaption></figure><p><strong>Create Kubernetes Secret</strong></p><p>After the new admin account is confirmed working, create a secret named unpoller-secret for the ID and password:</p><pre>$ kubectl -n unifi create secret generic unpoller-secret \<br>  --from-literal=unifi-user=&lt;USERNAME_HERE&gt; \<br>  --from-literal=unifi-pass=&lt;PASSWORD_HERE&gt; \<br>  --dry-run=client -o yaml &gt; unpoller-secret.yaml<br><br>  # No output expected</pre><p>Manually apply the secret or convert it to a sealed secret or whatever your process is for working with secrets.</p><pre>$ kubectl create -f unpoller-secret.yaml -n unifi<br>secret/unpoller-secret created</pre><p><strong>UnPoller Configuration File</strong></p><p>The configuration file I created essentially disables everything except Prometheus and UniFi. The Prometheus metrics will published on port 9130. If something like enabling Loki is of interests to you, it can be enabled later. Assuming you configured the UniFi Network Controller service as documented in the previous article, you can use the configuration file “as-is”.</p><p>Configuration File: up.conf</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac67ce1fd9b5f745a53c87a531922f73/href">https://medium.com/media/ac67ce1fd9b5f745a53c87a531922f73/href</a></iframe><p>NOTE: The [unifi.defaults] <strong>url</strong> value is the internal Kubernetes service URL of the UniFi Network Controller, <em>NOT</em> the external URL you access it by using a web browser.</p><h3>Prometheus Exporter Manifest Files</h3><p>With the prep work completed we can start creating the manifest files for the deployment of UnPoller for our Prometheus Exporter on Kubernetes.</p><p>My original manifest files can be found in my <a href="https://github.com/reefland/extra_k8s_apps/tree/master/apps/unpoller-exporter">GitHub repository</a> along with the Kustomize files which make it easier to customize to your environment (discussed towards the end).</p><h4>Prometheus PodMonitor</h4><p>The Prometheus Operator includes a <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/#customresourcedefinitions">Custom Resource Definition</a> that allows the definition of the PodMonitor. We can use the PodMonitor to define an application we wish to scrape metrics from within Kubernetes. By using Kubernetes Labels within the PodMonitor, it can identify the Kubernetes Pod we wish to monitor.</p><p>podmonitor.yaml:</p><pre>---<br>apiVersion: monitoring.coreos.com/v1<br>kind: PodMonitor<br>metadata:<br>  name: unpoller-prometheus-podmonitor<br>  namespace: monitoring<br>  labels:<br>    name: unpoller-prometheus-podmonitor<br>    release: kube-prometheus-stack<br>spec:<br>  selector:<br>    matchLabels:<br>      app.kubernetes.io/name: unpoller<br>  namespaceSelector:<br>    matchNames:<br>    - unifi<br>  podMetricsEndpoints:<br>  - port: metrics<br>    path: /metrics</pre><ul><li>The .metadata.labels.release value makes this PodMonitor auto discoverable and dynamically added to the Prometheus instance configuration. I use <a href="https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack">Kube Prometheus Stack</a> which uses the release label kube-prometheus-stack you may need to adjust this for your installation.</li><li>The .spec.selector.matchLabels value points to the name of the pod where<strong> </strong>UnPoller will be running.</li><li>The .spec.namespaceSelector.matchNames value points to the namespace where UnPoller will be running. We will be placing UnPoller into the same namespace the previous article placed the UniFi Network Controller which is namespace unifi.</li></ul><h4>Pod Affinity</h4><p>Pod Affinity allows us to instruct the Kubernetes Scheduler to schedule the UnPoller Pod to the same node where the UniFi Network Controller is already running. The pod affinity rules are defined in the deployment.yaml file. Since UnPoller will be constantly talking to the UniFi Network Controller we are using the requiredDuringSchedulingIgnoredDuringExecution Pod Affinity.</p><pre>...<br>  template:<br>    spec:<br>      affinity:<br>        podAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>            - labelSelector:<br>                matchExpressions:<br>                  - key: app<br>                    operator: In<br>                    values:<br>                      - unifi-controller<br>              topologyKey: &quot;kubernetes.io/hostname&quot;<br>...</pre><p>Essentially the rule is saying to find an existing pod with a label key app with value unifi-controller and place the UnPoller pod on that same node using the topologyKey of kubernetes.io/hostname.</p><h4>Resources</h4><p>UnPoller is very lightweight. In my testing I found it uses about 30% of the CPU request and 85% of the memory request. I have the limits defined a little higher to allow for some extra usage when needed. The resources are defined in the deployment.yaml file.</p><pre>...<br>  resources:<br>    requests:<br>      cpu: &quot;10m&quot;<br>      memory: &quot;30Mi&quot;<br>    limits:<br>      cpu: &quot;25m&quot;<br>      memory: &quot;50Mi&quot;<br>...</pre><h4>ConfigMaps</h4><p>The UnPoller configuration file up.conf will be loaded into a <a href="https://kubernetes.io/docs/concepts/configuration/configmap/">configMap</a> named unpoller-config-file by a Kustomize <a href="https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/#configmapgenerator">configMapGenerator</a>. The configMap is defined in the deployment.yaml file:</p><pre>...<br>  volumes:<br>    - name: unpoller-config<br>      configMap:<br>        name: unpoller-config-file<br>...</pre><p>The configMap will be mounted in the pod in directory /etc/unifi-poller as defined in the deployment.yaml file:</p><pre>...<br>  volumeMounts:<br>    - mountPath: /etc/unifi-poller<br>      name: unpoller-config<br>...</pre><h4>Secrets</h4><p>The secrets for the UniFi Read Only Admin account are mapped to environment variables. The value of unifi-user is mapped to environment variable UP_UNIFI_DEFAULT_USER and unifi-pass is mapped to UP_UNIFI_DEFAULT_PASS as defined in the deployment.yaml file:</p><pre>...<br>  env:<br>    - name: UP_UNIFI_DEFAULT_USER<br>        valueFrom:<br>        secretKeyRef:<br>          name: unpoller-secret<br>          key: <strong>unifi-user</strong><br>    - name: UP_UNIFI_DEFAULT_PASS<br>        valueFrom:<br>        secretKeyRef:<br>          name: unpoller-secret<br>          key: <strong>unifi-pass</strong><br>...</pre><h4>Deployment Manifest File</h4><p>The completed deployment.yaml file for reference is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08914cb01dfd12bc117a81f3d04d5904/href">https://medium.com/media/08914cb01dfd12bc117a81f3d04d5904/href</a></iframe><h3>Grafana Dashboards for UnPoller</h3><p>There are six Grafana dashboards <a href="https://unpoller.com/docs/install/grafana">published by UnPoller</a> based on the UniFi equipment you have:</p><ul><li><a href="https://grafana.com/grafana/dashboards/11310">11310 </a>— Deep Packet Inspection Enabled with UniFi Security Gateway, Edge Routers, etc.</li><li><a href="https://grafana.com/grafana/dashboards/11311">11311 </a>— One or Multiple UniFi Network Sites summary.</li><li><a href="https://grafana.com/grafana/dashboards/11312">11312 </a>— USW Insights for UniFi Switches or Dream machines.</li><li><a href="https://grafana.com/grafana/dashboards/11313">11313 </a>— USG Insights for UniFi Security Gateway or Dream machines.</li><li><a href="https://grafana.com/grafana/dashboards/11314">11314 </a>— UAP Insights for UniFi Access Points.</li><li><a href="https://grafana.com/grafana/dashboards/11315">11315 </a>— Client Insights. Detailed information on connected clients.</li></ul><p>You can import Grafana Dashboards directly using the dashboard numbers listed above. However, personally I use <a href="https://argoproj.github.io/cd/">ArgoCD</a> and follow<a href="https://about.gitlab.com/topics/gitops/"> GitOps methodology</a>, so I prefer store the raw JSON files and then use Kustomize <a href="https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/#configmapgenerator">configMapGenerator</a> to load the JSON into ConfigMaps:</p><pre>generatorOptions:<br>  disableNameSuffixHash: true<br>  labels:<br>    grafana_dashboard:</pre><pre><strong>configMapGenerator</strong>:<br>  - name: unpollerdashboard-network-sites-11311<br>    files: [ unpollerdashboard-network-sites-11311.json ]<br>    <br>  - name: unpollerdashboard-usw-insights-11312<br>    files: [ unpollerdashboard-usw-insights-11312.json ]<br>    <br>  - name: unpollerdashboard-uap-insights-11314<br>    files: [ unpollerdashboard-uap-insights-11314.json ]</pre><pre>  - name: unpollerdashboard-client-insights-11314<br>    files: [ unpollerdashboard-client-insights-11315.json ]</pre><p>If you have enabled the <a href="http://blog.sozinov.eu/2021/03/28/Grafana-dashboards-via-k8s-sidecar.html">Grafana Dashboard Sidecar</a> loader it will look for ConfigMaps with a specific label you defined (I defined label grafana_dashboard) and dynamically load the dashboards into the Grafana instance runtime configuration.</p><p>My configuration is fairly simple, I have the Dashboard Sidecar look for the presence of label grafana_dashboard (the label value is ignored). More complicated environments may need to restrict ConfigMaps to ones with labels with a specific value. In that case you can use a Kustomize patch to set the label value you require. The example below sets the namespace and label value to true (you can set it to dev, prod, fred, anything you want to match).</p><pre>  - patch: |-<br>      - op: replace<br>        path: /metadata/namespace<br>        value: monitoring<br>      - op: add<br>        path: /metadata/labels/grafana_dashboard<br>        value: &quot;<strong>true</strong>&quot;<br>    target:<br>      kind: ConfigMap<br>      name: unpollerdashboard-.*</pre><h3>Kustomize</h3><p>Kustomize is a “template free” way to apply changes to manifest files without actually making modifications to them. There is nothing special you need to install. Kustomize is built into the kubectl command since version 1.14.</p><p>You can grab the files I use directly from my <a href="https://github.com/reefland/extra_k8s_apps/tree/master/apps/unpoller-exporter/workloads/unpoller">GitHub Repository</a>. (<em>If you go up one directory level in that GitHub link, it also includes the files I use to wrap all this to allow ArgoCD to deploy it</em>).</p><h4>Directory Structure</h4><p>The directory structure for the manifests, config file, dashboards, and kustomization scripts looks like:</p><pre><strong>$</strong> tree <br><strong>.</strong> <br>├── <strong>base</strong> <br>│   ├── <strong>application</strong> <br>│   │   ├── deployment.yaml <br>│   │   ├── kustomization.yaml <br>│   │   ├── podmonitor.yaml <br>│   │   ├── unpollerdashboard-client-insights-11315.json <br>│   │   ├── unpollerdashboard-network-sites-11311.json <br>│   │   ├── unpollerdashboard-uap-insights-11314.json <br>│   │   └── unpollerdashboard-usw-insights-11312.json <br>│   └── <strong>conf</strong> <br>│       └── up.conf <br>└── kustomization.yaml</pre><p>To preview what the rendered (metadata with labels and selectors) and patches applied manifests will look like:</p><pre>$ kubectl kustomize .</pre><p>You can manually review the output. However, that does not validate that the output is usable. To add validation, we can attempt a dry-run. A dry-run will process the files but does not make actual changes to the cluster.</p><pre>$ kubectl kustomize . | kubectl create -f - --dry-run=client</pre><pre>configmap/unpollerdashboard-client-insights-11314 created (dry run) <br>configmap/unpollerdashboard-network-sites-11311 created (dry run) <br>configmap/unpollerdashboard-uap-insights-11314 created (dry run) <br>configmap/unpollerdashboard-usw-insights-11312 created (dry run) <br>configmap/unpoller-config-file created (dry run) <br>deployment.apps/unpoller created (dry run) <br>podmonitor.monitoring.coreos.com/unpoller-prometheus-podmonitor created (dry run)</pre><p>With a successful dry-run we can apply the changes to the namespace unifi:</p><pre>$ kubectl kustomize . | kubectl -n unifi create -f -</pre><pre>configmap/unpollerdashboard-client-insights-11314 created<br>configmap/unpollerdashboard-network-sites-11311 created<br>configmap/unpollerdashboard-uap-insights-11314 created<br>configmap/unpollerdashboard-usw-insights-11312 created<br>configmap/unpoller-config-file created<br>deployment.apps/unpoller created<br>podmonitor.monitoring.coreos.com/unpoller-prometheus-podmonitor created</pre><p>Instead, I applied the manifest and kustomization files to my ArgoCD git repository and let ArgoCD process the kustomize deployment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8ciDtF4PJHbaYWQ98PZfA.png" /><figcaption>ArgoCD WebUI presents a nice map of resources created during the deployment.</figcaption></figure><p>The upper level kustomization.yaml file defines all the important values which we might need to update such as image tag version, where the config file is located, namespaces to apply, labels and values to create.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1486bec2f05ceb1d6242c38906bfe902/href">https://medium.com/media/1486bec2f05ceb1d6242c38906bfe902/href</a></iframe><blockquote>Technically you could define the credentials within this as well, but I comment that out as I used Sealed Secrets instead. I would not want the ID and Password here as this will be commit to my git repository for ArgoCD.</blockquote><p>The upper level kustomization.yaml file will process the lower level kustomization.yaml file which is used to render the deployment.yaml, podmonitor.yaml and load all the JSON dashboards into ConfigMaps for Grafana:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f9df413c0afcd3fd2e51891b68ef48b/href">https://medium.com/media/3f9df413c0afcd3fd2e51891b68ef48b/href</a></iframe><h3>Troubleshooting</h3><p>One item to troubleshoot unique to this setup is checking if UnPoller is able to connect to your UniFi Network Controller. You can view the UnPoller log file to determine that:</p><pre><strong>$</strong> kubectl logs -n unifi -l app=unpoller</pre><pre>2022/06/19 22:26:36 [INFO] Prometheus exported at http://0.0.0.0:9130/ - namespace: unifipoller<br>2022/06/19 22:26:54 [INFO] UniFi Measurements Exported. Site: 1, Client: 26, UAP: 2, USG/UDM: 0, USW: 4, DPI Site/Client: 0/0, Desc: 167, Metric: 1372, Err: 0, 0s: 349, Req/Total: 44.2ms / 50ms<br>2022/06/19 22:27:24 [INFO] UniFi Measurements Exported. Site: 1, Client: 26, UAP: 2, USG/UDM: 0, USW: 4, DPI Site/Client: 0/0, Desc: 167, Metric: 1372, Err: 0, 0s: 350, Req/Total: 41.8ms / 49.3ms<br>2022/06/19 22:27:54 [INFO] UniFi Measurements Exported. Site: 1, Client: 26, UAP: 2, USG/UDM: 0, USW: 4, DPI Site/Client: 0/0, Desc: 167, Metric: 1372, Err: 0, 0s: 371, Req/Total: 31.3ms / 40.9ms<br>2022/06/19 22:28:24 [INFO] UniFi Measurements Exported. Site: 1, Client: 27, UAP: 2, USG/UDM: 0, USW: 4, DPI Site/Client: 0/0, Desc: 167, Metric: 1392, Err: 0, 0s: 360, Req/Total: 33.5ms / 43.5ms<br>2022/06/19 22:28:54 [INFO] UniFi Measurements Exported. Site: 1, Client: 27, UAP: 2, USG/UDM: 0, USW: 4, DPI Site/Client: 0/0, Desc: 167, Metric: 1392, Err: 0, 0s: 358, Req/Total: 34.3ms / 41.6ms</pre><p>Once you have confirmed that UnPoller is publishing metrics, you would also want to confirm that Prometheus has detected the PodMonitor and that the state is UP. This is confirmed from within Prometheus under <strong>Status</strong> &gt; <strong>Targets</strong>.</p><figure><img alt="Prometheus Active Target showing UnPoller PodMonitor State is UP" src="https://cdn-images-1.medium.com/max/1024/1*YUIvwuOBWF1gDS9cDywMVA.png" /><figcaption>Prometheus PodMonitor for UnPoller shows State UP</figcaption></figure><blockquote>If you do not see this in the list then auto-discovery didn’t happen; could be the <strong>release label</strong> discussed in the PodMonitor section needs to be adjusted for your installation. If it is found but state is DOWN then troubleshoot using the curl command below.</blockquote><p>If you wanted to troubleshoot using a curl statement directly against UnPoller. The steps below fetch the UnPoller pod IP address, port number and creates an interactive Pod shell that has the curl command available.</p><pre># Get POD IP Address<br>$ kubectl get pods -n unifi -l app=unpoller \<br> -o jsonpath=&#39;{.items[*].status.podIP}&#39;</pre><pre>10.42.2.15</pre><pre># Get POD Port Number<br>$ kubectl get pods -n unifi -l app=unpoller \<br> -o jsonpath=&#39;{.items[*].spec.containers[0].ports[0].containerPort}&#39;</pre><pre>9130</pre><pre># Create a interactive shell in POD with CURL<br>$ kubectl run curl --image=radial/busyboxplus:curl \<br> --rm=true --stdin=true --tty=true --restart=Never</pre><pre># At curl prompt, get first 10 lines from UnPoller<br>[ root@curl:/ ]$ curl -s http://10.42.2.15:9130/metrics | \<br>  grep -v &quot;#&quot; -m 10</pre><pre>go_gc_duration_seconds{quantile=&quot;0&quot;} 4.6267e-05 <br>go_gc_duration_seconds{quantile=&quot;0.25&quot;} 0.000102031 <br>go_gc_duration_seconds{quantile=&quot;0.5&quot;} 0.099062978 <br>go_gc_duration_seconds{quantile=&quot;0.75&quot;} 0.188369757 <br>go_gc_duration_seconds{quantile=&quot;1&quot;} 0.398864909 <br>go_gc_duration_seconds_sum 696.265466277 <br>go_gc_duration_seconds_count 7826 <br>go_goroutines 12 <br>go_info{version=&quot;go1.16.3&quot;} 1 <br>go_memstats_alloc_bytes 3.89068e+06</pre><pre># We have good output from curl! Type exit to Quit this POD<br>[ root@curl:/ ]$ exit</pre><h3>Eye Candy</h3><p>Example from <strong>UnPoller UAP Insights</strong> showing some info about users connected to access points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4th9jI5gJVHYJXYQBqDlw.png" /><figcaption><a href="https://grafana.com/grafana/dashboards/11314">11314 </a>— UAP Insights for UniFi Access Points.</figcaption></figure><p>Example from <strong>UnPoller Client Insights</strong> showing how users are connected, device summary and bandwidth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIJx4-TOAFWQqhv6KMVhVA.png" /><figcaption><a href="https://grafana.com/grafana/dashboards/11315">11315 </a>— Client Insights. Detailed information on connected clients.</figcaption></figure><p>Example from <strong>UnPoller USW Insights</strong> showing all traffic per port on a switch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXnCGhUEpCAWl8GUkUWkcw.png" /><figcaption><a href="https://grafana.com/grafana/dashboards/11312">11312 </a>— USW Insights for UniFi Switches or Dream machines</figcaption></figure><p>Example from <strong>UnPoller USW Insights</strong> showing POE power usage on a port:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*sURaAlBgYv759KBzjY7gaw.png" /><figcaption><a href="https://grafana.com/grafana/dashboards/11312">11312 </a>— USW Insights for UniFi Switches or Dream machines</figcaption></figure><h3>Conclusion</h3><p>This wraps up this two part article with UniFi Network Controller on Kubernetes with Prometheus and Grafana. This information has a limited audience, kudos to making it to the end. 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67476b48866" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/monitoring-unifi-network-controller-with-prometheus-67476b48866">Monitoring UniFi Network Controller with Prometheus</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating UniFi Network Controller from Docker to Kubernetes]]></title>
            <link>https://medium.com/@reefland/migrating-unifi-network-controller-from-docker-to-kubernetes-5aac8ed8da76?source=rss-7e72a89eabe9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aac8ed8da76</guid>
            <category><![CDATA[unifi]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[ubiquiti]]></category>
            <category><![CDATA[self-hosted]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Richard Durso]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 02:10:38 GMT</pubDate>
            <atom:updated>2023-05-26T13:24:31.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The UniFi Network Application Controller is part of a management platform for the UniFi ecosystem of devices made by <a href="https://ui.com/">Ubiquiti</a>. The hardware tends to be very high quality and perfect for home use, small business and enterprise.</p><p>The network device(s) require the presence of a controller to adopt the device (add to your network) and configure the device (add WiFi networks, <a href="https://en.wikipedia.org/wiki/VLAN">vlans</a>, etc). The UniFi Network Application Controller can be <a href="https://www.ui.com/download-software/">downloaded</a> for free (Linux, MacOS and Windows) and used free of charge. Unlike other [annoying] network companies there is no subscription fee to use Ubiquiti equipment you have paid for.</p><p>Once configured most devices such as UniFi switches and UniFi access points can operate just fine without the network controller present, they will use the existing configuration upon a device restart.</p><p>However the controller can also:</p><ul><li>Monitor devices for firmware upgrades, download and apply upgrades off-hours</li><li>Collect and track performance data and metric history about your network as a whole and individual devices</li><li>Perform regular backups of your network configuration</li><li>Perform some basic monitoring tasks</li><li>See <a href="https://dl.ui.com/guides/UniFi/UniFi_Controller_V5_UG.pdf">User Guide</a> for more details.</li></ul><p>If you self-host the controller, then this information can stay privately within your network. Typically you are going to want the UniFi Controller up and running all the time to provide these services.</p><h3>Scope</h3><p>This is not a sales pitch. UniFi equipment isn’t perfect, <a href="https://ui.com/">Ubiquiti</a> company polices are sometimes questionable. But overall they have some equipment I really like. I use several UniFi products in my home network (switches and access points) and I wanted to move my UniFi Network Controller from my Docker Server to my self-hosted Kubernetes cluster.</p><blockquote>My <a href="https://medium.com/@reefland/monitoring-unifi-network-controller-with-prometheus-67476b48866">next article now published</a> is about extracting network metrics from the UniFi Controller container using a Prometheus Exporter, and Prometheus PodMonitor to populate Grafana dashboards which is much more flexible than the few graphs UniFi console can create.</blockquote><p>If you have an enterprise perspective using Ubiquiti products you have other options you should consider such as:</p><ul><li>The <a href="https://store.ui.com/collections/unifi-network-unifi-os-consoles/products/unifi-cloudkey-plus">CloudKey</a> which is essentially dedicated hardware version of the UniFi Network Controller that is cloud connected and you can self host</li><li>The <a href="https://ui.com/consoles/cloud-console">Cloud Console</a> which has a month subscription you can pay instead of having your own local console device</li><li>Do your own home work, I’m not making recommendations for anything :)</li></ul><h3>My Network</h3><p>Don’t dismiss home network as simple Cable TV router and generic dumb switches. Many people run home networks as if it was a small business network to experiment with enterprise class equipment and refine techniques where you can fail and mess up in the privacy of your own home and not have your boss looking over your shoulder. Many of us call this <a href="https://twitter.com/hashtag/100DaysOfHomeLab?src=hashtag_click">HomeLab</a>.</p><p>My Home Internet is provided via a fiber optic line going right to my <a href="https://www.pfsense.org/">pfSense</a> firewall with a few managed UniFi switches throughout the house and UniFi access points to provide WiFi services. When my house was built they wired it for cable TV, but nothing for Ethernet. Like many modern families we stream our TV services now and the cable TV wires are mostly unused.</p><p>Our cable TV wire is not even connected to anything external as internet is provided over the fiber optic line. To re-use the cable TV wires I installed 2.5 Gigabit <a href="https://en.wikipedia.org/wiki/Multimedia_over_Coax_Alliance">MoCA</a> adapters which injects (bridges?) Ethernet onto the cable TV wire. I placed a MoCA 2.5 adapter in my home office (server room switch), family room, master bedroom, any room I needed a small switch or an access point that already had a cable TV wire connection available. [<a href="https://broadbandlibrary.com/a-preview-of-10g-enabling-technologies/">MoCA 3.0</a> is expected to bring 10 GbE speeds!!]</p><p>This effectively created a 2.5 GbE “<a href="https://en.wikipedia.org/wiki/Backbone_network">backbone network</a>” within the house which greatly reduce the amount of WiFi traffic needed and that preserves WiFi bandwidth for devices that actually need it.</p><blockquote>The trade off is the MoCA adapters also introduce some latency to network packets as they have to be converted and re-transmitted between the two wire types. I also have the MoCA devices using encryption among themselves to keep traffic private.</blockquote><p>I treat this MoCA backbone as trunk line where multiple networks run over it. Using <a href="https://www.pfsense.org/">pfSense</a> and UniFi Network Controller I can create multiple WiFi networks (family, guest, <a href="https://en.wikipedia.org/wiki/Internet_of_things">IOT devices</a>, etc) but also create multiple virtual networks (VLANS) within the home LAN. There is a dedicated server network, equipment management network, family network, guest network, IOT device network.</p><p>This combination of pfSense, vlans and the UniFi network controller allow me to keep everything nicely isolated down to individual switch ports. If a device needs to cross vlan boundaries then I make that happen with pfSense firewall rules.</p><h3>Docker to Kubernetes Migration Planning</h3><p>After many years of running my UniFi Network Controller under Docker. I’ve decided to move it to my self hosted multi-node <a href="https://k3s.io/">K3S based Kubernetes</a>. My starting point was to use my existing UniFi <a href="https://docs.docker.com/compose/compose-file/">Docker-Compose file</a> and try to convert it to Kubernetes Manifest files. This is not a straight forward process for many reasons.</p><h4>Docker was a Single Server</h4><ol><li>Setting up a DNS name for the controller was pretty simple. I didn’t have to worry about which node it was running on.</li><li>UniFi controller needs a lot of TCP/UDP ports opened, still pretty easy under Docker.</li><li>Setting up persistent storage was pretty simple. Being a single server, doing a volume mapping to the local server drive was pretty simple.</li></ol><h4>Multi-Node Kubernetes</h4><ol><li>I have 3 nodes now with additional nodes planned in the future. A Kubernetes service will be needed to expose a static IP address. I use <a href="https://github.com/kube-vip/kube-vip-cloud-provider">Kube-VIP</a> to provide IP address for LoadBalancer service, but <a href="https://metallb.universe.tf/">MetalLB</a> works very well.</li><li>By default a Kubernetes Service is TCP or UDP only. To enable UDP &amp; TCP ports on the same service requires a <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/">Kubernetes Mixed Protocol Feature Gate</a> to be enabled. The UniFi service will require both TCP and UDP ports for device discovery and communication.</li><li>The UniFi Web GUI will be an Ingress Route provided by Traefik. I deploy Traefik as a DaemonSet behind another LoadBalanced IP. I created a DNS alias such as unifi.example.com to this LoadBalancer IP in pfSense and Traefik will match the hostname to the service name. If you use <strong>nginix</strong> or <strong>kong</strong> it should be easy to convert to your equivalent ingress.</li><li>For simple Persistent Volume Storage needs like this I use <a href="https://longhorn.io/">Longhorn</a>. Longhorn provides replicated block storage for the cluster. (For large persistent volumes like my Prometheus Database, I use <a href="https://github.com/democratic-csi/democratic-csi">democratic-csi</a> for external iSCSI block storage from my TrueNAS storage server). Longhorn can also create scheduled snapshots of volumes and send a backup of your volumes to an NFS or S3 location. I have Longhorn create backups of my volumes to my TrueNAS storage server via NFS. Handy to have a backup external to the cluster. A simple Longhorn PV around 5GB has been enough for my needs. Longhorn will do its best to mount the PV on the node running the UniFi Network Controller container. But its not a requirement for it to work.</li><li>Since this is a stateful application with a persistent volume, we will deploy it as a <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/">Kubernetes StatefulSet </a>deployment.</li></ol><blockquote>As a reminder, I just use UniFi Switches and Access Points. Ubiquiti makes a lot of other products. If you use UniFi security cameras, phones, doorbells, etc. they might not work. If that happens, it is likely some port requirement missing that you will have to adjust for.</blockquote><h3>Migration Prep Work</h3><p>You will be able to setup the new UniFi Application Controller under Kubernetes without impacting the your existing UniFi Controller installation. You will be able to backup your configuration from the existing installation and import that into the new installation. Just before switching over there will be some settings you need set in the now old installation to tell your network devices to now report to the new UniFi Controller.</p><blockquote>Worst case scenario would be you have to factory reset your network device(s) and adopt them again to the new UniFi Controller. You would loose any device specific settings like profiles assigned to ports. I did not have this happen, but I was prepared for it just in case. You should be too.</blockquote><h4>Enable Mixed Protocol LoadBalancer Service Feature Gate</h4><p>The Mixed Protocol LoadBalancer Service Feature Gate will allow TCP and UDP ports to be load balanced at the same time on the same service.</p><p>The <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/">Kubernetes Feature Gate List</a> contains a list of <em>Alpha</em> and <em>Beta</em> features by Kubernetes Version and if the feature is enabled or not by default.</p><p>The MixedProtocolLBService shows it was an Alpha feature <strong><em>not</em></strong> enabled by default for Kubernetes 1.20 through 1.23. However, with version 1.24 it graduated to Beta and will be enabled by default.</p><p>For K3s to enable feature gates you can place this in the /etc/rancher/k3s/config.yaml (where you often disable the limited version of Traefik that installs by default) such as:</p><pre>k3s_args:<br>    - --disable=traefik<br>    - --kube-apiserver-arg<br>    - feature-gates=MixedProtocolLBService=true</pre><p>Or pass it as a command line parameter to the installation script:</p><p>--kube-apiserver-arg=feature-gates=MixedProtocolLBService=true</p><p>If you are using a different Kubernetes distribution, you’ll have to determine how to enable this. Might be within /etc/kubernetes/manifests/kube-apiserver.yaml</p><h4>Select a Static IP Address of New UniFi Network Controller Service</h4><p>The Kube-VIP service already maintains a pool of IP address that can be given out for LoadBalancer Services. For my network that is 192.168.10.240/29 which is 8 IP addresses starting from .240 address. The .240 and .241 are already used as fixed IP address LoadBalancers for other applications.</p><p>I will be using 192.168.10.242 for the UniFi Controller service. You do not need to assign this a DNS name. However, if you like consistency as I do, then you probably will. I gave it the name unifi-lb.<em>example.com</em> .</p><h4>Create DNS Alias for Web GUI</h4><p>The default ingress route for my cluster is a Load Balanced Service for HA Traefik deployed as a DaemonSet which uses the name k3s.<em>example.com</em> which takes you to the Traefik Dashboard login.</p><p>The DNS for my home network is handled by my pfSense firewall. I can create a DNS alias in the form of a Host Override defined within the <em>DNS Resolver</em> service. This is reachable from the pfSense console under <strong>Services &gt; DNS Resolver</strong>. Scroll down to the bottom of the page and under <strong>Host Overrides</strong> click [+ Add] button.</p><p>I already have an entry for the k3s host defined something like this:</p><figure><img alt="Host Override Options form from pfSense populated with sample data." src="https://cdn-images-1.medium.com/max/763/1*1Fyzc9VK_Iv96nU9QxWvpQ.png" /><figcaption>pfSense Host override for domain name k3s.example.com to IP Address of Traefik Load Balancer IP address</figcaption></figure><p>Just below the options shown above, you can define the new name for the UniFi Network Controller such as:</p><figure><img alt="Additional Name or alias to be assigned to this IP address. In this example the name unifi.example.com will be used." src="https://cdn-images-1.medium.com/max/1024/1*7haO2mCxjVMP-USFLW3ciQ.png" /><figcaption>Create a DNS Alias of unifi.example.com for k3s.example.com</figcaption></figure><p>Click [Save] button when completed. You should now able to ping the alias name from any computer on your network:</p><pre>$ ping unifi -c 5</pre><pre>PING unifi.example.com (192.168.10.240) 56(84) bytes of data.<br>64 bytes from k3s.example.com (192.168.10.240): icmp_seq=1 ttl=64 time=0.209 ms<br>64 bytes from k3s.example.com (192.168.10.240): icmp_seq=2 ttl=64 time=0.134 ms<br>64 bytes from k3s.example.com (192.168.10.240): icmp_seq=3 ttl=64 time=0.155 ms<br>64 bytes from k3s.example.com (192.168.10.240): icmp_seq=4 ttl=64 time=0.146 ms<br>64 bytes from k3s.example.com (192.168.10.240): icmp_seq=5 ttl=64 time=0.152 ms</pre><pre>--- unifi..example.com ping statistics ---<br>5 packets transmitted, 5 received, 0% packet loss, time 4092ms<br>rtt min/avg/max/mdev = 0.134/0.159/0.209/0.025 ms</pre><p>Note that the DNS name resolves to the IP address of k3s.example.com . However, we will be able to use the DNS name unifi.example.com for matching name within the ingress route.</p><h3>UniFi Network Application Controller Manifest Files</h3><p>With the prep work completed we can start creating the manifest files for the deployment of the new UniFi Network Controller on Kubernetes.</p><p>My original manifest files can be found in my <a href="https://github.com/reefland/extra_k8s_apps/tree/master/apps/unifi-controller-argocd-helm">GitHub repository</a> along with the Kustomize files which make it easier to customize to your environment (discussed towards the end).</p><h4>Persistent Storage Claim</h4><p>This will create the PVC for 5 GB of Longhorn storage to hold the UniFi Controller’s datafiles, configuration, backups, etc.</p><pre>---<br>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: unifi-longhorn-pvc<br>spec:<br>  accessModes:<br>    - ReadWriteOnce<br>  storageClassName: longhorn<br>  resources:<br>    requests:<br>      storage: 5Gi</pre><h4>StatefulSet Deployment</h4><p>This will reference the PVC created above and mount it as a volume within the container at /config directory. It also defines the port numbers and protocols that will be needed for the service. Ubiquiti publishes <a href="https://help.ui.com/hc/en-us/articles/218506997-UniFi-Network-Required-Ports-Reference">UniFi ports used</a>, which can help you determine if you need to add additional ports.</p><p>NOTE: The version tag for the container image and labels to apply will be handled in the kustomization file later.</p><pre>---<br>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>  name: unifi-controller<br>spec:<br>  serviceName: unifi-controller<br>  replicas: 1<br>  template:<br>    spec:<br>      containers:<br>      - name: unifi-controller<br>        image: linuxserver/unifi-controller<br>        imagePullPolicy: IfNotPresent<br>        ports:<br>        - name: device-comm<br>          containerPort: 8080<br>          protocol: TCP<br>        - name: stun<br>          containerPort: 3478<br>          protocol: UDP<br>        - name: default-console<br>          containerPort: 8443<br>          protocol: TCP<br>        - name: secure-redirect<br>          containerPort: 8843<br>          protocol: TCP<br>        - name: http-redirect<br>          containerPort: 8880<br>          protocol: TCP<br>        - name: speedtest<br>          containerPort: 6789<br>          protocol: TCP<br>        - name: unifi-disc<br>          containerPort: 10001<br>          protocol: UDP<br>        - name: unifi-disc-l2<br>          containerPort: 1900<br>          protocol: UDP</pre><pre>        resources:<br>          requests:<br>            cpu: &quot;150m&quot;<br>            memory: &quot;1024Mi&quot;<br>          limits:<br>            cpu: &quot;512m&quot;<br>            memory: &quot;2048Mi&quot;</pre><pre>        volumeMounts:<br>          - name: unifi-data<br>            mountPath: /config</pre><pre>      volumes:<br>        - name: unifi-data<br>          persistentVolumeClaim:<br>            claimName: unifi-longhorn-pvc</pre><p>The resources defined are reasonable. The UniFi Network Controller is a large Java application with a MongoDB database. At idle my installation shows it using 865Mi of RAM.</p><h4>Service Definition</h4><p>The service type of LoadBalancer and the fixed IP address to use, as well as label matching will be defined in the kustomization file. This is just to define the mixed protocol ports that the service will listen on.</p><pre>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: unifi-controller<br>spec:<br>  ports:<br>    - name: device-comm<br>      port: 8080<br>      protocol: TCP<br>    - name: stun<br>      port: 3478<br>      protocol: UDP<br>    - name: default-console<br>      port: 8443<br>      protocol: TCP<br>    - name: secure-redirect<br>      port: 8843<br>      protocol: TCP<br>    - name: http-redirect<br>      port: 8880<br>      protocol: TCP<br>    - name: speedtest<br>      port: 6789<br>      protocol: TCP<br>    - name: unifi-disc<br>      port: 10001<br>      protocol: UDP<br>    - name: unifi-disc-l2<br>      port: 1900<br>      protocol: UDP</pre><h4>Ingress Route</h4><p>The <a href="https://doc.traefik.io/traefik/routing/providers/kubernetes-crd/#kind-ingressroute">IngressRoute</a> is a Kubernetes <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/">Custom Resource</a> Definition (CRD) implementation of <a href="https://doc.traefik.io/traefik/routing/routers/#configuring-http-routers">Traefik’s HTTP router</a>. If you want to use a non-CRD Ingress or a different ingress controller, should be easy to convert this to your needs.</p><p>This will map external HTTPS port 443 (known to Traefik as websecure ) to the containers default-console port 8443. The UniFi Network Controller does not know its running in a container so unfortunately it is doing its own self-signed SSL certificate. We need to instruct Traefik to not do a certificate validation check on the target. We know the certificate is invalid and that is OK since Traefik will handle the SSL for us with its own certificates. Will can use the <a href="https://doc.traefik.io/traefik/routing/services/#serverstransport">ServersTransport</a> to tell Traefik to skip certificate validation.</p><pre>---<br>apiVersion: traefik.containo.us/v1alpha1<br>kind: IngressRoute<br>metadata:<br>  name: unifi-ingress-route<br>spec:<br>  entryPoints:<br>    - websecure<br>  routes:<br>    - match: Host(`unifi.example.com`)<br>      kind: Rule<br>      services:<br>      - name: unifi-controller<br>        port: 8443<br>        scheme: https<br>        serversTransport: unifi-ingress-transport</pre><pre>---<br>apiVersion: traefik.containo.us/v1alpha1<br>kind: ServersTransport<br>metadata:<br>  name: unifi-ingress-transport<br>spec:</pre><pre>  insecureSkipVerify: true</pre><p>You can leave the generic host unifi.example.com as it will be replaced by the values defined in the kustomization file.</p><h4>Kustomization File</h4><p>Kustomize is a “template free” way to apply changes to manifest files without actually making modifications to them. There is nothing special you need to install. Kustomize is built into the kubectl command since version 1.14.</p><pre>---<br>kind: Kustomization</pre><pre>resources:<br>  - longhorn-pvc.yaml<br>  - statefulset.yaml<br>  - service.yaml<br>  - ingress-route.yaml</pre><pre>images:<br>  - name: linuxserver/unifi-controller<br>    newTag: 7.1.65</pre><pre>patches:<br>  # Set Service to LoadBalancer and Specify IP Address to use<br>  - patch: |-<br>      - op: add<br>        path: /spec/type<br>        value: LoadBalancer<br>      - op: add<br>        path: /spec/loadBalancerIP<br>        value: 192.168.10.242<br>    target:<br>      kind: Service</pre><pre>  # Set IngressRoute Match Value for Traefik<br>  # Remember to use ` (backtick) not &#39; (single quote) around Host<br>  - patch: |-<br>      - op: replace<br>        path: /spec/routes/0/match<br>        value: Host(`unifi.example.com`)<br>    target:<br>      kind: IngressRoute</pre><pre>  # Set Longhorn Persistent Volume Claim Size<br>  - patch: |-<br>      - op: replace<br>        path: /spec/resources/requests/storage<br>        value: 5Gi<br>    target:<br>      kind: PersistentVolumeClaim</pre><pre>commonLabels:<br>  app: unifi-controller<br>  app.kubernetes.io/instance: unifi-controller<br>  app.kubernetes.io/name: unifi-controller</pre><p>The resources: defines the four manifest files created above that need to be processed for kustomization changes. The images section defines the container image and version number to install. Each of the patch blocks specify what to patch (the target) and what to add or replace. For example the LoadBalancer type and IP address are added to the Service while the Host name for the ingress route is to replace whatever is currently defined.</p><p>To preview what the rendered (metadata with labels and selectors) and patches applied manifests will look like:</p><pre>$ kubectl kustomize .</pre><p>You can manually review the output. However, that does not validate that the output is usable. To add validation, we can attempt a dry-run. A dry-run will process the files but does not make actual changes to the cluster.</p><pre>$ kubectl kustomize . | kubectl create -f - --dry-run=client</pre><pre>service/unifi-controller created (dry run) <br>persistentvolumeclaim/unifi-longhorn-pvc created (dry run) <br>statefulset.apps/unifi-controller created (dry run) <br>ingressroute.traefik.containo.us/unifi-ingress-route created (dry run) </pre><pre>serverstransport.traefik.containo.us/unifi-ingress-transport created (dry run)</pre><p>With a successful dry-run we can apply the changes to the namespace of our choice, below uses namespace unifi .</p><pre>$ kubectl create namespace unifi  <br>namespace/unifi created</pre><pre>$ kubectl kustomize . | kubectl create -n unifi -f -</pre><pre>service/unifi-controller created <br>persistentvolumeclaim/unifi-longhorn-pvc created <br>statefulset.apps/unifi-controller created <br>ingressroute.traefik.containo.us/unifi-ingress-route created <br>serverstransport.traefik.containo.us/unifi-ingress-transport created</pre><p>Instead, I applied the manifest and kustomization files to my ArgoCD git repository and let ArgoCD process the kustomized deployment:</p><figure><img alt="ArgoCD map of deployment resources." src="https://cdn-images-1.medium.com/max/1024/1*4_UzkYjaI9FXzVLyCAb6Ow.png" /><figcaption>ArgoCD WebUI presents a nice map of resources created during the deployment.</figcaption></figure><p>We can check that the IngressRoute was applied with the Traefik dashboard:</p><figure><img alt="Traefik dashboard showing the HTTP router was created and its associated rules, entry points and services" src="https://cdn-images-1.medium.com/max/1024/1*WXWO_eprLheId2ogEAcNDA.png" /><figcaption>Traefik Dashboard showing the UniFi Network Controller HTTP Router (IngressRoute)</figcaption></figure><p>As noted above the UniFi Network Controller is a large Java application. It can take several minutes before it is available for use. If you test the IngressRoute URL too soon you might briefly see <strong>Page Not Found</strong> or <strong>Bad Gateway</strong> messages which lasts a while longer. Just wait and watch the logs….</p><p>You can monitor the application logs for it to be ready (done):</p><pre>$ kubectl logs unifi-controller-0 -n unifi</pre><pre>[s6-init] making user provided files available at /var/run/s6/etc...exited 0. <br>[s6-init] ensuring user provided files have correct perms...exited 0. <br>[fix-attrs.d] applying ownership &amp; permissions fixes... <br>[fix-attrs.d] done. <br>[cont-init.d] executing container initialization scripts... <br>[cont-init.d] 01-envfile: executing...  <br>[cont-init.d] 01-envfile: exited 0. <br>[cont-init.d] 01-migrations: executing...  <br>[migrations] started <br>[migrations] no migrations found <br>[cont-init.d] 01-migrations: exited 0. <br>[cont-init.d] 02-tamper-check: executing...  <br>[cont-init.d] 02-tamper-check: exited 0. <br>[cont-init.d] 10-adduser: executing...<br>...<br>[cont-init.d] 10-adduser: exited 0. <br>[cont-init.d] 15-install: executing...  <br>*** installing unifi packages *** <br>Selecting previously unselected package unifi. <br>(Reading database ... 8892 files and directories currently installed.) <br>Preparing to unpack /app/unifi.deb ... <br>Unpacking unifi (7.1.65-17871-1) ... <br>Setting up unifi (7.1.65-17871-1) ... <br>invoke-rc.d: could not determine current runlevel <br>invoke-rc.d: policy-rc.d denied execution of start. <br>[cont-init.d] 15-install: exited 0. <br>[cont-init.d] 19-deprecate: executing...  <br>[cont-init.d] 19-deprecate: exited 0. <br>[cont-init.d] 20-config: executing...  <br>[cont-init.d] 20-config: exited 0. <br>[cont-init.d] 30-keygen: executing...  <br>[cont-init.d] 30-keygen: exited 0. <br>[cont-init.d] 90-custom-folders: executing...  <br>[cont-init.d] 90-custom-folders: exited 0. <br>[cont-init.d] 99-custom-scripts: executing...  <br>[custom-init] no custom files found exiting... <br>[cont-init.d] 99-custom-scripts: exited 0. <br>[cont-init.d] done. <br>[services.d] starting services <br>[services.d] done.</pre><p>Once it shows done, you can test the IngressRoute URL from your Web Browser. If you have done everything correctly to this point you will get the following screen which has the link to <strong>restore setup from backup</strong>:</p><figure><img alt="Fresh UniFi Network Controller Installation Wizard screen" src="https://cdn-images-1.medium.com/max/1007/1*Kcc4EbwJ8zGPmsjp5G7VKQ.png" /><figcaption>New UniFi Network Controller Installation Wizard Screen</figcaption></figure><p><em>I could not find a published procedure from Ubiquiti for doing the steps below. This is what I came up with from trying to piece together several forum discussion threads on the topic.</em></p><p><strong>NOTE:</strong> It is possible that if you can reuse your existing UniFi Controller DNS name on the IngressRoute and reuse its existing IP address for the LoadBalancer, this could be a simpler process. You might be able to simply shut down the old one and start the new one with a restored setup from backup. <em>I was not able to test this scenario.</em> I had to use a different DNS name and IP address for my Kubernetes Server vs my Docker Server which added some complications trying to get my existing devices to report to the new UniFi Network Controller.</p><h3>UniFi Network Controller Switchover</h3><h4>Make a Configuration Backup</h4><ul><li>Login to your existing UniFi Network Controller and make a backup of your configuration. This is done from <strong>Settings</strong> &gt; <strong>System</strong> scroll down to <strong>Backup</strong> and click [Download] button.</li></ul><h4>Restore Configuration Backup</h4><ul><li>Access the new UniFi Network Controller and click the link for “<strong>Or restore setup from backup</strong>” as show in the screen shot above. Then click the link as shown below to <strong>upload a backup file</strong>.</li></ul><figure><img alt="UniFi Netowork Controller screen asking for where to get backup files from." src="https://cdn-images-1.medium.com/max/959/1*sqBgk9opQAySx3hr8AzxKg.png" /><figcaption>UniFi Controller Screen — upload backup file.</figcaption></figure><p>Now you can browse to the location you saved the configuration backup file and upload it. Within a few moments the restore is completed and you can check to see if your network devices are attached to this controller.</p><h4>Nudge the Network Devices to the New Controller</h4><p>My network devices had no way of knowing that I setup a new controller. To solve this I used the old existing UniFi Controller to tell the network devices about the new controller. This is done with <strong>Override Inform Host</strong> option:</p><ul><li>If your existing UniFi controller is a bit outdated, the option may not be available in the new UniFi web interface. You can check in <strong>Settings</strong> &gt; <strong>System</strong> and then scroll all the way down to <strong>Other Configuration</strong>. Then at the bottom of that section you should see:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*Ly_K8VrruYAlAZExGYJalA.png" /><figcaption>Enable and set the domain name or IP address of your new UniFi Controller</figcaption></figure><p>If you are unable to locate this in the new web interface. You will have to enable the <strong>Legacy Web Interface</strong> and do it from there. That is found in the <strong>Settings </strong>&gt;<strong> System</strong> as well:</p><figure><img alt="How to enable Legacy Web Interface." src="https://cdn-images-1.medium.com/max/674/1*SnmTojzkMy3gmytA1QJrpw.png" /><figcaption>Option to Enable Legacy Web Interface</figcaption></figure><p>Under the <strong>Legacy Web Interface</strong>, you can find the <strong>Override Inform Host</strong> under <strong>Network Application</strong> &gt; <strong>Network Application Settings</strong>:</p><figure><img alt="Legacy Web Interface for Override Host Inform" src="https://cdn-images-1.medium.com/max/1024/1*0sOzJ16KGDw7BZlef6KqaQ.png" /><figcaption>Override Inform Host settings under Legacy Web Interface</figcaption></figure><p>Once this change is applied, after a few minutes you should see your network devices start attaching to your new UniFi Network Controller.</p><p>You may have a UniFi network device that is not managed. These devices might not respond to the <strong>Override Inform Host</strong>. If that is the case, it is probably easier to factory reset the device and then adopt and configure it from the new UniFi Network Controller.</p><p>However, if you are bored there is another option…</p><h3>DHCP Option 43</h3><p>I set <strong>DHCP Option 43</strong> on all my UniFi Network Devices anyway. Think of it as a hint you can provide as part of the DHCP process on how that device can find the UniFi Network Controller.</p><p>I assign all my network devices a Static IP address assigned via DHCP based on the MAC address of its network card. I use pfSense to perform this.</p><p>Using pfSense this is configured in <strong>Services</strong> &gt; <strong>DHCP Server</strong> then select the tab for the <strong>VLAN</strong> (or Interface) of the network the device is on. Then scroll down to the section <strong>DHCP Static Mappings for this Interface</strong>. This is where you configure:</p><ul><li>MAC Address to watch for</li><li>IP Address to Assign</li><li>Hostname to Assign</li><li>Description, DNS Servers, lots of items.</li></ul><p>Scroll down to the bottom and you can define Additional <strong>BOOTP/DHCP Options</strong>. Once defined it will look something like this:</p><figure><img alt="pfSense Configuration Screen to setup DHCP Option 43" src="https://cdn-images-1.medium.com/max/1024/1*YP2T5NN6elIEeYkhotKfMQ.png" /><figcaption>pfSense Configuration for DHCP Option 43</figcaption></figure><p>As you can see it is literally <strong>DHCP Option number 43</strong>. It is a String, but what does the value mean?</p><p>The value 01:04:c0:a8:0a:f2 is the IP address of the UniFi Network Controller converted to Hexadecimal and a standard prefix.</p><ul><li>The prefix is 01:04: and this DHCP option will always start with this for UniFi devices.</li><li>The remaining c0:a8:0a:f2 is the hexadecimal version of the IP address. If its hard to imagine it, then think of it like c0.a8.0a.f2 now convert each value from Hex to Decimal. You can use the Bash shell to convert numbers, to convert c0 to decimal:</li></ul><pre><strong>$</strong> echo $((16#<strong>c0</strong>)) <br>192</pre><p>See where this is going now? Convert them all:</p><pre><strong>$</strong> echo $((16#<strong>c0</strong>)).$((16#<strong>a8</strong>)).$((16#<strong>0a</strong>)).$((16#<strong>f2</strong>)) <br>192.168.10.242</pre><p>That is the IP address of the UniFi Network Controller Service LoadBalancer we defined earlier. Now if you have the decimal numbers of your IP address and need to convert to hex, it’s just as ugly a process:</p><pre><strong>$</strong> printf &quot;%.2x:%.2x:%.2x:%.2x&quot; 192 168 10 242       <br>c0:a8:0a:f2</pre><p>If you include the required prefix of 01:04: then:</p><pre><strong>$</strong> printf &quot;01:04:%.2x:%.2x:%.2x:%.2x&quot; 192 168 10 242   <br>01:04:c0:a8:0a:f2</pre><p>You have the exact full value you need to place within DHCP Option 43.</p><p>Once your new UniFi Network Controller is in good shape and devices are manageable again, be sure to make a backup! and save it in a safe place so you do not need to go through this conversion process again.</p><p>In the next article <a href="https://medium.com/@reefland/monitoring-unifi-network-controller-with-prometheus-67476b48866">now published</a>:</p><ul><li>We will create a Prometheus Exporter that is able to login to the UniFi Console via a read-only account.</li><li>We will create Prometheus ServiceMonitor that can scrape the Exporter metrics and import into Prometheus.</li><li>We will use Pod Affinity to keep the UniFi Controller and Exporter on the same node.</li><li>We will import Grafana dashboards for exploring our UniFi network metrics.</li></ul><blockquote>Be sure to follow me if this is of interested so you do not miss it.</blockquote><p>Some upcoming Prometheus and Grafana eye candy of the UniFi data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBMoBLKtZJLdzRAvpCYeGw.png" /><figcaption>Grafana showing Users Connected to Access Points, channels and WiFi Protocols</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRCxHJXhOPq--GYQ7nbcXw.png" /><figcaption>Grafana showing comparison between 5 GHz and 2.4 GHz packets and drops per access point</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aac8ed8da76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>