<?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 Sebastian Nyberg on Medium]]></title>
        <description><![CDATA[Stories by Sebastian Nyberg on Medium]]></description>
        <link>https://medium.com/@seb-nyberg?source=rss-822c940ca374------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6f0Bg2sJY8NZLJ2kVr1-HA.jpeg</url>
            <title>Stories by Sebastian Nyberg on Medium</title>
            <link>https://medium.com/@seb-nyberg?source=rss-822c940ca374------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:29:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seb-nyberg/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[Length-Delimited Protobuf Streams]]></title>
            <link>https://seb-nyberg.medium.com/length-delimited-protobuf-streams-a39ebc4a4565?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/a39ebc4a4565</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[storage]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Sun, 31 May 2020 18:22:30 GMT</pubDate>
            <atom:updated>2021-03-24T09:29:10.839Z</atom:updated>
            <content:encoded><![CDATA[<p>Protobuf is a great encoding format. It’s become wildly popular as an encoding protocol, not only for gRPC messages, but for all kinds of information exchange.</p><p>When using Protobuf in a streaming situation — i.e. when writing to a file, or over a socket — the problem of delimiting one message from the next becomes apparent. Encoded Protobuf messages do not mark the end of each message, so it is not be possible to reliably distinguish one message from another when reading the stream on the other end.</p><p>While Protobuf has no official guidelines regarding this problem, there is a commonly used solution to the problem called length-delimiting (sometimes called prefixing / framing) messages.</p><p>This article will go through some basic properties of Protobuf, why large messages are difficult to work with, the length-delimited (length-prefixed) implementation, and finally some considerations when using this streaming format.</p><p>Let’s get started</p><h3>Protobuf Message Basics</h3><p>Consider a very simple Protobuf definition of a User:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be2a1f171dcce31a6e8e3ee6f83c6dcc/href">https://medium.com/media/be2a1f171dcce31a6e8e3ee6f83c6dcc/href</a></iframe><p>I put this in a file called simple.proto and generate the output with</p><pre>protoc --python_out=. simple.proto</pre><p>The process for writing a Protobuf message to a file is dead-simple. Create the message, serialize it to binary, and write it to the file. To read the message from file, open and parse (decode) the entire contents of the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1954d61a2bf0a48fb466977ad9e1449/href">https://medium.com/media/c1954d61a2bf0a48fb466977ad9e1449/href</a></iframe><h4>Multiple Messages in One File</h4><p>Writing multiple Protobuf messages to a file is no harder than writing one message. Simply repeat the write for each message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5382fc538a9be12e0b43119abd748bd/href">https://medium.com/media/c5382fc538a9be12e0b43119abd748bd/href</a></iframe><p>In order to parse one message from the file however, we need to know where the “Bob message” ends so that the encoded message can be read from the file and parsed individually.</p><p>There are typically two ways to predictably parse blocks from a stream — either each block is of fixed size, or blocks are delimited in some way.</p><p>For this reason, Avro has formed a specification called the Object Container File (OCF) format. In this format, a special sync-marker is placed in the file to delimit messages.</p><p>For Protobuf, we’ll have to find our own solution to the problem.</p><h4>Wrapper Messages &amp; Size Constraints</h4><p>A quick-n-dirty solution to the lack of built-in message delimiters is to wrap one message in another:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69e8b968b008c2804dffd74813f6b064/href">https://medium.com/media/69e8b968b008c2804dffd74813f6b064/href</a></iframe><p>There is however one big drawback to this: in order for Protobuf messages to be reliably decoded, the entire message must be decoded at once, i.e. <em>the entire message must fit in memory</em>. In some contexts, this is not a problem, in others, it may be catastrophic. While the wrapper message grows, the memory requirements can quickly become unwieldy.</p><p>The official recommendation is to keep Protobuf messages around 1MB in size. 64MB is the limit from Google, and the hard-limit is 2GB in total. <em>These limits and recommendations are there for a reason</em>. Having a message that is 64MB in size can require several GB of RAM to decode the message.</p><h3>Length-Delimited Protobuf</h3><p>Delimited streaming formats are used everywhere. In the case of textual formats, such as CSV, the delimiter is simply a newline character. For JSON, streaming can be achieved by using a specific line-delimited JSON format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/133f61d81492c86a47973c02832412d5/href">https://medium.com/media/133f61d81492c86a47973c02832412d5/href</a></iframe><p>Since Protobuf is a binary format, and due to the encoding specification itself, it is not possible to insert some kind of character or byte sequence that delimits each message.</p><p>It is however possible to instruct the reader how far it should read before decoding each message. This is called <em>length-delimiting</em> or <em>length-prefixing</em>, and is similar to how the header of an IP packet contains a header that contains the length of the data payload.</p><h4>Writing Length-Delimited Messages</h4><p>The process for writing length-delimited messages is is simple: serialize each message, calculate its length in bytes, and store the length in binary format. In this example I’ve picked a big-endian, unsigned 32-bit integer (&gt;L ). Finally, write both the length and the message to the stream:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb0938727d14abff4b6947bb9b4922c7/href">https://medium.com/media/cb0938727d14abff4b6947bb9b4922c7/href</a></iframe><p>The file content layout will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAMiGhqz_cRy_522K5aAKA.png" /></figure><h4>Reading Length-Delimited Messages</h4><p>In order to read a message, start by reading the first four bytes. Then parse those bytes to get the message length. Finally, read the length of bytes from the stream before decoding the message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf2e9bc0f0b2f452698a6690a618c2bc/href">https://medium.com/media/bf2e9bc0f0b2f452698a6690a618c2bc/href</a></iframe><p>Voilá, you’ve just written and read files one-by-one from a file. For most cloud providers, it is possible to perform this operation over the wire, i.e. each message can be streamed to and from the remote file in real-time. This is an extremely powerful property. Since we write both the length and message at the same time as well, we do not need to worry about incomplete writes.</p><h3>Considerations</h3><p>The advantages of using a streaming format are plenty:</p><ul><li>It is possible to stream individual messages over e.g. a Socket</li><li>New messages can be appended to existing files without parsing previous content.</li><li>It’s possible to count the number of messages in a file without decoding any of the messages</li><li>By reading only the length-prefixes, an index can be created that can be used to split the file into smaller batches without decoding any messages.</li></ul><p>However, it’s not all flowers and sunshine in Protobuf streaming land.</p><h4>Lack of a Standard</h4><p>This format <em>is design</em>. For example, the choice of a prefix varies between implementations, but is normally either a varint, uint32, or uint64.</p><p>In Java and C#, there are two functions that can be used ( parseDelimitedFrom and writeDelimitedTo ), but this <a href="https://github.com/protocolbuffers/protobuf/issues/4303">this compatibility issue</a> has been open since 2018.</p><p>In 2015,<a href="https://github.com/protocolbuffers/protobuf/pull/710"> a PR </a>was opened that aimed to merge the Java implementation into the core C++ library, but it was ultimately closed in 2017.</p><p>For Go, there is a delimited reader /writer implementation found in the Gogo Protobuf package called Uint32DelimitedReader and Uint32DelimitedWriter. I’ve used this implementation quite a bit and it’s worked well with the Python implementation this article.</p><p>In the <a href="https://docs.rs/protobuf/2.14.0/protobuf/fn.parse_length_delimited_from_reader.html">Rust protobuf package</a>, there is a delimited reader / writer, but it has been marked as deprecated. Possibly for the same reasons the C++ PR was closed.</p><p>I wrote a small library for Python available on Github <a href="https://github.com/sebnyberg/ldproto-py">https://github.com/sebnyberg/ldproto-py</a> that can be used as a reference for an implementation. The package is also available on Pip as ldproto in case someone wants to try it out.</p><p>All in all, the format has been a contentious issue throughout the years, but luckily it is not all that hard to just implement it yourself.</p><p>If you made it this far, thank you for reading this article, and good luck on your Protobuf streaming adventures!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a39ebc4a4565" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure S3 Storage Proxy with MinIO in AKS]]></title>
            <link>https://seb-nyberg.medium.com/azure-s3-storage-proxy-with-minio-in-aks-233dad87b800?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/233dad87b800</guid>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[minio]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Mon, 25 May 2020 16:54:44 GMT</pubDate>
            <atom:updated>2020-05-25T17:44:03.047Z</atom:updated>
            <content:encoded><![CDATA[<h3>MinIO S3 Storage Proxy in AKS</h3><p><em>Why give up all those S3 tools because you are using Azure?</em></p><p>The S3 API has become more or less a standard interface for cloud storage. Whether you’re using AWS, <a href="https://cloud.google.com/storage/docs/interoperability">GCP</a>, <a href="https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-compatibility-api">IBM Cloud</a>, <a href="https://www.digitalocean.com/docs/spaces/resources/s3-sdk-examples/">DigitalOcean</a>, well, pretty much any cloud provider except for Azure, storage is provided with a S3-compliant API.</p><p>For this reason, it is quite common that tools within the Open Source community does not support Azure Blob Storage. After all, these tools contain what is contributed to them, and most people are using S3-compliant storage.</p><p>While setting up Argo Workflows, I found out that it is possible to provide an S3 API for an Azure Blob Storage with MinIO’s Azure S3 Gateway. Yeah, you read it right: <em>it is possible to use Azure Blob Storage as if it were S3</em>.</p><p>This article will give a step-by-step example of how MinIO can be deployed to an AKS cluster and exposed via a public ingress. Halfway through this article, AWS CLI will be used to copy files to Blob Storage. Bear in mind that the article is quite opinionated and should serve as an example rather than a reference.</p><h4>Introduction &amp; Terminology</h4><p><a href="https://min.io/">MinIO</a> is a “High Performance, Kubernetes Native Object Storage”. For this article, the focus will be on the S3 Gateway Feature and the AKS deployment. However, MinIO has lots of other features, and can also be deployed via the Azure Marketplace. Please check out the MinIO website for more information.</p><p>Before we get started, let’s go through some terminology for mapping the S3 API to Azure Storage:</p><ul><li>Storage Account Name → Access Key</li><li>Storage Account Key → Secret Key</li><li>Storage Account → <em>Kinda an AWS Account</em></li><li>Storage Container → Bucket</li></ul><p>The storage account will have an S3 URL in the following format: s3://$CONTAINER/path/to/blob . The Endpoint URL to the S3 storage will be the DNS of the MinIO installation.</p><h4>Placeholders in this guide</h4><p>For the purpose of demonstration, I’ll call my AKS cluster mycluster and the Azure Storage Account miniostorage.</p><p>I’ll use the admin context retrieved from az aks get-credentials … --admin when deploying resources, i.e. mycluster-admin.</p><p>Please ensure that you update these placeholders as necessary.</p><h3>Basic MinIO Setup</h3><p>I will be using the <a href="https://github.com/helm/charts/tree/master/stable/minio">stable/minio Helm Chart</a>.</p><p>It is best practice to put deployed manifests in version control, including Helm values. This allows for reproducibility and serves as a reference for future, forgetful you.</p><p>For third-party installations, <a href="https://github.com/roboll/helmfile">helmfile</a> is my go-to tool, and will be used in this article. To use Helm directly, copy the values section from each helmfile and provide missing secrets via --set , or encrypt the values file with e.g. SOPS or helm-secrets-plugin.</p><p>If you are new to helmfile, it might be helpful to look at <a href="https://github.com/cloudposse/helmfiles/tree/master/releases/">CloudPosse’s repository of helmfiles</a>. It has certainly served me well.</p><h4>Deploying with Helmfile</h4><p>Below is a basic Helmfile installation that deploys the MinIO helm chart into the minio namespace with a release name of miniotest. I’ve pinned the version to 5.0.26 in this example to ensure that it will run. For a production setup however, it is recommended to let patches go through, i.e. with semver ~v5.0 .</p><p>To get started, create the minio namespace:</p><pre>kubectl \<br>  --context mycluster-admin \<br>  create ns minio</pre><p>Then create the helmfile for the basic setup, let’s call it minio.yaml :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/208fc16f99a9f0989d356f19fca85dbf/href">https://medium.com/media/208fc16f99a9f0989d356f19fca85dbf/href</a></iframe><p>This helmfile showcases the requiredEnv template directive, which marks AZURE_STORAGE_KEY as required, as is seen in this error:</p><pre>$ helmfile --file minio.yaml apply<br>in ./minio.yaml: error during minio.yaml.part.0 parsing: template: stringTemplate:12:18: executing &quot;stringTemplate&quot; at &lt;requiredEnv &quot;AZURE_STORAGE_KEY&quot;&gt;: error calling requiredEnv: required env var `AZURE_STORAGE_KEY` is not set</pre><p>Let’s retrieve AZURE_STORAGE_KEY using Azure CLI:</p><pre># test that key is available<br>az storage account keys list -n miniostorage -o table</pre><pre># set storage key<br>export AZURE_STORAGE_KEY=$(<em>az storage account keys list</em> -n miniostorage --query &#39;[0].value&#39; -o tsv)</pre><p>Then, run helmfile again</p><pre>helmfile --file minio.yaml apply</pre><p>This will install a bunch of resources in your cluster inside the minio namespace. It may take several minutes for the installation to finish so please be patient. Once done, helm will print instructions in the terminal on how to get started. I would suggest trying out these instructions and putting the output somewhere safe for future reference. For example, I will not show how to use the MinIO client ( mc ) in this article.</p><h4>Accessing the MinIO UI</h4><p>Once the installation has finished, open a port-forward to the UI on <a href="http://localhost:9000/">localhost:9000</a> :</p><pre>kubectl \<br>  --context mycluster-admin \<br>  --namespace minio \<br>  port-forward svc/miniotest 9000</pre><p>The website will ask you to log in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpPYVfMwdSbSHvg9UeeeeA.png" /></figure><p>Provide the Storage Account Name as the Access Key, and the Storage Account Key as the Secret Key.</p><p>Once logged in, the default bucket (aptly named default ) that was provided in the Helm values has been created for us. This bucket is actually a container under the hood. The UI can be used to view buckets, their contents, manage policies, and upload files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8U9wdjtF-wSpan1d24bDNQ.png" /><figcaption>MinIO UI while logged in</figcaption></figure><p>Let’s put the S3 API to the test by accessing the Azure Storage Account via AWS CLI.</p><h4>Putting a file into Azure Blob Storage using AWS CLI</h4><p>To access the Storage Account, provide the storage account name as the AWS_ACCESS_KEY_ID and the storage account key as the AWS_SECRET_ACCESS_KEY .</p><p>Bring up the port-forward again if it was shut it down before:</p><pre>kubectl \<br>  --context mycluster-admin \<br>  --namespace minio \<br>  port-forward svc/miniotest 9000</pre><p>Open a new terminal. Set the storage account and key (verify output as well).</p><pre>export AZURE_STORAGE_ACCOUNT=miniostorage<br>export AZURE_STORAGE_KEY=$(az storage account keys list -n ${AZURE_STORAGE_ACCOUNT} --query &#39;[0].value&#39; -o tsv)</pre><pre>echo $AZURE_STORAGE_KEY</pre><p>You may now list the “buckets” (actually, <em>containers</em>) in the storage account by passing localhost as the endpoint to AWS CLI:</p><pre>aws --endpoint-url <a href="http://$endpoint_url/">http:/</a>/localhost:9000 s3 ls</pre><p>Let’s create a temporary test file and put it in the default “bucket”</p><pre>tmpfile=$(mktemp)</pre><pre>echo &quot;test&quot; &gt; $tmpfile</pre><pre>aws --endpoint-url <a href="http://localhost:9000/">http://localhost:9000</a> s3 cp $tmpfile s3://default/test.txt</pre><p>The output can be seen in Storage Explorer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVYUPkjo5Eejm2K_TYvOCA.png" /><figcaption>First uploaded file to Azure Storage via the S3 API</figcaption></figure><h4>Cleaning up resources</h4><p>Remember to clean up the port-forward either by exiting the terminal, or resuming the job with fg and ctrl+c .</p><p>To clean up the installed resources, use helmfile destroy or helm del :</p><pre>helmfile --file minio.yaml destroy</pre><pre># or<br>helm \<br>  --context mycluster-admin \<br>  --namespace minio \<br>  delete miniotest</pre><h3>Production Setup w/ Public Ingress</h3><p><em>Pretty much all guides I see on Medium completely omit this section, and it makes sense. There are many ways to set up a public ingress, and also many things that can go wrong. While getting started with Kubernetes, I remember this being a big pain-point, so I decided to add this section anyway. I hope it helps you in setting up the ingress — the same approach can be used for any other DNS in need of TLS termination.</em></p><p>By default, the deployment does not expose any public endpoints.</p><p>Patching the service type to LoadBalancer will expose a public IP that can be used to access the S3 API. However, traffic will remain unencrypted. There primarily are two approaches to provide encryption: either supply the TLS certificate to the installation yourself, or use cert-manager to automatically generate the certificate for you.</p><p>Personally, I prefer not to manage certificates myself, so I tap into a working cert-manager + nginx setup. I then add an A-name record to the DNS that points to the Public IP used by the nginx service’s LoadBalancer so that let’s encrypt can issue the ACME challenge, giving the Kubernetes ingress a certificate.</p><p>If what I just wrote makes perfect sense to you, and you already know how to do it, skip until the section called “<strong>Deploying the MinIO service with an ingress”</strong></p><h4>cert-manager + NGINX</h4><p><em>Normally, I would not write a guide for this since it is very error-prone and beyond the scope of this article. However, when getting started with Kubernetes, I recall having issues finding end-to-end examples of exposing a public ingress such as this one, so I decided to put it here anyway.</em></p><p>Setting up cert-manager (Let’s Encrypt) and NGINX can be a struggle. I recommend following the <a href="https://docs.microsoft.com/en-us/azure/aks/ingress-tls">Azure Guide</a> to get started. If you get stuck, below is the helmfile I typically use to deploy NGINX / Let’s Encrypt to new AKS clusters (note that I use the namespace nginx instead of nginx-ingress ):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/023a654eb815716f5754f1d72b432667/href">https://medium.com/media/023a654eb815716f5754f1d72b432667/href</a></iframe><h4>Finding the Azure Public IP for the nginx service</h4><p>Once nginx is up and running, its reverse proxy will be exposed through a service of type LoadBalancer. This service maps to an Azure Public IP inside the Azure Environment. To find the IP, get services in the nginx namespace and make note of the EXTERNAL-IP:</p><pre>kubectl \<br>  --context mycluster-admin \<br>  --namespace nginx \<br>  get service </pre><p>Once you know the EXTERNAL-IP of the service, it is a matter of track down the corresponding Azure Public IP. I typically grep for the public IP via Azure CLI — the first column will be the name of the Azure Public IP</p><pre>az network public-ip list -o table | grep 123.456.789.012</pre><h4><strong>Pointing a DNS to the Public IP</strong></h4><p>The next step is to get a hold of a DNS that can point to the public IP address.</p><p>A quick and simple solution to get a verifiably owned DNS is to add a DNS name label to the Public IP resource. This will grant you a Fully Qualified Domain Name (FQDN) that can be used as a hostname in the MinIO ingress later on. I have used this approach for testing purposes sometimes when there is only one ingress in the cluster that I want to expose to the outside world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Th-aPrEi486L2KRqpE_cqA.png" /><figcaption>Creating a FQDN for a Public IP used by Kubernetes</figcaption></figure><p>If you already own a domain name on some other registrar, it is fairly simple to create a new A-record there that points towards the Azure Public IP and be done with it. I typically create new subdomains for different tools, e.g. artifacts.argo.my.company.com .</p><p>If you control a domain name and would like to manage it in Azure, follow <a href="https://docs.microsoft.com/en-us/azure/dns/dns-delegate-domain-azure-dns">this guide</a> to delegate control to Azure DNS Zone. The advantage of doing so is that the A-Name record can be of type “alias record”, which allows attachment to the Public IP resource itself, instead of the IP address of the resource.</p><h4>Deploying the MinIO service with an ingress</h4><p>Once your domain name (e.g. miniostorage.my.domain.com ) is pointing towards the nginx ingress service, a Kubernetes ingress with the same hostname can be set up for the MinIO installation. Below is an example helmfile:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5c83aae4cc5e17eebacc4a553232e1e/href">https://medium.com/media/e5c83aae4cc5e17eebacc4a553232e1e/href</a></iframe><p>Once again apply the file:</p><pre>helmfile --file minio-with-ingress.yaml apply</pre><p>This will deploy a Kubernetes ingress object. If your cert-manager setup is working, cert resources will show up in the minio namespace:</p><pre>kubectl \<br>  --context mycluster-admin \<br>  --namespace minio \<br>  get certificates,challenges,csr</pre><p>To debug problems, check kubectl get events and logs from the nginx ingress controller. If the DNS does not work, try accessing the service directly via the Public IP. This will show an Invalid Request error once entering the website, but at least you know the ingress is correctly managed by the nginx ingress.</p><p>There is one important detail in the deployment manifestabove: nginx does not support uploading of large files by default and will send a 413 - Payload Too Large. It is however possible to remove this limit as an annotation in the ingress object definition.</p><pre>nginx.ingress.kubernetes.io/proxy-body-size: &quot;0&quot;</pre><p>Now that all is said and done, the Azure Storage Account is available via a public URL, encrypted with TLS, and accessible as an S3 API.</p><h3>Conclusion</h3><p>MinIO has opened up the door for us Azure developers to use a large set of previously inaccessible tools that rely on S3 as the storage backend.</p><p>I really want to stress that MinIO is much more than what’s contained in this article, and that you should check out their <a href="https://docs.min.io/docs/minio-quickstart-guide.html">docs</a> for more info. For example, I highly recommend trying the MinIO client.</p><p>Thank you for reading this article, and make sure to subscribe for more content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=233dad87b800" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing Protobuf JSON Serialization in Golang]]></title>
            <link>https://seb-nyberg.medium.com/customizing-protobuf-json-serialization-in-golang-6c58b5890356?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c58b5890356</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Thu, 27 Feb 2020 10:01:47 GMT</pubDate>
            <atom:updated>2021-03-05T21:57:01.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>Customizing Protobuf JSON Serialization in Go</h3><p><em>A primer on customizing Protobuf to JSON serialization in Golang</em></p><p>A new version of Protobuf was released in March 2020, See <a href="https://blog.golang.org/protobuf-apiv2">this post</a> for more info. Please ensure that you have <a href="https://developers.google.com/protocol-buffers/docs/reference/go-generated">the latest version</a> of the protoc-gen-go plugin, or this article may diff from what you see locally.</p><p>Let’s start with a toy example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/708db51a0626bb23c73e3c42c36f323e/href">https://medium.com/media/708db51a0626bb23c73e3c42c36f323e/href</a></iframe><p>Generate the code:</p><pre>protoc --go_out=. todo.proto</pre><p>Output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/480024dda8a4637a43bcf6c89d817ac6/href">https://medium.com/media/480024dda8a4637a43bcf6c89d817ac6/href</a></iframe><p>Create and serialize an example Todo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c63088bdf4dc953262db750e56206da/href">https://medium.com/media/4c63088bdf4dc953262db750e56206da/href</a></iframe><p>JSON output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e990f58bd79dd491dc3a6011ae8e3a/href">https://medium.com/media/d4e990f58bd79dd491dc3a6011ae8e3a/href</a></iframe><p>There are two obvious problems with this: the enum is serialized as an int, and the timestamp is serialized as.. a struct of seconds and nanos?</p><h4>protocolbuffers/protobuf-go/encoding/protojson</h4><p>The Golang JSON serializer doesn’t deal well with Protobuf. Instead, you should use protojson:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00253e5a69d13ef02d43f03ec51f696e/href">https://medium.com/media/00253e5a69d13ef02d43f03ec51f696e/href</a></iframe><p>The output is now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bccfc711dee153ef3ed8b02fc5ede385/href">https://medium.com/media/bccfc711dee153ef3ed8b02fc5ede385/href</a></iframe><p>The timestamp is now in RFC3339 format, and the fields are camelCased.</p><h4>protojson Marshaler Options</h4><p>Let’s look at the protojson.Marshal function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91ad908e31df1e3ee04c983eafce5698/href">https://medium.com/media/91ad908e31df1e3ee04c983eafce5698/href</a></iframe><p>As you can see, proto.Marshal is just a convenience function which initializes MarshalOptions with default settings.</p><p>MarshalOptions has a <a href="https://pkg.go.dev/google.golang.org/protobuf@v1.25.0/encoding/protojson#MarshalOptions">number of dials</a>:</p><ul><li>Multiline and Indent — print the message on multiple lines, using the provided indent.</li><li>UseProtoNames —Effectively makes the JSON keys snake_cased instead of camelCased.</li><li>EmitUnpopulated — Explicitly include unpopulated values in the output (see next section)</li><li>UseEnumNumbers — print enums as ints instead of their .String() representations. This is what the regular JSON marshaler gave us earlier.</li></ul><h4><strong>MarshalOptions.EmitUnpopulated</strong></h4><p>EmitUnpopulated can be set to include default values in the response. This is very helpful when default values carry meaning and I would advice to let consumers manage default values rather than the API omitting them.</p><p>Let’s say we want to keep track of how many times users have viewed a todo. We add a new view_count field to the Protobuf definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79fe2b8a0fddfc0e4e798aa98b2a255d/href">https://medium.com/media/79fe2b8a0fddfc0e4e798aa98b2a255d/href</a></iframe><p>If ViewCount is unset or set to zero, then the resulting JSON will be just as before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a720533d2833a99b30402a2622c3ac9e/href">https://medium.com/media/a720533d2833a99b30402a2622c3ac9e/href</a></iframe><p>In this case, it would make sense to include that view count is zero.</p><p>To remedy this issue, set EmitUnpopulated and try again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f413c2f8104ad70230c5df14828e1880/href">https://medium.com/media/f413c2f8104ad70230c5df14828e1880/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47827e4ec0e0f2cdc72c262f10f15619/href">https://medium.com/media/47827e4ec0e0f2cdc72c262f10f15619/href</a></iframe><h4>MarshalOptions.UseProtoNames</h4><p>UseProtoNames changes the output to use the Proto names, which are snake_cased:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a261b170556a367a159c390e0b70c61/href">https://medium.com/media/9a261b170556a367a159c390e0b70c61/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48eedbbb388c372c091c4bf3b02b8f67/href">https://medium.com/media/48eedbbb388c372c091c4bf3b02b8f67/href</a></iframe><h4>MarshalOptions.Resolver</h4><p>Implementing the resolver interface is an advanced topic that is used to manage resolution of objects that are of type google.protobuf.Any</p><p>That’s it folks, thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c58b5890356" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubectl Absolute Basics on Linux]]></title>
            <link>https://seb-nyberg.medium.com/kubectl-absolute-basics-on-linux-86304131f6b0?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/86304131f6b0</guid>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Wed, 16 Oct 2019 20:07:28 GMT</pubDate>
            <atom:updated>2020-05-15T08:38:59.365Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubectl Absolute Basics</h3><p><em>If you are already using Kubectl, this article is not for you. I wrote this as an on-boarding material for new employees. The aim of the article is to provide the minimum necessary instructions on how to inspect and debug running applications.</em></p><h3>The Kubeconfig</h3><p>After retrieving redentials to a Kubernetes cluster, e.g. on GCP, Azure or AWS, a “context” is created and merged it into your Kubeconfig. The kubeconfig is a yaml file that is normally stored in your home folder at ${HOME}/.kube/config. Although it may be interesting to look at the file directly, modifications to the config will normally happen using kubectl config commands.</p><p>To view the contexts listed in the kubectl file, run:</p><pre>kubectl config get-contexts</pre><p>Chances are that your namespace is set to ‘default’ or completely unset. To make changes to the context, such as changing the default namespace, use the kubectl config set-context command. For example, to set the default namespace to seb, I would run:</p><pre>kubectl config set-context --current --namespace=seb</pre><h3>Listing resources</h3><p>There are a ton of different resources in Kubernetes. The most simple way to list resources is to just use kubectl get:</p><pre>kubectl get pods<br>kubectl get services<br>kubectl get deployments</pre><p>The three commands above can all be run in one command by comma-separating the resources:</p><pre>kubectl get pods,services,deployments</pre><p>To list all resources in your namespace, you can run:</p><pre>kubectl get all</pre><p>All kubectl commands implicitly use the namespace set in your config, to view resources from another namespace, add the --namespace flag:</p><pre>kubectl get all --namespace kube-system</pre><p>To view a certain resource in all namespaces, use the --all-namespaces flag:</p><pre>kubectl get services --all-namespaces</pre><p>Some Kubernetes resources have shorthands. For example, kubectl get services can be replaced with kubectl get svc. To list these shorthands, run</p><pre>kubectl api-resources</pre><p>Kubectl has a built-in --watch flag. It will show any changes to the state of the output as a new row in the output. I personally prefer the Unix watch since it will replace the rows in-place instead of print new lines in my terminal:</p><pre># run kubectl get pods every 0.2s<br>watch -n 0.2 kubectl get pods</pre><h4>Listing by labels</h4><p>If your pod has labels, you can list these labels with the --show-labels flag. Be sure to have a wide screen:</p><pre>kubectl get pods --show-labels</pre><p>These labels can be used to filter resources. To only show pods with the label tier=frontend, we pass this filter to the -l flag:</p><pre>kubectl get pods -l &quot;tier=frontend&quot;</pre><p>If you only care about the existence of a label, just pass in the label name:</p><pre>kubectl get pods -l &quot;tier&quot;</pre><h3>Inspecting resources</h3><p>Listing using get is cool and all, but often you want more details. For this you can use the describe command:</p><pre>kubectl describe service orders-api</pre><p>For pods and services, view logs with:</p><pre>kubectl logs my-pod-name</pre><p>If you have multiple pods running behind a service, running the log command on the service will show logs from all pods that match the service route (matchLabels).</p><p>To follow the log, add the -f flag:</p><pre>kubectl logs -f svc/my-service</pre><h4>Running a shell inside a running Pod</h4><p>If the Docker image being run by your Pod has some shell installed, you can run a shell inside the running pod to inspect state. For example, to run bash on a pod called my-pod, run:</p><pre>kubectl exec -it my-pod bash</pre><p>Note that since the exec command only can be run on pods, there is no need to specify the resource type.</p><h4>Running ad-hoc Pods</h4><p>You may also run pods directly in the cluster using kubectl run. For example, to run a pod called mycurlrun that is interactive, and that will be cleaned up when you are finished, run:</p><pre>kubectl run -it --rm --image=pstauffer/curl mycurlrun</pre><p>Note: I highly suggest to avoid running pods like this. There is a great tool called Telepresence which allows you to run a local shell that can interact with resources internal to Kubernetes. By running</p><pre>telepresence --run bash</pre><p>You will achieve the above result while keeping all the tools on your local machine available to you. I have written a more <a href="https://medium.com/swlh/local-development-with-telepresence-256911cb21e9">in-depth article</a> on Telepresence that you may bookmark for further reading once Kubernetes is more familiar to you.</p><h3>Starting, restarting and stopping pods</h3><p>Unlike Docker containers, you don’t start, restart or stop pods in Kubernetes. If you wish to reboot a pod that is part of a deployment, delete it with:</p><pre>kubectl delete pod my-pod</pre><p>And the pod will automatically be re-created.</p><h3>What next?</h3><p>There are tons of great resources on Kubernetes. I highly recommend bookmarking the <a href="https://kubernetes.io/docs/reference/kubectl/cheatsheet/">Kubectl Cheat Sheet</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86304131f6b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local Development with Telepresence]]></title>
            <link>https://medium.com/swlh/local-development-with-telepresence-256911cb21e9?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/256911cb21e9</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[telepresence]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 08:19:43 GMT</pubDate>
            <atom:updated>2019-10-16T14:28:46.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simplifying Local Development in Kubernetes with Telepresence</h3><p><a href="https://www.telepresence.io/">Telepresence</a> is a versatile CNCF sandbox project that aims to provide “Fast, local development for Kubernetes and OpenShift microservice.”</p><p>I personally believe that Telepresence is more than that — it simplifies configuration management for local development, allowing developers to work as though the application was running in the remote environment.</p><p>This article contains two sections: an introduction to the Telepresence shell and swapping remote deployments. The goal is to, from a functional standpoint, outline when you would use the Telepresence shell and how it can be used to bridge the gap between remote and local development configuration.</p><h3>Making use of the Telepresence shell</h3><blockquote>You just joined a team working on a shopping website. There are three non-public services running in Kubernetes that you want to use: Orders, Products and Users. Since the services are only available inside the cluster, you open three kubectl port-forwards to make the services accessible for local development.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*9leSUd7FNMM_b7Bada1gng.png" /></figure><p>The first and most obvious problem with the setup above is the maintenance of the tunnels. Depending on Node configuration, the connection will time out and close if it’s not actively being used (on AKS, timeout happens after 5 minutes).</p><p>A more serious problem is that of environment configuration drift — you now have a <em>local </em>configuration and a <em>remote</em> configuration. The remote configuration will use the DNS of the services, and the local configuration will use the localhost URLs.</p><p>With Telepresence, there is no need to make this local/remote distinction.</p><h4>Starting a shell</h4><p>To start a new Telepresence shell, run:</p><pre>telepresence [--run-shell]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*9yhKiSgpJ9KHXQoguhN1mg.png" /></figure><p>And… it seems like nothing happened! The first time I ran Telepresence, this really threw me off — I didn’t really know what was going on.</p><p>Under the surface, there is now a proxy running inside the cluster that makes the local shell act as if it was a Pod inside the Kubernetes cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*3TTH9FuTlLn3_Fb88yAamg.png" /></figure><p>By running printenv in the local shell, you will notice environment variables such as KUBERNETES_SERVICE_HOST that are normally injected into Kubernetes pods.</p><p>To check the new deployment and pod that was created by Telepresence, run:</p><pre>kubectl get all -l &quot;telepresence&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*aFxedDggjQoXqUbu_3lOog.png" /></figure><p>The pod that proxies the environment runs with the Docker image datawire/telepresence-k8s . This deployment will be cleaned up as soon as you exit the Telepresence shell.</p><p>Going back to the shopping example, there would no longer be a need to use these localhost addresses:</p><pre>ORDERS_SERVICE_URL=localhost:10001<br>PRODUCTS_SERVICE_URL=localhost:10002<br>USERS_SERVICE_URL=localhost:10003</pre><p>Instead they could be the same as you’d expect in the Kubernetes environment:</p><pre>ORDERS_SERVICE_URL=orders.default.svc<br>PRODUCTS_SERVICE_URL=products.default.svc<br>USERS_SERVICE_URL=users.default.svc</pre><p><em>Note: there are some limitations to using </em><em>--method vpn-tcp (default proxy method). For more info, </em><a href="https://www.telepresence.io/reference/methods"><em>visit the docs</em></a><em>.</em></p><h4>Running the shell inside a Docker container</h4><p>At some point before the first deployment, you’ll want to test the Docker image of your application. Just like running telepresence --run-shell starts a new shell, using --docker-run will give you a local Docker container which has its environment proxied into the Kubernetes cluster:</p><pre>docker build . -t shopweb</pre><pre>telepresence --docker-run --rm -it \<br>  -p 3000:3000 \<br>  -v $(pwd):/path/to/workdir \<br>  shoppingweb \<br>  bash</pre><p>Note how there is no need to push the image to a remote registry. As long as the local Telepresence container starts successfully, you’ll be able to try out the image as if it was in the cluster.</p><p>Running a container changes the proxy method from vpn-tcp to container .</p><h4>Testing things in your cluster</h4><p>With Telepresence in your toolbelt, there is no need to run commands such as this one:</p><pre>kubectl run -it --rm --restart=Never --image=pstauffer/curl test</pre><p>Instead, you may just as well start a new Telepresence shell and enjoy the availability of all the tools you have on your local machine:</p><pre>telepresence --run bash</pre><p><strong>You can also run Postman to query your services directly using their internal domain names:</strong></p><pre>telepresence --run postman<br># on MacOS<br>telepresence --run open /Applications/Postman.app</pre><h3>Swapping Deployments</h3><blockquote>The shopping application has now grown and now consists of three components: the web client responsible for serving web pages, a GraphQL API acting as the interface against the back-end services, and a Redis session store.</blockquote><blockquote>To manage deployment and configuration of the application, releases are now done via Helm. The Helm chart manages configuration relating to connectivity between services within the chart.</blockquote><blockquote>For example, when Alice installs a Helm release with the name alice-shopweb , then its Redis store will, by convention, be given the name alice-shopweb-redis . The Redis hostname is put in the env section of both the Web and GraphQL pod specifications.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*TsuuDSgDMwGS33hs7hKylg.png" /></figure><p>Let’s consider local development with the setup above. A traditional approach would be to run Docker Compose on the host network, containing the GraphQL Server, Web Server and Redis Cache. Then, either the dependencies towards back-end services would be mocked, or the containers would use the host network to gain access to port-forwards into Kubernetes.</p><p>The local development situation with Docker Compose would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54ojecblt9K7EA2lLC2uzg.png" /></figure><p>Whenever configuration changes occur, both the Docker Compose configuration and values file used by Helm would need to be updated. Also, any host names would be different depending on if the application was running in Kubernetes or locally.</p><p>This is where the the feature of <em>deployment swapping</em> comes into play.</p><p>Telepresence has the ability to temporarily replace a remote deployment with a local shell, container or process, inheriting the environment of the remote deployment.</p><p>For example, assuming that the Web Server deployment is called shopweb , and its pods running on port 3000, we can swap the remote deployment with:</p><pre>telepresence --swap-deployment shopweb \<br>  --expose 3000 \<br>  --run bash</pre><p>The system now looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*pU5XICGlfIRCyz_tO4RGDw.png" /></figure><p>Hitting the web service now actually hits your local Telepresence shell. This means that anything you run locally will be available to whoever uses the service in the cluster. If the service is public, then you’re currently serving whoever hits the ingress- from your local machine.</p><h4>Deployment swapping under the hood</h4><p>Inside Kubernetes, the the Web setup now looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*ceyHmoGefCl-EuWleiZFQw.png" /></figure><p>In essence, Telepresence copied the existing deployment, replaced the image with datawire/telepresence-k8s and set the number of replicas for the existing deployment to be 0. The Telepresence shell then awaits an exit signal to clean up the deployment and restore the replicas in the original deployment.</p><h4>Replacing the deployment with Docker Container</h4><p>Just as in the previous section, you may replace the --run flag with a --docker-run and pass in any arguments you’d normally pass to docker run . Just be aware that you will no longer use vpn-tcp , but rather the proxy method container, which naturally incurs some overhead. You can read more about proxying methods <a href="https://www.telepresence.io/reference/methods">here</a>.</p><h4>Updating the environment</h4><p>Because developer can inherit the remote environment of the deployment and make small adjustments when running local development, you should aim to get a deployment into Kubernetes as fast as possible. The deployment will then become the source of truth for the environment — both local and remote.</p><p><strong><em>In order to make permanent changes to the local environment, the developer actually changes the remote configuration of the deployment.</em></strong></p><p>For example, if there is a need to access credentials for a service, the DevOps engineer can put those credentials into the deployment configuration itself and <em>voilà</em>: the developer now has access to the service.</p><h3>Conclusion</h3><p>In this article you’ve seen from a high level how Telepresence can be used to run local development as if you were inside Kubernetes — reducing the need to configure the local environment and service connectivity setup. If you are interested in knowing more, I highly recommend checking out the Telepresence <a href="https://www.telepresence.io/discussion/overview">documentation</a>.</p><p>A huge thanks to the <a href="https://www.datawire.io/">Datawire</a> for the initial development of Telepresence, and to all the great contributors working on the project! It truly is an amazing tool.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=256911cb21e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/local-development-with-telepresence-256911cb21e9">Local Development with Telepresence</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Validation Errors in Go Gin]]></title>
            <link>https://seb-nyberg.medium.com/better-validation-errors-in-go-gin-88f983564a3d?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/88f983564a3d</guid>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 07:44:29 GMT</pubDate>
            <atom:updated>2020-06-04T15:50:54.303Z</atom:updated>
            <content:encoded><![CDATA[<p>Out-of-the-box errors provided by the validation library used by Go Gin aren’t that great.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfe4f4cbe99958dd4154b35644b636a7/href">https://medium.com/media/cfe4f4cbe99958dd4154b35644b636a7/href</a></iframe><p>Running the server</p><pre>go run main.go</pre><p>And sending a request yields us:</p><pre>$ curl localhost:8080/car<br>&quot;Key: &#39;Name&#39; Error:Field validation for &#39;Name&#39; failed on the &#39;required&#39; tag&quot;</pre><h4>Retrieving errors from Validator</h4><p>Gin uses the <a href="https://github.com/go-playground/validator">go-playground/validator</a> under the hood. When ShouldBind fails, the error returned is actually a map[string]validator.FieldError which maps the field name to its error.</p><pre>if err := c.ShouldBind(&amp;query); err != nil {<br>  for _, fieldErr := range err.(validator.ValidationErrors) {<br>    c.JSON(http.StatusBadRequest, fieldErr)<br>    return // exit on first error<br>  }<br>}</pre><h4>Porting from validator.v8 to v9</h4><p>If you just formatted your main.go file, you’ll notice the new import validator.v8 . This is (as of writing) the default validator for Gin. The latest version of validator however is v9 . To upgrade to v9, you need to create your own validator and assign it tobinding.validator . By following <a href="https://github.com/go-playground/validator/blob/v9/_examples/gin-upgrading-overriding/v8_to_v9.go">the upgrade guide</a>, you should end up with something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1444cf326520b9a944fca0b437d395e9/href">https://medium.com/media/1444cf326520b9a944fca0b437d395e9/href</a></iframe><p>Note: now with v9, the FieldError struct has turned into an interface, which means we need to pass the error to fmt.Sprint to get some output (don’t worry, it’s just temporary).</p><pre>c.JSON(http.StatusBadRequest, fmt.Sprint(fieldErr))</pre><p>Running</p><pre>go run main.go v8_to_v9.go</pre><p>And sending a request once again to localhost:8080/car yields once again:</p><pre>$ curl localhost:8080/car<br>&quot;Key: &#39;Name&#39; Error:Field validation for &#39;Name&#39; failed on the &#39;required&#39; tag&quot;</pre><h4>Composing the validation message</h4><p>The validator.FieldError interface contains a number of functions that can be used to compose an error message, you can see them all <a href="https://godoc.org/gopkg.in/go-playground/validator.v9#FieldError">here</a>.</p><p>By wrapping the validator.FieldError in our own fieldError struct, we can implement the Stringer interface and get our own, custom validation message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ae3ad608b7f3d99f3e4207130dbe355/href">https://medium.com/media/9ae3ad608b7f3d99f3e4207130dbe355/href</a></iframe><p>By initializing a fieldError with a validator.FieldError , we can now get some decent output from ShouldBind:</p><pre>c.JSON(http.StatusBadRequest, fieldError{fieldErr}.String())</pre><p>Start the server and try once again:</p><pre>go run main.go v8_to_v9.go fielderr.go</pre><p>Output is now:</p><pre>$ curl localhost:8080/car<br>&quot;validation failed on field Name, condition: required&quot;</pre><h4>Using the form tags as field names</h4><p>As you could see in the error above, the Struct field name is used in the error message (returned by fieldErr.Field() ). To instead print the form tag name (e.g. form:”name&quot; ) we can add validator.RegisterTagNameFunc() to the lazyinit function that was added as part of the v8 -&gt; v9 transition:</p><pre>func (v *defaultValidator) lazyinit() {<br>  v.once.Do(func() {<br>    v.validate = validator.New()<br>    v.validate.SetTagName(&quot;binding&quot;)</pre><pre>    // Print JSON name on validator.FieldError.Field()<br>    v.validate.RegisterTagNameFunc(func(fld reflect.StructField) string {<br>      name := strings.SplitN(fld.Tag.Get(&quot;form&quot;), &quot;,&quot;, 2)[0]</pre><pre>      return name<br>    })<br>  })<br>}</pre><p>Now, both the string in the map[string]validator.FieldError , and the validator.FieldError.Field() function returns the JSON name from the tag, resulting in:</p><pre>$ curl localhost:8080/car<br>&quot;validation failed on field &#39;name&#39;, condition: required&quot;</pre><pre>$ curl localhost:8080/car?name=volvo<br>&quot;validation failed on field &#39;color&#39;, condition: required&quot;</pre><pre>$ curl &#39;localhost:8080/car?name=volvo&amp;color=red&#39;<br>&quot;validation failed on field &#39;color&#39;, condition: oneof { blue yellow }, actual: red&quot;</pre><pre>$ curl &#39;localhost:8080/car?name=volvo&amp;color=blue&#39;<br>{&quot;status&quot;:&quot;ok&quot;}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88f983564a3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Go Modules with Private Azure DevOps repositories]]></title>
            <link>https://seb-nyberg.medium.com/using-go-modules-with-private-azure-devops-repositories-4664b621f782?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/4664b621f782</guid>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 10:45:54 GMT</pubDate>
            <atom:updated>2020-01-16T13:41:55.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Private Go Modules on Azure DevOps</h3><p>There is a long-running issue with go get imports of Azure DevOps repositories due to the fact that the HTTPS URL contains a “_git” segment:</p><p><a href="https://github.com/golang/go/issues/28236">cmd/go: add support for Azure DevOps Git repos to go get · Issue #28236 · golang/go</a></p><h4><strong>The case for using PAT instead of SSH</strong></h4><p>When a module that is imported in your Go code is missing, Go will attempt to fetch the package using go get path/to/package. If the package is missing in $GOPATH/src and $GOPATH/pkg/mod , an attempt is made with HTTPS.</p><p>In order for Git to access the private repository, you may choose to either use a Personal Access Token (PAT) or to register an SSH key and redirect traffic from the HTTPS URL to the SSH equivalent. No matter how you got about it however, there will always be a trailing .git at the end of the repo name.</p><p>The big downside to using SSH is that the module name will need to be aliased, which means that anyone consuming your module would also need to use SSH or create another custom Git URL redirect.</p><p>With a PAT on the other hand, the URL remains intact and usable.</p><h3>Using a Personal Access Token</h3><p>Start off by creating a new Personal Access Token that has read access to code. <a href="https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&amp;tabs=preview-page">Here’s a guide that will step you through the process</a>.</p><p>My process for creating a PAT is normally:</p><ol><li>Create a new PAT in the UI</li><li>Schedule a meeting with the Ops team the date the PAT runs out, set a notification for a week or two before the date</li><li>Copy the PAT to an Azure Key Vault (or any other Vault available to me)</li><li>Copy the PAT into an “common” Azure Library that can be used by the build pipelines</li></ol><p>Then put the token in the global Git config like so:</p><pre>git config --global url.&quot;<a href="https://anythinggoeshere:$devops_token@dev.azure.com/">https://anythinggoeshere:$devops_token@dev.azure.com</a>&quot;.insteadOf &quot;<a href="https://dev.azure.com/">https://dev.azure.com</a>&quot;</pre><p>The anythinggoeshere is the username, and is disregarded by Azure DevOps in this case.</p><p>It is now possible to fetch the Go package with its regular URL + .git :</p><pre>go get -v dev.azure.com/${ORG}/${PROJECT}/_git/${REPO}.git</pre><h4>Using with Docker</h4><p>Simply run the .insteadOf Git command in your Dockerfile. IMPORTANT: remove the $HOME/.gitconfig or credentials will be baked into the image / running container.</p><p>Note that <a href="https://github.com/Azure/draft/issues/564">there are ways</a> to extract build arguments from a Docker image, so it’s not entirely safe, but it’s a best effort.</p><pre>FROM golang:1.12-alpine3.10 AS builder</pre><pre>RUN apk add --no-cache git bash</pre><pre>WORKDIR /code</pre><pre>ARG devops_token<br>RUN git config --global url.&quot;<a href="https://anythinggoeshere:$devops_token@dev.azure.com/">https://anythinggoeshere:$devops_token@dev.azure.com</a>&quot;.insteadOf &quot;<a href="https://dev.azure.com/">https://dev.azure.com</a>&quot;</pre><pre>COPY go.mod go.sum ./</pre><pre>RUN go mod download</pre><pre>COPY . .</pre><pre>RUN go build -o main .</pre><pre>RUN rm $HOME/.gitconfig</pre><p>Then pass the token as an argument when running Docker build:</p><pre><a href="http://twitter.com/docker">docker</a> build \<br>  -t $IMAGE:$TAG \<br>  --build-arg devops_token=$DEVOPS_TOKEN \<br>  .</pre><h4>Bonus: bootstrapping the DevOps token using Makefile and Azure Key Vault</h4><p>Putting this in your Makefile in projects will give developers an easy way to keep the URL up to date. Rotating the key would just force everyone to run make set-git-redirect once.</p><pre>VAULT_NAME ?= &quot;NAME-OF-YOUR-VAULT&quot;<br>DEVOPS_TOKEN_SECRET_NAME ?= &quot;devops-repo-pat&quot;</pre><pre>set-git-redirect:<br> <a href="http://twitter.com/token">@token</a>=`az keyvault secret show --name $(DEVOPS_TOKEN_SECRET_NAME) --vault-name $(VAULT_NAME) --query value -o tsv`; \<br>  [ -z &quot;$$token&quot; ] &amp;&amp; echo &quot;failed to fetch token...&quot; &amp;&amp; exit 1; \<br>  git config --global --unset $(git config --global --get-regexp &quot;dev.azure.com&quot;) &amp;&gt;/dev/null || &quot;true&quot; ; \<br>  git config --global url.&quot;<a href="https://anything:$token@dev.azure.com/">https://anything:$$token@dev.azure.com</a>&quot;.insteadOf &quot;<a href="https://dev.azure.com/">https://dev.azure.com</a>&quot;</pre><p>Something similar can of course be done for the docker build process. YMMV.</p><h4>Bonus: using an SSH key</h4><p>I don’t recommend doing this but I’ll keep this for future reference.</p><p>Each Azure DevOps HTTPS endpoint has a SSH equivalent:</p><pre><a href="https://dev.azure.com/myorg/myproject/_git/myrepo">https://myorg@dev.azure.com/myorg/myproject/_git/myrepo</a><br># has the SSH equivalent<br>git@ssh.dev.azure.com:v3/myorg/myproject/myrepo.git</pre><p>Git can be configured to use SSH instead of HTTPS:</p><pre>git config --global url.&quot;git@ssh.dev.azure.com:v3&quot;.insteadOf https://dev.azure.com</pre><p>You can view the results in ~/.gitconfig.</p><p>To set up an SSH key on your machine, follow <a href="https://docs.microsoft.com/en-us/azure/devops/repos/git/use-ssh-keys-to-authenticate?view=azure-devops&amp;tabs=current-page">this guide</a>.</p><p>Make sure to initialize your modules with the SSH path, including the .git postfix:</p><pre>go mod init dev.azure.com/myorganization/myproject/mypackage.git</pre><p>Once the package has been pushed to Azure DevOps, you can now access it with go get:</p><pre>go get -v -u dev.azure.com/myorganization/myproject/mypackage.git</pre><p>Also, you can use the module in your other go modules:</p><pre>package main</pre><pre>import (<br>    hello &quot;dev.azure.com/myorganization/myproject/mypackage.git/pkg/hello&quot;<br>)</pre><pre>func main() {<br>    hello.SayHello()<br>}</pre><p>For information on how to use this with Docker, check the SSH section of <a href="https://smartystreets.com/blog/2018/09/private-dependencies-in-docker-and-go">this guide</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4664b621f782" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing Git Repositories on Azure DevOps using Personal Access Tokens on Linux]]></title>
            <link>https://seb-nyberg.medium.com/accessing-git-repositories-on-azure-devops-using-personal-access-tokens-on-linux-7fa7495bf1e?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa7495bf1e</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Fri, 04 Jan 2019 11:17:11 GMT</pubDate>
            <atom:updated>2019-01-04T11:34:40.864Z</atom:updated>
            <content:encoded><![CDATA[<p>A quick guide on how to set up PAT authentication without installing a Git Credentials Manager.</p><h3>Creating a new PAT</h3><p>Open the Security section of your account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*SUG5xJkdltXq_eHMWQq-jw.png" /></figure><p>Click “New Token”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFg4hLfcRaDPiCLxLmBinA.png" /></figure><p>Create your token. I grant this one Read &amp; Write but you may want to leave it on Read depending on your use-case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*akZkbmP6OoVO8O6oL8wqZQ.png" /></figure><p>Done! Copy the PAT to clipboard and close the window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*h9RvKhVW04irk19OsdqJ7g.png" /></figure><h3>Authenticating with Git</h3><p>Authentication with PAT in Git happens via the HTTP Authorization header. The header takes a Base64 encoded value on the format “user:token”, and in the case of Azure DevOps, the user part is omitted so what we end up with is simply “:token”.</p><p>Base64 encode your PAT:</p><pre>AUTH=$(echo -n &quot;:$PAT&quot; | openssl base64 | tr -d &#39;\n&#39;)</pre><p>echo -n | ... | tr -d &#39;\n is a common hack on Linux to send input to a prompt and trim away the newline from the output. Simply writingopenssl base64 will ask for user input.</p><p>You can now use $AUTH inside the HTTP Header to authenticate git calls:</p><pre>REPO_URL=&quot;<a href="https://myorg@dev.azure.com/myorg/myrepo/_git/myrepo">https://myorg@dev.azure.com/myorg/myrepo/_git/myrepo</a>&quot;</pre><pre>git -c http.$REPO_URL.extraHeader=&quot;Authorization: Basic $AUTH&quot; \<br>  clone $REPO_URL</pre><p>git -c sends a configuration option to the following git command. To avoid passing the option with each call, you can set the header either in the local config or globally:</p><pre># in case you prefer vim<br># git config --global core.editor vim</pre><pre># add header to global config<br>git config --global http.$REPO_URL.extraHeader &quot;Authorization: Basic $AUTH&quot;</pre><pre># view your config<br>git config --global --edit</pre><p><em>I would suggest adding the PAT expiration date to your calendar to avoid pulling your hair out over why you suddenly lost access.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fa7495bf1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing Tags as Environment Variables to an EC2 instance]]></title>
            <link>https://seb-nyberg.medium.com/passing-tags-as-environment-variables-to-an-ec2-instance-12b64e69891e?source=rss-822c940ca374------2</link>
            <guid isPermaLink="false">https://medium.com/p/12b64e69891e</guid>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Sebastian Nyberg]]></dc:creator>
            <pubDate>Sun, 11 Feb 2018 20:03:46 GMT</pubDate>
            <atom:updated>2018-02-12T08:45:58.718Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article will explore how the UserData EC2 property can be used to bootstrap an EC2 instance with environment variables. If you are already familiar with UserData, feel free to </em><a href="https://gist.github.com/sebnyberg/075e88162b9ce1438b2ebe0b94e7b1c5"><em>check out the final template in this gist</em></a><em>.</em></p><p>While working on a project in <a href="https://serverless.com/">Serverless Framework</a>, I faced the problem of passing environment variables to an EC2 instance. Naively, I thought that it would be as easy as passing variables to lambda functions. Unlike the Lambda resource type however, the CloudFormation resource type <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html">AWS::EC2::Instance</a> does not have an environment property.</p><h4>UserData</h4><p>By passing a script to the UserData property, we can run initialization commands the first time the instance starts up. UserData accepts two types of scripts: <a href="https://cloudinit.readthedocs.io/en/latest/topics/capabilities.html"><em>Cloud Init</em> <em>scripts</em></a><em> </em>and <em>Bash scripts</em>. For our use-case, a Bash script is more than enough.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d49f305cafdb17eefe5594d146d512b2/href">https://medium.com/media/d49f305cafdb17eefe5594d146d512b2/href</a></iframe><p>The problem with exporting environment variables directly in the script is that the UserData script<em> only runs once. </em>The variables will disappear whenever the instance is stopped or restarted, which happens a lot during development.</p><p>So, UserData should create a script that runs automatically on startup.</p><p><em>Note: when the UserData script is executed, the output is appended to the file </em><em>/var/log/cloud-init-output.log . If you are having issues with your script, SSH into the instance and check the log for more info.</em></p><h4>Startup scripts</h4><p>Scripts placed in the folder /etc/profile.d/are run automatically when a new shell is launched. For example, we can create a script called /etc/profile.d/load_env.sh which exports the variables we need.</p><p>A consequence of using CloudFormation in combination with UserData is that we can use the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html">Fn::Sub</a> function to export the AWS Account ID and Region as environment variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b42a272889058ff23ed41d75d8b27cf4/href">https://medium.com/media/b42a272889058ff23ed41d75d8b27cf4/href</a></iframe><h3>Exporting instance tags</h3><p>The tags for an instance can be retrieved with the AWS CLI by running the EC2 command describe-tags. Installing AWS CLI is best done with pip, as shown below:</p><pre># run these on Ubuntu<br>apt-get -y update<br>apt get -y install python-pip</pre><pre># and these on Amazon AMI<br>yum update -y<br>yum install -y python-pip</pre><pre># finally, install AWS CLI<br>pip install --upgrade pip<br>pip install awscli --ignore-installed six</pre><p>Now you can run</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/245e83300649f6e75c57d44ca75e8744/href">https://medium.com/media/245e83300649f6e75c57d44ca75e8744/href</a></iframe><p>Running describe-tags requires that the instance has access to to the policy action ec2:DescribeInstances</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fb491ee5cafc88c04e621cdba541d5c/href">https://medium.com/media/8fb491ee5cafc88c04e621cdba541d5c/href</a></iframe><p><strong><em>IMPORTANT: </em></strong><em>It takes a while for pip to install, so if you SSH into the instance while the UserData script is running, the environment variables will not show up. Allow for some time to pass after the initialization is done.</em></p><h4>Instance metadata</h4><p>In order to properly filter the tags, we need to know the instance id of the running instance. We can find this id in the EC2 instance’s metadata which is available at the special url <a href="http://169.254.169.254/latest/meta-data">http://169.254.169.254/latest/meta-data</a> .</p><pre>ubuntu@i:~$ curl -s <a href="http://169.254.169.254/latest/meta-data/">http://169.254.169.254/latest/meta-data/</a><br>...<br>instance-id<br>instance-type<br>...</pre><pre>ubuntu@i:~$ curl -s <a href="http://169.254.169.254/latest/meta-data/">http://169.254.169.254/latest/meta-data/instance-id</a><br>i-0a648e2145e45c7d3</pre><h4>Exporting tags as environment variables</h4><p>Finally we are ready to export our tags as environment variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84eb088a8239f691971c256256a60d36/href">https://medium.com/media/84eb088a8239f691971c256256a60d36/href</a></iframe><h3>Final thoughts &amp; solution</h3><p>The final solution can be found at <a href="https://github.com/sebnyberg/aws-tags-as-env">Github</a>. Make sure to provide a stack name and a key name to the deployment script, and to wait for a while to let the initialization complete. Good luck!</p><p><em>Finally, it is also worth mentioning that for more complex initialization scenarios, a more tenable solution is to use </em><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html">cfn-init</a><em> and the metadata property </em><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html">AWS::CloudFormation::Init</a><em>. Since we only wanted to pass environment variables however, UserData sufficed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12b64e69891e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>