<?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 John Montroy on Medium]]></title>
        <description><![CDATA[Stories by John Montroy on Medium]]></description>
        <link>https://medium.com/@john.montroy?source=rss-18ea302cd2e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lDT8P6MLxnWzjW80yMlXCA.jpeg</url>
            <title>Stories by John Montroy on Medium</title>
            <link>https://medium.com/@john.montroy?source=rss-18ea302cd2e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:53:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@john.montroy/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[Go Puzzlers: Comparing Error Values]]></title>
            <link>https://medium.com/go-puzzlers/go-puzzlers-comparing-error-values-ccf26de4b594?source=rss-18ea302cd2e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccf26de4b594</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[John Montroy]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 03:08:39 GMT</pubDate>
            <atom:updated>2023-03-27T03:25:11.846Z</atom:updated>
            <content:encoded><![CDATA[<p>In Go, <a href="https://go.dev/blog/errors-are-values">errors are values</a>, as in they have a value and a type, like anything else. This is different from languages like Java or Python, where errors are exceptional things (pun intended) that require special handling and language syntax, like try / catch.</p><p>Since errors are just values in Go, we handle them by comparing them to other values. There are some subtleties here — thus, this article.</p><h3>#1 —Comparing new errors directly</h3><p>What does this code print out?</p><pre>// Go Playground: https://play.golang.com/p/f_1lmY16aKY<br>e1 := errors.New(“ohno”)<br>e2 := errors.New(“ohno”)<br>// What does this print?<br>fmt.Println(e1 == e2)</pre><p>Answer: false</p><p>We’re starting simple — all errors created via errors.New are distinct. You might know this intuitively or from reading and writing Go code, but why exactly is this true?</p><p><strong>Short answer</strong>: these errors e1 and e2 are ultimately compared as pointers. Pointers are only equal in Go if they point to the same underlying object in memory. Since each call to errors.New is a new allocation (thus the name), the pointers are not equal.</p><p><strong>It DOES NOT MATTER that the errors have the same string value “ohno” within them.</strong></p><p><strong>Long answer?</strong> Let’s take a little detour into how interfaces and comparisons work in Go. The details will aid us in subsequent puzzlers.</p><p>The code for errors.New (as of Go 1.19) is as follows:</p><pre>// New returns an error that formats as the given text.<br>// Each call to New returns a distinct error value even if the text is identical.<br>func New(text string) error {<br>  return &amp;errorString{text}<br>}<br><br>// errorString is a trivial implementation of error.<br>type errorString struct {<br>  s string<br>}<br><br>func (e *errorString) Error() string {<br>  return e.s<br>}</pre><p>A few things to note:</p><ol><li>First off, the docs on the function tell you that all values returned are distinct. Always read the docs.</li><li>For callers, errors.New returns an error interface.</li><li>The actual thing returned is of type *errorString , which implements the error interface using a pointer receiver on the Error() method.</li></ol><p>So when we call the function twice, we get two error interface values implemented by an *errorString inside them. We then compare our two error interface values. What does Go do when comparing two interface values? Let’s check the <a href="https://golang.org/ref/spec">Go Programming Specification</a>, specifically its section on <a href="https://golang.org/ref/spec#Comparison_operators">Comparison Operators</a>:</p><blockquote>Interface values are comparable. Two interface values are equal if they have <a href="https://go.dev/ref/spec#Type_identity">identical</a> dynamic types and equal dynamic values or if both have value nil.</blockquote><p>What are dynamic types and values? We once again delegate to the <a href="https://go.dev/ref/spec#Variables">spec</a>:</p><blockquote>The <em>static type</em> (or just <em>type</em>) of a variable is the type given in its declaration, the type provided in the new call or composite literal, or the type of an element of a structured variable. Variables of interface type also have a distinct <em>dynamic type</em>, which is the (non-interface) type of the value assigned to the variable at run time (unless the value is the predeclared identifier nil, which has no type).</blockquote><p>So here, for errors.New:</p><ol><li>The static type is error.</li><li>The dynamic type is *errorString.</li><li>The dynamic value is &amp;errorString{s: &quot;ohno&quot;}.</li></ol><p>So two interface values are equal if they have identical dynamic types and equal dynamic values. Well, our two errors e1 and e2 certainly have identical dynamic types: *errorString. Do they have equal dynamic values? That would mean comparing the pointer values &amp;errorString{s: &quot;ohno&quot;}. Let’s reference the spec again:</p><blockquote>Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct <a href="https://go.dev/ref/spec#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.</blockquote><p>Well, there you have it. The dynamic values are both separately-allocated struct pointers, e.g. &amp;errorString{s: &quot;ohno&quot;}. The pointers point to different memory / different variables. So they are not equal.</p><h3>#2 — Comparing new errors by value</h3><p>Per <a href="https://go.dev/blog/go1.13-errors">the original blog post</a> introducing them:</p><blockquote>The errors.Is function compares an error to a value.</blockquote><p>So we start by comparing two errors as values using errors.Is. What does this code print out?</p><pre>// Go Playground: https://play.golang.com/p/Kl8d9MpWhc_T<br>e1 := errors.New(&quot;ohno&quot;)<br>e2 := errors.New(&quot;ohno&quot;)<br>// What does this print?<br>fmt.Println(errors.Is(e1, e2))</pre><p>Answer: false</p><p>Yes. This is good. errors.Is should not change the fact that we’re comparing two distinct variables as values. Those variables are two distinct interface values that contain two distinct pointers to structs as their dynamic values.</p><h3>#3— Comparing existing errors as values</h3><p>What does this code print out?</p><pre>// Go Playground: https://play.golang.com/p/cpimPBzUeOS<br>var (<br>  ErrCustom = errors.New(&quot;ohno&quot;)<br>)<br><br>var e1 error = ErrCustom<br>var e2 error = ErrCustom<br>// What does this print?<br>fmt.Println(e1 == e2)<br>// And this?<br>fmt.Println(errors.Is(e1, e2))</pre><p>Answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*smUJ1wBfD_qOH1g__u6o_A.png" /></figure><p>This is good. Both variables are error interface values that contain and point to the same underlying error in memory. So this matches everything we want, and is indeed akin to how we compare error values most of the time.</p><p>Note, however — this is a bit contrived. In normal code, we’d usually compare some error returned by a function to a package-level variable. But this mimics the general idea.</p><h3>#4— Comparing custom errors as values</h3><p>Let’s try one more thing with values. What does this code print?</p><pre>// Go Playground: https://play.golang.com/p/8DGtBOuTQSp<br>type CustomError struct {<br>  Err string<br>}<br><br>func (ce CustomError) Error() string {<br>  return ce.Err<br>}<br><br>func main() {<br>  var e1 error = CustomError{Err: &quot;ohno&quot;}<br>  var e2 error = CustomError{Err: &quot;ohno&quot;}<br>  fmt.Println(errors.Is(e1, e2))<br>}</pre><p>Answer: <strong>true!</strong></p><p>Can you see what happened? We’ve created a custom error type, which implements the error interface using <strong>value receivers</strong>. That means that variables of this type actually ARE compared by value!</p><p>Recall that errors.New returns an error interface value containing an *errorString dynamic type and value. It’s returned with a *errorString because that’s how the Go library writers chose to implement error for the type — using <strong>pointer receivers</strong>. And when we compare pointers, they have to point to the same thing to be equal. This was clearly an intentional choice of semantic — errors.New should return something that is distinct / not equal to any other error, every time! Otherwise they probably would’ve called it something else.</p><p>So now we have a custom error type, which is assigned to and contained within an error interface value. But these dynamic values implement the interface with value receivers, which means they get compared not as pointers, but just as structs! And per the <a href="https://go.dev/ref/spec#Comparison_operators">Golang spec</a> again:</p><blockquote>Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-<a href="https://go.dev/ref/spec#Blank_identifier">blank</a> fields are equal.</blockquote><p>Well, the only fields here are strings, and strings are also compared directly by content:</p><blockquote>String values are comparable and ordered, lexically byte-wise.</blockquote><p>So these custom errors are equal.</p><p>What would happen if we changed our custom error to implement error using pointer receivers? Well, that would just make our situation completely identical to the original *errorString scenario, no? And we know what happens there!</p><h3>Conclusion</h3><p>We’ve looked at how to compare Go errors by value, mostly using == and errors.Is. We haven’t looked at:</p><ul><li>Comparing Go errors by type using errors.As</li><li>Comparing wrapped Go errors</li></ul><p>We’ll tackle these subjects next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf26de4b594" width="1" height="1" alt=""><hr><p><a href="https://medium.com/go-puzzlers/go-puzzlers-comparing-error-values-ccf26de4b594">Go Puzzlers: Comparing Error Values</a> was originally published in <a href="https://medium.com/go-puzzlers">Go Puzzlers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Puzzlers: JSON Unmarshaling]]></title>
            <link>https://medium.com/go-puzzlers/go-puzzlers-json-unmarshaling-bbadfea28ee3?source=rss-18ea302cd2e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbadfea28ee3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[John Montroy]]></dc:creator>
            <pubDate>Wed, 04 May 2022 01:21:40 GMT</pubDate>
            <atom:updated>2022-05-04T01:38:34.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*FfpDBQnvJkmHOlEy1bJQRA.png" /><figcaption>Uh-oh.</figcaption></figure><p>Go does pretty well with JSON, but there are demons lurking on the margins. Here are three edge cases that might bite you.</p><h3>#1 — JSON Tags and Casing</h3><p>What does this code print out?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb93d562d02cb13286e8e7278d2c1c66/href">https://medium.com/media/fb93d562d02cb13286e8e7278d2c1c66/href</a></iframe><p>Note what’s occuring here — the raw JSON data has fields whose casing is the OPPOSITE of the casing defined in the struct tags. Do you think this unmarshals okay?</p><p>Answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*x-a_G84CyYpayLYf8qb6sw.png" /><figcaption>Everything unmarshals just fine!</figcaption></figure><p>Yep, everything unmarshals okay.</p><p>Golang doesn’t care about casing when unmarshaling. As long as your struct field is Exported, Go will unmarshal a raw field with any casing whatsoever. So here, for Field1, you could hand Go raw data with “field1”, “Field1”, “FIELD1”, or “fIeLd1” — Go doesn’t care, and will successfully unmarshal any of these JSON fields into the struct’s Field1.</p><h3>#2 — Default JSON Tags and Casing</h3><p>What does this code print out?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91e152faf4c8ef34a3bee8ff689c0633/href">https://medium.com/media/91e152faf4c8ef34a3bee8ff689c0633/href</a></iframe><p>Here we have the same thing, just with no explicit JSON struct tags. Is the behavior the same?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*NWbrj-rvG4TPP9RRn8RQDg.png" /><figcaption>Yes.</figcaption></figure><p>Yes. This is good. Although #1’s behavior may be surprising, it shouldn’t change based on whether you have explicit JSON tags or not.</p><h3>#3 — Duplicate JSON Fields</h3><p>What does this code print?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b28611ddfdd5c8bc96f02bd6a9ca262e/href">https://medium.com/media/b28611ddfdd5c8bc96f02bd6a9ca262e/href</a></iframe><p>Now we have many Field1 raw fields, with a mixture of different casing as well as an exact duplicate. What does Go do?</p><p>Answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*nYnJXI-79mA1DlKpLl3gBg.png" /><figcaption>Golang takes the last-found matching occurrence.</figcaption></figure><p>It takes the last occurrence of the field, case-insensitive.</p><p>Without the raw payload, there’s no way to know that Golang has arbitrarily chosen the last occurrence of the field and dropped the others.</p><h3>Comments</h3><p>I’m far from the first person to write something up about this behavior. Here’s a <a href="https://github.com/golang/go/issues/14750">GitHub thread</a> dating back to 2016, which itself dates this issue back to Go 1.2.</p><p><a href="https://datatracker.ietf.org/doc/html/rfc7159">RFC 7159</a> defining JSON seems to be silent on this issue of case sensitivity. This means that Go’s take is just one possible take. <a href="https://mtyurt.net/post/jackson-case-insensitive-deserialization.html">Jackson seems to be case-insensitive</a> like Go, but <a href="https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-character-casing">.NET Core requires you to enable case-insensitivity</a>.</p><p>Therefore, it’s not terribly hard to get yourself in a situation where you end up with two duplicate fields with different casing in one JSON payload.</p><ul><li>Perhaps whatever API you consume emits JSON with two field names that differ only in their casing, demanding that you treat them as semantically different.</li><li>Perhaps one application emitted the field with lowercase, and another one, handling serialization differently, emitted the field with uppercase. This is already a bad place to be in, but Go doesn’t help, because it will simply choose the last occurrence without you being any wiser.</li></ul><p>So what do you do if you want case-sensitive JSON unmarshaling? Let’s tackle that in another post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbadfea28ee3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/go-puzzlers/go-puzzlers-json-unmarshaling-bbadfea28ee3">Go Puzzlers: JSON Unmarshaling</a> was originally published in <a href="https://medium.com/go-puzzlers">Go Puzzlers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using K8s Label Selectors in Go — the right way!]]></title>
            <link>https://medium.com/coding-kubernetes/using-k8s-label-selectors-in-go-the-right-way-733cde7e8630?source=rss-18ea302cd2e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/733cde7e8630</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[labels]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[John Montroy]]></dc:creator>
            <pubDate>Sun, 24 Jan 2021 03:10:18 GMT</pubDate>
            <atom:updated>2021-01-24T15:16:39.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using K8s Label Selectors in Go without doing it wrong</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dWN6cMCN_fvc_YtFsBmTg.png" /><figcaption>This is the good stuff.</figcaption></figure><p>Labels are how we group objects together in Kubernetes. Label selectors are how we use those labels to retrieve our grouped objects. There are a <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/">bazillion</a> <a href="https://kubernetesbyexample.com/labels/">articles</a> <a href="https://www.tutorialspoint.com/kubernetes/kubernetes_labels_selectors.htm">out</a> <a href="https://medium.com/faun/node-labels-and-selectors-in-kubernetes-76fbd8a8940c">there</a> on the subject, so if you’re not familiar, start there.</p><p>Instead, our focus here is: <strong>how do I use Kubernetes libraries to work with labels via label selectors?</strong></p><p>If you’re just looking for quick help, the Cheatsheet section will give you top-level summary info. Otherwise, read on.</p><blockquote><strong>Important: </strong>all Go Playground examples here might need to be run a few times for the dependencies to load in. Go Playground has an unforgiving timeout.</blockquote><h3>Cheatsheet</h3><p>There are two Go types for working with label selectors: the <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L45">labels.Selector</a> interface, and the <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/apis/meta/v1/types.go#L1096">LabelSelector</a> struct. They are different.</p><ol><li><a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L45">labels.Selector</a> is used for <strong>filtering</strong> <strong>client reads</strong>. It’s like the client-go equivalent of kubectl label ... -l service=backend. Use <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L96">labels.NewSelector</a> + <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L152">labels.NewRequirement</a> to construct something the client-go can query with.</li><li>The <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/apis/meta/v1/types.go#L1096">LabelSelector</a> struct is used as part of individual Resources as the <strong>API type</strong>. You’d <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#resources-that-support-set-based-requirements">write this struct in your object’s YAML</a> before applying. So you might get this <strong>from</strong> a read (as part of a returned object, e.g. <a href="https://github.com/kubernetes/api/blob/fedd331d628e80908d201b026e3f3dd32f702478/apps/v1beta2/types.go#L341">Deployment</a>), but don’t use this struct <strong>for</strong> client reads.</li><li>You can <strong>convert</strong> from a LabelSelector (what you get from a read) to a label.Selector (what you use to read) with <a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/apis/meta/v1/helpers.go#L34">LabelSelectorAsSelector</a> . But if you’re doing this, you’re either doing something Controller-esque (if so, fine) OR you should just be using labels.Selector directly.</li></ol><h3>Using labels.Selector</h3><p>The labels.Selector interface is located in the <a href="https://github.com/kubernetes/apimachinery">apimachinery</a> repo under <a href="https://github.com/kubernetes/apimachinery/blob/master/pkg/labels/selector.go">pkg/labels/selector.go</a>. It’s used to read and query Kubernetes Objects via their labels.</p><p>You should use it because:</p><ol><li>It provides standard validation for requirements, keys, and values.</li><li>It’s what Kubernetes libraries uses, so it’s battle-tested to the extreme.</li></ol><p>Initialize a new selector with labels.NewSelector() , and then add labels.Requirements as desired. Think of each Requirement as akin to the normal kubectl label operations you might use for <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#equality-based-requirement">equality-based</a> and <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#set-based-requirement">set-based</a> label selection (<a href="https://play.golang.org/p/pZtDqfDmC8i">Go Playground</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b19b189762d01e2d71174b99ee421fc/href">https://medium.com/media/7b19b189762d01e2d71174b99ee421fc/href</a></iframe><p>apimachinery gives you a few additional perks out of the box:</p><ol><li><a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/labels/selector.go#L152">Requirement validation</a> (e.g. Equals shouldn’t have two values).</li><li><a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/util/validation/validation.go#L42">Key validation</a> (e.g. can’t lead with characters like - or _ )</li><li><a href="https://github.com/kubernetes/apimachinery/blob/460d10991a520527026863efae34f49f89c2f4e1/pkg/util/validation/validation.go#L166">Value validation</a> (e.g. label values can’t exceed 63 characters)</li></ol><p>(Note: these key / value validations are widely used and worth perusing in full.)</p><p>apimachinery also provides helpful additional functionality (<a href="https://play.golang.org/p/1RPOPJRCYwX">Go Playground for both</a>):</p><ul><li><strong>labels.Parse</strong> allows you to use the same kubectl label syntax you might already be familiar with.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d47271dbc3664f94a2812c30f9bd9335/href">https://medium.com/media/d47271dbc3664f94a2812c30f9bd9335/href</a></iframe><ul><li><strong>labels.ValidatedSelectorFromSet</strong> is a validated convenience for the simplest label selection use case: give me all objects that match this label set exactly, AND’d together. Pass a Set object (under the hood, just map[string]string like labels themselves), it validates client-side (early errors, no extra load on the API Server), and gives you a Selector you can use to query:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31dba88e452538eeda9dd6f5e1d202e4/href">https://medium.com/media/31dba88e452538eeda9dd6f5e1d202e4/href</a></iframe><h3>What about LabelSelector?</h3><p>LabelSelector is an API type. That means it’s used as part of various Kubernetes Resource Specs. It’s not for client usage or library code, it’s part of the API, just like Pods and ConfigMaps.</p><p>This fact is reflected by where it lives: in apimachinery, but under pkg/apis/v1/meta/types.go. Indeed, comments in that file indicate:</p><blockquote>The package contains two categories of types:</blockquote><blockquote>— external (serialized) types that lack their own version (e.g TypeMeta)</blockquote><blockquote>— internal (never-serialized) types that are needed by several different api groups, and so live here, to avoid duplication and/or import loops (e.g. LabelSelector).</blockquote><p>So when you create an Object, you’re probably going to write out a LabelSelector struct in YAML, and when you retrieve Objects from the API Server using labels.Selector as above, your returned Objects might contain the LabelSelector struct as a field. Modified example from the docs:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    &lt;snip&gt;</pre><p>That spec.selector is a LabelSelector struct object behind the scenes. The Deployment controller will use it (converting it to labels.Selector , more below) to query the Deployment’s Pods.</p><p>If this all sounds very obvious to you, good. The key point to understand here is the difference between normal library code and API types. labels.Selector is library code used to read and filter Kubernetes Objects. LabelSelector is part of the API type you get back from those reads.</p><h3>Converting between the two</h3><p>Say you use a labels.Selector to query Deployments . You get back matching Deployment Objects, all of which have their own LabelSelector data at spec.selector. Maybe you want to now use those LabelSelector objects to query the Pods programmatically. So we need to convert from LabelSelector to labels.Selector (API type -&gt; library type for querying).</p><p>LabelsSelectorAsSelector is your ticket here (r.i.p. Go Playground, not a chance on these dependencies):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95d5fc7967060d7ef73a75c61ec2a0d8/href">https://medium.com/media/95d5fc7967060d7ef73a75c61ec2a0d8/href</a></iframe><p>Why do we need to do this? Well, controllers do it all the time! In order for the Deployment controller to get all Pods it owns, it will:</p><ol><li>Get the LabelSelector API type from a Deployment at spec.selector .</li><li>Convert it to a labels.Selector using LabelsSelectorAsSelector .</li><li>Query Pods using the newly-converted labels.Selector.</li></ol><p>See for yourself in the <a href="https://github.com/kubernetes/kubernetes/blob/fb276ce2015a8bab93dd2d6ff96ca23a657df67b/pkg/controller/deployment/deployment_controller.go#L536">Deployment Controller</a>, reproduced and shortened here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a5e6456817ecb3071e37fb5a5381742/href">https://medium.com/media/9a5e6456817ecb3071e37fb5a5381742/href</a></iframe><p>This also serves as a great example of everything we’ve discussed here, including actually passing a labels.Selector to a Pod client and querying away!</p><h3>Conclusions</h3><p>labels.Selector is library code for filtering reads. LabelSelector is an API type used in other Objects like Deployments and StatefulSets. If you’re writing Go code, you probably want to work with labels.Selector, unless you’re writing controller code that needs to work with some Resource’s selector field!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=733cde7e8630" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-kubernetes/using-k8s-label-selectors-in-go-the-right-way-733cde7e8630">Using K8s Label Selectors in Go — the right way!</a> was originally published in <a href="https://medium.com/coding-kubernetes">Coding Kubernetes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark, Torrents, and Technical Debt]]></title>
            <link>https://medium.com/@john.montroy/spark-torrents-and-technical-debt-9b5cdb23296c?source=rss-18ea302cd2e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b5cdb23296c</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[tech-debt]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[John Montroy]]></dc:creator>
            <pubDate>Tue, 09 Apr 2019 02:04:24 GMT</pubDate>
            <atom:updated>2024-02-28T05:47:17.494Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Broadcast variables are typically encountered early on when first learning Spark. From the <a href="https://spark.apache.org/docs/2.4.0/rdd-programming-guide.html#broadcast-variables">Spark docs</a>:</p><blockquote>Broadcast variables allow the programmer to keep a read-only variable cached on each machine rather than shipping a copy of it with tasks.</blockquote><p>Fair enough. Let’s zoom in a little closer on what comes next:</p><blockquote>Spark also attempts to distribute broadcast variables using efficient broadcast algorithms to reduce communication cost.</blockquote><p>In this post, we’re going to dive into a few things:</p><ol><li>Understand what this mysterious “efficient broadcast algorithm” is</li><li>Examine how Spark uses class-based design patterns — in particular, the Factory pattern — to implement Broadcast variables</li><li>See an example of technical debt creeping into one of the most contributed-to codebases around!</li></ol><h4>Spark’s TorrentBroadcast</h4><h4>Torrenting Basics</h4><p>Let’s cut to the chase — torrents! Spark uses the torrenting algorithm for broadcasts. This includes Broadcast variables, of course, but note that <strong>all</strong> serialized Spark closures sent to executors are distributed via this torrenting broadcast algorithm.</p><p>The torrent algorithm itself is pretty simple. Pretend we’re all taking a math test. Now pretend we’re all cheating off each other’s answers, but also we know that ultimately we’re all stealing Lisa’s answers (who sits in the middle of the room), because she’s the best student in the class.</p><p>Ta-da, torrenting. Peer-to-peer knowledge / data sharing, where one person seeds the original data to everyone else, who then cheat amongst themselves. We call Lisa the “uploader”, and everyone else a “downloader”. Or, if you prefer, Lisa is the “seeder” and everyone else is a “leecher”.</p><p>From Spark’s perspective, “Lisa’s answers” correspond to the broadcast variable, which is generated on the Spark driver and distributed via torrenting to the executors for computation.</p><p>Let’s revisit Spark’s description of broadcast variables with that in mind:</p><blockquote>Spark also attempts to distribute broadcast variables <strong><em>help everyone get Lisa’s answers</em></strong> using efficient broadcast algorithms <strong><em>by letting everyone cheat off each other </em></strong>to reduce communication cost <strong><em>help everyone finish the test faster and better</em></strong>.</blockquote><p>Visually (from Wikipedia.org):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LroK5Rb1sqhSqYj4.png" /></figure><h4>The TorrentBroadcast Algorithm</h4><p>Let’s first demonstrate how Spark implements its torrenting algorithm by studying what happens when you attempt to get a Broadcast variable’s actual value.</p><p>Given a Broadcast bc, here&#39;s where Spark will try to get your Broadcast value from, in order, when you call bc.value.</p><ol><li>Check this instance of bc for a memoized, previously-computed value (essentially a memory-sensitive lazy val)</li><li>Check this executor’s local Broadcast cache for bc</li><li>Check local BlockManager for either complete or partial transfer of bc</li><li>Fetch remote bytes of bc from executors running on the same node as this executor.</li><li>Fetch remote bytes of bc from other nodes, preferring if possible rack-local nodes first.</li></ol><p>In a diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*Nhf_u0wYLBwKA4Eb.png" /></figure><p>The BlockManager is used for most Spark operations, whereas the Broadcast cache is simply a per-executor Map that contains previously-fetched Broadcasts. The first successful bc.value will always end by caching bc, both as memoized in step #1 and in the Broadcast cache of step #2.**</p><p>The “torrent” part of this is actually implemented in a totally different class — TorrentBroadcast contains control flow logic, but it&#39;s the BlockManager class that contains the characteristic &quot;leech from nearest neighbors first&quot; torrent code. We examine it more closely here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*15LQwT_AFc2Gp2sf.png" /></figure><p>We see clearly from the last line that the returned Seq contains first preferredLocs (locations where this.host == that.host, i.e. same actual node), then rack-specific locations -- if topological information is available -- and finally all other locations.</p><h4>Broadcasts and Factories</h4><h4>TorrentBroadcast Code Architecture</h4><p>Let’s switch gears. We now understand the basics of torrenting, as well as how Spark implements it (tl;dr with lots of caching and otherwise how you might guess). But for software professionals, the implementation itself is only half the battle, if even that much. Setting up our code architecture such that it is maintainable and composable is an equally important and difficult battle.</p><p>Here’s where our more-academic topic of the day comes in to help us: the <strong>factory</strong> <strong>pattern</strong>.</p><p>To step incrementally into this, let’s first dig through the underlying Broadcast code. What do we find when we simply look at the code definitions underlying the basic sc.broadcast(...) call?</p><p>(Note in all this, I’m using IntelliJ IDEA to go to the definitions with Cmd+B.)</p><p>We start by peeking at that method…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*BfAvje1w3dz3Shsj.gif" /></figure><p>…and quickly find ourself in a BroadcastManager class with a newBroadcast method on it...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*r98hUvc1K4SvtrrC.gif" /></figure><p>…which in turn calls newBroadcast on a broadcastFactory field. That itself is an instance of the BroadcastFactory interface, which we quickly see has one implementation: TorrentBroadcastFactory. There, we finally find our actual culprit -- this newBroadcast implementation generates instances of TorrentBroadcast.</p><p>So — we’ve got a whole slew of classes behind this method! In brief:</p><ol><li>broadcast on SparkContext</li><li>A BroadcastManager class which uses the newBroadcast method to return a Broadcast variable.</li><li>A BroadcastFactory class which implements newBroadcast</li><li>The actual basic Broadcast generated by newBroadcast.</li></ol><p>And, as we see from above, #3 and #4 both are interfaces with their implementations pinned to the Torrent implementation.</p><p>This is a lot — and we see most of it involves factories, so our concept is in play. A few immediate questions come to mind that we’ll seek to answer in the next section.</p><ol><li>What is the factory pattern?</li><li>How is the Spark Broadcast code using the factory pattern?</li></ol><ul><li>Why so many classes?</li><li>Why only one implementation?</li><li>Does it have to be this way?</li></ul><h4>The Factory Pattern</h4><p>The Factory pattern was first popularized as part of the <a href="https://en.wikipedia.org/wiki/Design_Patterns">Gang of Four Design Patterns</a> — there are tons of resources on the topic that will do it better justice than I ever could, so we’ll stay focused on the details relevant to Spark’s Broadcast variables.</p><p><strong><em>Purpose</em></strong></p><p>According to <a href="https://en.wikipedia.org/wiki/Factory_method_pattern">Wikipedia</a>, the factory pattern:</p><blockquote>“…uses factory methods to deal with the problem of <a href="https://en.wikipedia.org/wiki/Object_creation">creating objects</a> without having to specify the exact <a href="https://en.wikipedia.org/wiki/Class_(computer_programming)">class</a> of the object that will be created.”</blockquote><p>Instead of the usual “maze game” / “database connection” / whatever example you’ll find on the internet, let’s try to ground this.</p><p>The Factory pattern involves three entities:</p><ol><li><strong>The Client</strong> — a larger component that uses the factory. The factory is just one small part of the client.</li><li><strong>The Factory</strong> — a smaller component used by the client to generate instances of the Thing.</li><li><strong>The Thing</strong> — the instance generated by the client.</li></ol><p>We deal with this kind of situation all the time as human beings. Here’s the first example that came into my head.</p><blockquote>“I bought a <a href="https://www.keurig.com/coffee-makers">Keurig machine</a>. I’ve bought a whole bunch of different K-Cups. I can’t wait to drink all this different coffee using my Keurig.”</blockquote><p>The Keurig is the client. It has lots of parts, but it needs a little coffee-generating factory to work correctly: the K-Cup itself. It doesn’t care which actual K-Cup you use — it leave that decision till later. The K-Cup is the factory. Your cup of coffee is the Thing.</p><p>Let’s look at an example of this by looking at how Spark does it.</p><h4>TorrentBroadcast &lt;/3 Factory Patterns</h4><p>Let’s match up the different entities defined above to the Broadcast code.</p><p><strong>What’s our Client?</strong> That’s our BroadcastManager. Per above, it does more than other components. It manages:</p><ul><li>Broadcast caching</li><li>Broadcast id monotonicity</li><li>Initialization, teardown</li><li>The choice of Factory to use</li><li>Generating Broadcasts from the chosen Factory</li></ul><p><strong>What’s our Factory? </strong>That’s the aptly-named BroadcastFactory! The Client above chooses which Factory to use, leaving this responsible for:</p><ul><li>Actually generating Broadcast instances</li><li>Unbroadcasting a Broadcast instance</li></ul><p><strong>And what’s our Thing?</strong> The Broadcast variable itself!</p><p>Great! We’ve set up our code to be SOLID and composable. Or have we?</p><p>The BroadcastManager chooses which Factory to use, right? Just like a Keurig using different K-Cups? This code in the Manager begs to differ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/0*0hMmZw9NSlxqTIJi.png" /></figure><p>Oh no! All this Factory-looking stuff just to be pinned to our only Factory implementation. Why go through the bother?</p><p>Let’s look back at history. Here’s the same BroadcastManager code in Spark 1.0.0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TOrFrnbSrXatZx14.png" /></figure><p>This code is our Client switch between Factories. In Spark 1.0.0, the Factory class was injected in via config and dynamically loaded at runtime! ALSO — there used to be an HttpBroadcastFactory -- indeed, it was the default!</p><p>But the HttpBroadcast code has been gone since Spark 2.0.0 -- its legacy in code architecture, however, lives on. Another phrase for this is technical debt.</p><p>So let’s now answer our original questions:</p><p>Why so many classes?</p><ul><li>The Factory pattern is verbose, and involves three entities. For Broadcasts, each of those entities corresponds to a separate component.</li><li>This class explosion is reduced with other patterns and ideas — methods instead of classes, or perhaps the abstract factory pattern instead!</li></ul><p>Why only one implementation?</p><ul><li>There used to be two!</li></ul><p>Does it have to be this way?</p><ul><li>Nope.</li></ul><h4>Conclusion</h4><p>Here’s what we’ve learned:</p><ol><li>Spark uses torrenting and LOTS of caching to facilitate Broadcast variables.</li><li>Spark originally used the Factory pattern to switch between different Broadcast implementations, but now we’ve got the pattern without the different implementations! That’s not great.</li></ol><p>** If you’re wondering what the difference between the caching of #1 and #2 are — the current implementation uses Java’s <a href="https://www.baeldung.com/java-soft-references">SoftReference</a> in step #1, and <a href="https://www.baeldung.com/java-weak-reference">WeakReference</a> for the cache of step #2. If you read <a href="https://stackoverflow.com/questions/299659/whats-the-difference-between-softreference-and-weakreference-in-java">here</a>, this seems a bit backwards to me, but that’s a whole separate analysis. It certainly seems redundant, though, and undesirable after a destroy call -- it won&#39;t cause an OOM if these References stick around per their definition, but they could certainly lead to memory pressure!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b5cdb23296c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>