<?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 Boris Djurdjevic on Medium]]></title>
        <description><![CDATA[Stories by Boris Djurdjevic on Medium]]></description>
        <link>https://medium.com/@djboris?source=rss-bb447eceb1e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*B7-Q_83CqVSdcpz8rUryyg.png</url>
            <title>Stories by Boris Djurdjevic on Medium</title>
            <link>https://medium.com/@djboris?source=rss-bb447eceb1e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:05:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@djboris/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[Automated branch deployment on Kubernetes]]></title>
            <link>https://blog.microfast.ch/automated-branch-deployment-on-kubernetes-fa02db949f0d?source=rss-bb447eceb1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa02db949f0d</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[argo]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Boris Djurdjevic]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 17:06:19 GMT</pubDate>
            <atom:updated>2021-12-29T17:06:19.740Z</atom:updated>
            <content:encoded><![CDATA[<p>This post describes how to configure automated branch deployments on Kubernetes using Argo Events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OvumaropHPC9ExYbic1Xg.png" /><figcaption>Using Argo Events for branch deployment automatisation</figcaption></figure><h3>What are the use cases</h3><p>In my previous work experience I saw the need of branch deployments for various reasons like</p><ul><li>you want to have a branch continuously integration tested</li><li>the testing team wants to be able to test against a branch</li><li>the business wants to preview a feature on a deployed instance</li><li>you just want to have your code deployed to enjoy it</li></ul><p>But at the end, each team or project solved the exact same problem using different ways which is generally not a problem but often results in extended complexity, orphaned deployments or security issues. Most of such strategies incorporate CI jobs that run a deployment using kustomize and revert it the same way. But on a shared cluster you struggle with the permissions of having enough rights to deploy and destruct all required resources but not having access to other deployments. But what if you could define your trusted deployment externally and use a service account to deploy it?</p><h3>What is Argo Events</h3><p>Argo Events is an event-driven workflow automation framework for Kubernetes. This allows us to ingest events when a branch is created or deleted on a VCS and to act on these events with creating and destroying deployments. This post doesn’t explain how to deploy Argo Events, as it’s easy to do so.</p><p>For the event source, where we will be listening to changes, we will choose Gitlab but <a href="https://argoproj.github.io/argo-events/concepts/event_source/">Argo Events supports more than 20 EventSources</a>.</p><p>For the action we take, we will use the <a href="https://argoproj.github.io/argo-events/sensors/triggers/k8s-object-trigger/">Kubernetes Object Trigger</a> as it can create and delete Kubernetes Resources. Our resource will be an <a href="https://argo-cd.readthedocs.io/en/stable/operator-manual/declarative-setup/#applications">ArgoCD Application</a> which deploys a Helm Chart so we have our branch deployment also visible in ArgoCD and can use a trusted Helm Chart for the deployment. For the ease of usage and example, we decide that we will only deploy branches that have an MR open.</p><h3>Configuring EventSources</h3><p>Having Argo Events setup, we can define a gitlab EventSource that registers itself for MergeRequest events on the defined gitlab project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b441724c68b975deee1e076d939ed0bf/href">https://medium.com/media/b441724c68b975deee1e076d939ed0bf/href</a></iframe><p>You can see that we connect the “microfast/website” project with this source and configure a webhook for it. You must create an according ingress for the webhook. Additionally we have a gitlab-access Secret that holds the gitlab personal access key of the user that has the rights to see merge requests and a gitlab-secret which is a random string to verify the webhook.</p><p>After creating this resource, Argo Events will configure the defined projects automatically to send webhooks to the defined URL so we can react when something is happening with merge requests.</p><h3>Configuring Triggers</h3><p>Now as we got the “gitlab” EventSource running, we are receiving events from Gitlab to our Argo Events instance and we just need to react on them. Therefore we need Sensors that handle the deployment and undeployment. Currently it’s not possible to have a dependency/condition construct to have a single Sensor for deployment and undeployment so we will have to define two of them.</p><p>The deployment Sensor listens on our gitlab events and filters only the ones that are resulting in an active MR state (open, reopen, update). Then it defines the trigger to create a Kubernetes resource of the type of an ArgoCD Application and fills the dynamic parameters with the Merge Request ID.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e20c763b72252559a5ff4f531b95fb/href">https://medium.com/media/70e20c763b72252559a5ff4f531b95fb/href</a></iframe><p>You can see that the trigger object is creating a helm chart deployment which sets the variable “MR” to the Merge Request ID, which is used by the helm chart to create unique global resources such as Ingress URLs. Also the ArgoCD Application name and the custom namespace has the ID included to prevent conflicts. After the instantiation of this resource, ArgoCD runs the automated sync so we can soon access the deployed application.</p><p>For the undeployment case, we create another Sensor that reacts only to closing and merging events and just deletes the ArgoCD Application, which also removes the helm based deployment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61db9b9704705fa705a90b9f12d52ee3/href">https://medium.com/media/61db9b9704705fa705a90b9f12d52ee3/href</a></iframe><p>But we also need to customize our deployment and image builds to deploy the release we want to see.</p><p>For the CI job this means in our case that we build a separate image, which we label accordingly with mr-${CI_MERGE_REQUEST_IID} only on merge requests.</p><p>As for the deployment we chose to use helm charts as we can easily propagate a discriminator variable to render unique global resources or identifiers. This can be for example an Ingress URL or the image label:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b3f562df3f491f76e9110c6d03eeb6e/href">https://medium.com/media/1b3f562df3f491f76e9110c6d03eeb6e/href</a></iframe><h3>Further implementation</h3><p>You can use this example as a starting point. In order to scale it’s recommended to create RBAC rules and a dedicated service account for the Sensor to create and delete the Kubernetes resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa02db949f0d" width="1" height="1" alt=""><hr><p><a href="https://blog.microfast.ch/automated-branch-deployment-on-kubernetes-fa02db949f0d">Automated branch deployment on Kubernetes</a> was originally published in <a href="https://blog.microfast.ch/">microfast</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes OpenID Connect]]></title>
            <link>https://blog.microfast.ch/kubernetes-openid-connect-3883043f0e94?source=rss-bb447eceb1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3883043f0e94</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Boris Djurdjevic]]></dc:creator>
            <pubDate>Mon, 30 Aug 2021 11:02:55 GMT</pubDate>
            <atom:updated>2021-08-30T11:02:55.839Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post I’m going to show you, how to authenticate Kubernetes users against Azure AD or any other OpenID Connect provider. The first part of this post gives you some background information about authentication methods while the second part describes the configuration needed.</p><figure><img alt="an overview of how kubectl, kubelogin, kube-apiserver, the OIDC IdP and the local browser interact with each other" src="https://cdn-images-1.medium.com/max/623/1*DG2Jb-hAphYZ7A3Btc323g.png" /><figcaption>Very simplified overview of how the components interact with each other</figcaption></figure><h3>Authentication methods for Kubernetes</h3><p>While Kubernetes has the resource type <em>ServiceAccount</em> for technical users, there is no such type for normal/human users.</p><p><em>ServiceAccounts</em> are used for example to run Pods, which recieve a token injected that can be used by the workload to authenticate itself to the kube-apiserver. According to the RBAC rules, it allows for example CoreDNS to access the service information it needs or allows a Jupyter Hub instance to spawn per-user workspaces. Each <em>ServiceAccount</em> has at least one corresponding <em>Secret</em> that is automatically created, which contains the JWT that is validated by the <em>kube-apiserver</em> so that the user information can be extracted.</p><p>Normal users don’t work like that, as they aren’t registered inside Kubernetes. But they are loosely coupled with the RBAC, that can contain usernames or groups as strings, which don’t have to match to an existing user. The way it works is, that when the <em>kube-apiserver</em> receives a call, it runs the defined authenticator which authenticates the request and exposes the extracted or calculated information for further processing.</p><p>A common authenticator is the x509 one, which uses the TLS connection to extract the username from the <em>CN</em> field and the groups from the <em>O</em> fields of the client certificate distinguished name. This is often used for the communication between Kubernetes components like the <em>kubelet</em> or <em>scheduler</em> to the <em>kube-apiserver</em>. You can also distribute such client certificates to users. This is commonly used in smaller or experimental setups but for a productive setup it lacks either of a certificate revocation method or a simple mechanism to provide very short lived certificates for users. Such mechanisms are required to revoke access in case credentials have been compromised. If the according certificate is long lived, the only way to revoke access to its defined user and groups is to rotate the CA.</p><p>Other authentication methods are token files (not practicable) or custom authenticators that can be put either in front of the kube-apiserver (authenticating proxy) or called with a webhook to validate bearer tokens. While a custom authenticator provides great opportunities for integrating Kubernetes into existing environments, it requires some security sensitive development effort.</p><p>But there is another authentication method: <strong>OpenID Connect</strong>. It allows you to configure the <em>kube-apiserver</em> to an identity provider of your choice. The <em>kube-apiserver</em> will validate the <em>id_token </em>from the <em>Authorization</em> HTTP header and extract the username and groups from configurable claims. Additionally kubectl is able to renew the <em>id_token</em> using a refresh token, which allows to keep the <em>id_token</em> lifetime short. This is important, as the <em>kube-apiserver</em> isn’t calling an <em>userinfo</em> endpoint and therefore there is no way to revoke an <em>id_token</em> as long as its signature and expiration is valid.</p><h3>Registering an OpenID Connect client</h3><p>For this post, we are using Azure AD as an example identity provider for OpenID Connect. But you can use Gitlab.com, Keycloak or any other IdP that is standards compliant and provides an OpenID Connect discovery endpoint.</p><p>Inside Azure Active Directory, go to “App Registrations” and register a new application. Give it an appropriate name, choose which user types can get a login and set an initial redirect URI to http://localhost:8000 :</p><figure><img alt="We see the form while registering an OIDC application inside azure active directory" src="https://cdn-images-1.medium.com/max/633/1*7eCNUXbTNuQaVgsZJyKo5A.png" /><figcaption>Registering an application inside Azure AD</figcaption></figure><p>Next, copy the <em>Application ID</em> (which is the OpenID Connect <em>client_id</em>) and the <em>Directory ID</em>, which you will need later.</p><figure><img alt="We see details about the registered application. Which are the Application ID and Directory ID." src="https://cdn-images-1.medium.com/max/516/1*cMxBlr-KOP4RMFQ3Lbn5EA.png" /><figcaption>Registered application overview in Azure AD</figcaption></figure><p>It is also recommended, that you add an additional redirect URI with http://localhost:18000 , which is used by <em>kubelogin</em> when the local port 8000 is already taken.</p><p>Then you need to create a client secret, which you can do in the <em>Certificates and Secrets</em> menu. Copy the secrets <em>Value </em>(not the ID), which you will need later.</p><figure><img alt="The form for adding a client secret can be found below “Certificates and Secrets”" src="https://cdn-images-1.medium.com/max/1024/1*X9POtWuhk1NlRhT2svcPfw.png" /><figcaption>Adding a client secret</figcaption></figure><p>Now you want to add a <em>groups</em> claim, that allows you to authorize the user based on its groups:</p><figure><img alt="Adding groups claims requires you to select what kind of groups should be included inside the id_token." src="https://cdn-images-1.medium.com/max/1024/1*B4J7HozmrKRSwOnbOYQUtQ.png" /><figcaption>Adding a groups claim</figcaption></figure><p>As the last step, you can get the users email which you can use in Kubernetes as username. For this you need to add the email claim in the <em>Token configuration</em>:</p><figure><img alt="The email claim needs to be added in the “Add optional claim” menu" src="https://cdn-images-1.medium.com/max/1024/1*3lApG3gjaluQDUF2rNMQ5w.png" /><figcaption>Adding the optional claim “email”</figcaption></figure><p>Now you are done configuring the OpenID Connect client for Kubernetes in Azure AD.</p><h3>Configuring kubectl</h3><p>kubectl supports token renewal, but it has no built-in mechanism to get the initial id_token and refresh_token. As we are using the <em>authorization code flow</em>, we need to have some browser redirect functionality. For this, there is a great project called <a href="https://github.com/int128/kubelogin">kubelogin</a> that implements the authentication against the OpenID Connect provider and configures your <em>kubeconfig</em> so that kubectl can use the <em>id_token</em> and also refresh it, when it’s time for.</p><h4>Testing the OpenID Connect configuration</h4><p>When you finished all the steps from above, you can test your configuration with <em>kubelogin</em>, which should be in your $PATH as kubectl-oidc_login . You need to run the following command with your own parameters:</p><ul><li>Issuer URL: The UUID part is the <em>Directory ID</em>, the URL must match the <em>iss</em> claim, therefore needs to be exactly like this, including the trailing slash</li><li>Client ID: This is your <em>Application ID</em></li><li>Secret: This is the <em>Secret Value</em></li></ul><pre>kubectl-oidc_login get-token \<br>  --oidc-issuer-url <a href="https://sts.windows.net/f3959687-7500-4140-86fa-5ac9d2911ab8/">https://sts.windows.net/f3959687-0000-0000-0000-000000000000/</a> \<br>  --oidc-client-id=57779e92-0000-0000-0000-000000000000 \<br>  --oidc-client-secret=&quot;t4a-XXXXXXXXXXXXXXXXXX-X.~XXXXXXXX&quot; \<br>  --oidc-extra-scope=&quot;email groups&quot;</pre><p>While this command is run, your browser should open automatically and redirect you to the Microsoft login page, where you need to give your newly registered application permission to access your data (consent). If everything is fine, your token is printed out to the console.</p><h4>Setting your kubeconfig</h4><p>Now you can configure <em>kubectl</em> to invoke <em>kubelogin</em> automatically when accessing your cluster and use OpenID Connect as token:</p><pre>kubectl config set-credentials azure \<br>  --exec-api-version=client.authentication.k8s.io/v1beta1 \<br>  --exec-command=kubectl \<br>  --exec-arg=oidc-login \<br>  --exec-arg=get-token \<br>  --exec-arg=--oidc-issuer-url=<a href="https://sts.windows.net/f3959687-0000-0000-0000-000000000000/">https://sts.windows.net/f3959687-0000-0000-0000-000000000000/</a> \<br>  --exec-arg=--oidc-client-id=57779e92-0000-0000-0000-000000000000 \<br>  --exec-arg=--oidc-client-secret=&quot;t4a-XXXXXXXXXXXXXXXXXX-X.~XXXXXXXX&quot; \<br>  --exec-arg=--oidc-extra-scope=&quot;email groups&quot;</pre><p>You can map this user to your according context:</p><pre>kubectl config set-context supercluster --cluster=supercluster --user=azure</pre><p>From the client side, everything is done now. But if you try to access your cluster now, you will get a token error. This is why we have to configure Kubernetes.</p><h3>Configuring the kube-apiserver</h3><p>Your <em>kube-apiserver</em> instance needs to have the following arguments configured, so it can validate your <em>id_token</em>s and doesn’t add a prefix to your groups. It will also use your <em>email</em> as username:</p><pre>--oidc-client-id=57779e92-0000-0000-0000-000000000000<br>--oidc-issuer-url=<a href="https://sts.windows.net/f3959687-0000-0000-0000-000000000000/">https://sts.windows.net/f3959687-0000-0000-0000-000000000000/</a><br>--oidc-username-claim=email<br>--oidc-groups-claim=groups<br>--oidc-groups-prefix=&quot;&quot;</pre><p>If you use kubeadm, you can define these settings in your <em>ClusterConfiguration</em> below apiServer.extraArgs .</p><p>After restarting all <em>kube-apiserver</em>s, you are ready to use OpenID Connect.</p><h3>RBAC configuration</h3><p>Most likely, when you first try to access your Kubernetes cluster with the OpenID Connect token, you will get a permission error but the message will mention your email. So you know, that you are successfully authenticated.</p><p>Now you can configure <em>(Cluster)RoleBindings</em> to your email or your Azure AD security groups:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: cluster-admins-from-azure<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: cluster-admin<br>subjects:<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: User<br>  name: &quot;boris.djurdjevic@example.com&quot;<br>- apiGroup: rbac.authorization.k8s.io<br>  kind: Group<br>  name: &quot;6ca56316-0000-0000-0000-000000000000&quot;</pre><p>If you look closely, you will see that the group identifier is not the display name of the group. This is because Azure AD only embeds the Group ID in the <em>id_token</em>, so you will have to map your groups manually by their Object ID.</p><h3>Further information</h3><p>This post shows a walk-through with Azure AD as an example on how to configure OpenID Connect in your Kubernetes cluster. But for a production setup, you want to check the following links for more and complete information:</p><ul><li><a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/#openid-connect-tokens">Kubernetes OpenID Connect authentication</a></li><li><a href="https://github.com/int128/kubelogin">kubelogin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3883043f0e94" width="1" height="1" alt=""><hr><p><a href="https://blog.microfast.ch/kubernetes-openid-connect-3883043f0e94">Kubernetes OpenID Connect</a> was originally published in <a href="https://blog.microfast.ch/">microfast</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring Go code using AST replacement]]></title>
            <link>https://blog.microfast.ch/refactoring-go-code-using-ast-replacement-e3cbacd7a331?source=rss-bb447eceb1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3cbacd7a331</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Boris Djurdjevic]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 14:41:00 GMT</pubDate>
            <atom:updated>2021-03-26T14:41:00.772Z</atom:updated>
            <content:encoded><![CDATA[<p>For complex refactoring of Go code you can use the Go AST parser and printer to find patterns and replace them with your new code, retaining parameters and variables.</p><p>A code base with a lot of simple Go tests wasn’t quite readable and we wanted to remove repetitive assertions using <a href="https://github.com/stretchr/testify">testify</a>. The goal was to implement such conversions:</p><pre>// before:<br>err := ThisMightReturnError()<br>if err != nil {<br>    t.Fatalf(&quot;my error: %s&quot;, err)<br>}<br></pre><pre>// after:<br>err := ThisMightReturnError()<br>require.NotNil(t, &quot;my error: %s&quot;, err)</pre><p>As regexes could solve this, there is an even more interesting solution for (over)engineers: AST rewriting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*nYySgzdZaNfZRmD2zy8M-A.png" /><figcaption>Example of an AST</figcaption></figure><h4>Parsing the AST</h4><p>Using go/parser we can parse a Go source file and get the AST from it. <a href="http://github.com/davecgh/go-spew">Spew</a> can be used to dump the AST in a human readable format:</p><pre>import (<br>    &quot;go/parser&quot;<br>    &quot;go/token&quot;</pre><pre>    &quot;github.com/davecgh/go-spew/spew&quot;<br>)</pre><pre>fs := token.NewFileSet()<br>f, err := parser.ParseFile(fs, &quot;example/main_test.go&quot;, nil, parser.AllErrors)</pre><pre>spew.Dump(f)</pre><p>Therefore we get the AST tree that looks similar to this part:</p><pre>(*ast.File)(0xc00014c000)({<br> Doc: (*ast.CommentGroup)(&lt;nil&gt;),<br> Package: (token.Pos) 1,<br> Name: (*ast.Ident)(0xc0001280c0)(main),<br> Decls: ([]ast.Decl) (len=3 cap=4) {<br>  (*ast.GenDecl)(0xc000108080)({<br>   Doc: (*ast.CommentGroup)(&lt;nil&gt;),<br>   TokPos: (token.Pos) 15,<br>   Tok: (token.Token) import,<br>   Lparen: (token.Pos) 22,<br>   Specs: ([]ast.Spec) (len=2 cap=2) {<br>    (*ast.ImportSpec)(0xc00010c300)({<br>     Doc: (*ast.CommentGroup)(&lt;nil&gt;),<br>...</pre><h4>Printing the code again</h4><p>If we want to print the AST back as code we can use go/printer:</p><pre>import &quot;os&quot;<br>import &quot;go/printer&quot;</pre><pre>...</pre><pre>printer.Fprint(os.Stdout, fs, f)</pre><h4>Finding the if statement</h4><p>To target if err != nil statements, we need to create a function that detects them in an AST tree. Such a statement looks like this in AST:</p><pre>(*ast.IfStmt)(0xc0000241c0)({<br> If: (token.Pos) 80,<br> Init: (ast.Stmt) &lt;nil&gt;,<br> Cond: (*ast.BinaryExpr)(0xc000074570)({<br>  X: (*ast.Ident)(0xc00005e220)(err),   // left-hand-side operator<br>  OpPos: (token.Pos) 87,<br>  Op: (token.Token) !=,                 // token.NEQ<br>  Y: (*ast.Ident)(0xc00005e240)(nil)    // right-hand-side operator<br>})</pre><p>A matching function can be implemented as follows: It gets an AST node and checks if the node is an ast.IfStmt , goes deeper into the statement and validates the operator and variable names:</p><pre>func isIfErrBlock(n ast.Node) bool {<br>  // is: if (err != nil)<br>  if ifStmt, ok := n.(*ast.IfStmt); ok {<br>    // is: (err != nil)<br>    if binExpr, ok := ifStmt.Cond.(*ast.BinaryExpr); ok {<br>       // is: !=<br>       if binExpr.Op != token.NEQ {<br>          return false<br>       }</pre><pre>       // Check left hand identifier (err)<br>       if ident, ok := binExpr.X.(*ast.Ident); ok {<br>         if ident.Obj == nil {<br>           return false<br>         }</pre><pre>         if ident.Obj.Kind != ast.Var || ident.Name != &quot;err&quot; {<br>           return false<br>         }<br>       }</pre><pre>       // Check right hand identifier (nil)<br>       if ident, ok := binExpr.Y.(*ast.Ident); ok {<br>         if ident.Obj != nil || ident.Name != &quot;nil&quot; {<br>           return false<br>         }<br>       }</pre><pre>      return true<br>    }<br> }</pre><pre>  return false<br>}</pre><h4>Validate the If-Body</h4><p>Additionally we validate that the if-body has only one expression inside and calls a Fatalf function. If we get this, we preserve the Fatalf arguments as we want to pass them to testify:</p><pre>func isErrBody(n ast.Node) (bool, []ast.Expr) {<br>  // check if it&#39;s really an if statement<br>  ifStmt, ok := n.(*ast.IfStmt)<br>  if !ok {<br>    return false, nil<br>  }</pre><pre>  // check if it has only one item in the block<br>  if len(ifStmt.Body.List) != 1 {<br>    return false, nil<br>  }</pre><pre>  stmt := ifStmt.Body.List[0]</pre><pre>  // Cast expression to get the call<br>  expr, ok := stmt.(*ast.ExprStmt)<br>  if !ok {<br>    return false, nil<br>  }</pre><pre>  call, ok := expr.X.(*ast.CallExpr)<br>  if !ok {<br>    return false, nil<br>  }</pre><pre>  // Get the function<br>  fun, ok := call.Fun.(*ast.SelectorExpr)<br>  if !ok {<br>    return false, nil<br>  }</pre><pre>  if fun.Sel.Name != &quot;Fatalf&quot; {<br>    return false, nil<br>  }</pre><pre>  return true, call.Args<br>}</pre><h4>Putting it all together</h4><p>We can now:</p><ul><li>Read and parse the AST of a Go file</li><li>Detect the if-statement</li><li>Validate the if-body, if it meets our criteria and extract the Fatalf call arguments</li><li>Serialize the AST as a Go file</li></ul><p>To put it in a working piece together we use the astutil to conveniently walk through our AST and find-and-replace our if-blocks:</p><pre>import &quot;golang.org/x/tools/go/ast/astutil&quot;</pre><pre>...<br>spew.Dump(f)</pre><pre>astutil.Apply(f, func(cr *astutil.Cursor) bool {<br>  // Check if it is: if err != nil<br>  if !isIfErrBlock(cr.Node()) {<br>    return true<br>  }</pre><pre>  // Check if body contains only one statement and get args for it<br>  sigRet, args := isErrBody(cr.Node())<br>  if !sigRet {<br>    return true<br>  }</pre><pre>  // Replace values<br>  cr.Replace(&amp;ast.ExprStmt{<br>    X: &amp;ast.CallExpr{<br>      Fun:  ast.NewIdent(&quot;require.NotNil&quot;),<br>      Args: append([]ast.Expr{ast.NewIdent(&quot;t&quot;)}, args...),<br>    },<br>  })</pre><pre>  return false<br>}, nil)</pre><pre>// Print result<br>printer.Fprint(os.Stdout, fs, f)</pre><p>As you can see, we use our isIfErrBlock and isErrBlock functions from above to check if our node matches the criteria and if so, we replace it with an expression statement:</p><pre>&amp;ast.ExprStmt{<br>  X: &amp;ast.CallExpr{<br>    Fun:  ast.NewIdent(&quot;require.NotNil&quot;),<br>    Args: append([]ast.Expr{ast.NewIdent(&quot;t&quot;)}, args...),<br>  },<br>})</pre><p>which equals to require.NotNil(t, args) , where the args are taken from the original t.Fatalf(args)statement.</p><h4>Example of operation</h4><p>The demonstration code from above converts files like this:</p><pre>package main</pre><pre>import (<br>  &quot;errors&quot;<br>  &quot;testing&quot;<br>)</pre><pre>func ThisMightReturnError() error {<br>  return errors.New(&quot;I&#39;m an error&quot;)<br>}</pre><pre>func TestMain(t *testing.T) {<br>  err := ThisMightReturnError()<br>  if err != nil {<br>    t.Fatalf(&quot;my error: %s&quot;, err)<br>  }<br>}</pre><p>to this:</p><pre>package main</pre><pre>import (<br>  &quot;errors&quot;<br>  &quot;testing&quot;<br>)</pre><pre>func ThisMightReturnError() error {<br>  return errors.New(&quot;I&#39;m an error&quot;)<br>}</pre><pre>func TestMain(t *testing.T) {<br>  err := ThisMightReturnError()<br>  require.NotNil(t, &quot;my error: %s&quot;, err)<br>}</pre><h4>Summary</h4><p>We could easily replace code blocks with other code blocks using AST parsing and serializing. The code can be improved for better reliability and usability (like importing github.com/stretchr/testify/require automatically or passing *testing.T too).</p><p>The demo code is available here: <a href="https://gist.github.com/djboris9/f58c7bf19472dab829a858fd426685e9">https://gist.github.com/djboris9/f58c7bf19472dab829a858fd426685e9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3cbacd7a331" width="1" height="1" alt=""><hr><p><a href="https://blog.microfast.ch/refactoring-go-code-using-ast-replacement-e3cbacd7a331">Refactoring Go code using AST replacement</a> was originally published in <a href="https://blog.microfast.ch/">microfast</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[whois with telnet]]></title>
            <link>https://djboris.medium.com/whois-with-telnet-8ca1afbe3cdd?source=rss-bb447eceb1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ca1afbe3cdd</guid>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Boris Djurdjevic]]></dc:creator>
            <pubDate>Mon, 11 Jun 2018 15:03:26 GMT</pubDate>
            <atom:updated>2018-06-11T15:03:26.931Z</atom:updated>
            <content:encoded><![CDATA[<p>Some might not know, that the <a href="https://tools.ietf.org/html/rfc3912">whois</a> protocol is simple to use directly from telnet. Just send the requested domain with a &lt;cr&gt;&lt;lf&gt; to the service on tcp/43 and you get the response or a pointer to the next whois service.</p><pre>$ telnet whois.iana.org 43<br>Trying 192.0.47.59...<br>Connected to whois.iana.org.<br>Escape character is &#39;^]&#39;.<br>medium.com                  &lt;-- requested domain<br>% IANA WHOIS server<br>% for more information on IANA, visit <a href="http://www.iana.org/">http://www.iana.org</a><br>% This query returned 1 object</pre><pre>refer:        whois.nic.ch</pre><pre>domain:       COM</pre><pre>...</pre><pre>whois:        whois.verisign-grs.com</pre><pre>...</pre><pre>Connection closed by foreign host.</pre><p>Now follow the whois pointer:</p><pre>$ telnet whois.verisign-grs.com 43<br>Trying 199.7.55.74...<br>Connected to whois.verisign-grs.com.<br>Escape character is &#39;^]&#39;.<br>medium.com                    &lt;-- requested domain<br>   Domain Name: MEDIUM.COM<br>   Registry Domain ID: 1329658_DOMAIN_COM-VRSN<br>   Registrar WHOIS Server: whois.registrar.amazon.com<br>   Registrar URL: <a href="http://registrar.amazon.com/">http://registrar.amazon.com</a><br>   Updated Date: 2017-11-06T05:17:00Z<br>   Creation Date: 1998-05-27T04:00:00Z<br>...</pre><p>That’s it</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ca1afbe3cdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebAssembly excursion with Go]]></title>
            <link>https://blog.microfast.ch/webassembly-excursion-with-go-2bb3eded536e?source=rss-bb447eceb1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bb3eded536e</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[wasm]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Boris Djurdjevic]]></dc:creator>
            <pubDate>Sat, 19 May 2018 21:27:34 GMT</pubDate>
            <atom:updated>2018-05-19T21:27:34.523Z</atom:updated>
            <content:encoded><![CDATA[<p>This post shows you how easily it is to compile a WebAssembly module using Go with the latest patches as language.</p><p>I’ve been watching the <a href="https://github.com/golang/go/issues/18892">WebAssembly (Wasm) support issue</a> for Go for a long time without trying any patches out. WebAssembly support would be a great benefit for the Go and web community as it allows different languages and technologies to be used crossplatform and sandboxed in a standard webbrowser. Completly without Flash, Silverlight and all other painful stuff. Even without transpiling to JavaScript. It’s a real solution, not a workaround.</p><h4>Building Go</h4><p>Building Go is pretty easy and takes less than five minutes on my mid-end laptop. Just clone the repository and run the build script. That’s it. But not all patches are merged into upstream yet so I will clone <a href="https://medium.com/u/1b34f20489ee">Richard Musiol</a> s repository, as he is the leading one who is porting Go to Wasm and will maintain the port:</p><pre>$ git clone <a href="/service/mailto:git@github.com">git@github.com</a>:neelance/go.git newgo<br>$ cd newgo/src/<br>$ git rev-parse HEAD<br>d7841c75357e82fb6b880bbc84d36bd28d825847<br>$ git checkout wasm-wip<br>$ ./all.bash<br>$ export PATH=/home/djboris/newgo/bin:$PATH<br>$ go version<br>go version devel +d7841c7535 Sat May 19 13:15:47 2018 +0200 linux/amd64</pre><h4>Go code for WebAssembly</h4><p>This example code should be compiled to a WebAssemble module:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    fmt.Println(Add(21, 21))<br>}</pre><pre>func Add(a, b int) int {<br>    return a + b<br>}</pre><p>As crosscompiling code for WebAssembly is exactly the same as for other architectures in Go, you must only set two environment variables and run the usual build command:</p><pre>$ GOARCH=wasm GOOS=js go build -o main.wasm main.go</pre><p>This will generate main.wasm which will be loaded and executed by the browser. Its MIME type is <em>application/wasm </em>so it must be served with the according <em>Content-Type</em> or the browser will complain.</p><h4>Combining the things</h4><p>My first try was a week ago on a older revision of the wasm-wip branch. So Firefox printed an error to the console when I tried to execute it using the <a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running">MDN examples</a>:</p><pre>TypeError: import object field &#39;go&#39; is not an Object</pre><p>Sadly the main.wasm binary had imports which couldn’t be satisfied:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*315zxGht7_bL4uPamx7T3w.png" /><figcaption>wasm-dump -x main.wasm # go get github.com/go-interpreter/wagon/cmd/wasm-dump</figcaption></figure><p>After that I tried to mock the non existing functions for the importObject but before I had a running version, a useful <a href="https://github.com/neelance/go/commit/d7841c75357e82fb6b880bbc84d36bd28d825847">commit</a> came in which fitted the gap. Combining the provided <a href="https://raw.githubusercontent.com/neelance/go/d7841c75357e82fb6b880bbc84d36bd28d825847/misc/wasm/wasm_exec.js">wasm_exec.js</a> with the following html does the trick.</p><pre>&lt;html&gt;<br>&lt;body&gt;<br>&lt;script src=&quot;wasm_exec.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>const go = new Go();<br>WebAssembly.instantiateStreaming(fetch(&#39;main.wasm&#39;), go.importObject).then(function(dat) {<br>    go.run(dat.instance);<br>});<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>After serving wasm_exec.js, index.htmland main.wasm, the developer console said 42. The WebAssembly module was executed and my first first WebAssembly excursion was successful too :)</p><h4>Acknowledgement</h4><p>I would like to thank <a href="https://medium.com/u/1b34f20489ee">Richard Musiol</a> for his great work making WebAssembly a build target for Go!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bb3eded536e" width="1" height="1" alt=""><hr><p><a href="https://blog.microfast.ch/webassembly-excursion-with-go-2bb3eded536e">WebAssembly excursion with Go</a> was originally published in <a href="https://blog.microfast.ch/">microfast</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digging into UPnP by searching a Sonos API]]></title>
            <link>https://djboris.medium.com/digging-into-upnp-by-searching-a-sonos-api-5e10e080a232?source=rss-bb447eceb1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e10e080a232</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[sonos]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Boris Djurdjevic]]></dc:creator>
            <pubDate>Wed, 26 Jul 2017 11:35:20 GMT</pubDate>
            <atom:updated>2017-07-26T11:35:20.613Z</atom:updated>
            <content:encoded><![CDATA[<p>A discussion about connection possibilities of a Sonos speaker led to an short analysis on how it communicates with other systems. As an exercise I would like to control the volume.</p><p>At first I thought Sonos uses a proprietary API because after a quick search on the internet I couldn’t find anything useful. However, after searching for some minutes it turned out that there are open protocols in use.</p><h4>Search for protocols</h4><p><em>nmap</em> found the IP address of my Sonos Play:5 and I searched for open TCP ports on this device:</p><pre># nmap -p1–65535 192.168.0.24</pre><pre>Starting Nmap 7.50 ( <a href="https://nmap.org/">https://nmap.org</a> ) at 2017–07–24 11:48 CEST<br>Nmap scan report for 192.168.0.24<br>Host is up (0.020s latency).<br>Not shown: 65532 closed ports<br>PORT STATE SERVICE<br>1400/tcp open cadkey-tablet<br>1410/tcp open hiq<br>1443/tcp open ies-lm<br>MAC Address: B8:E9:XX:XX:XX:XX (Sonos)</pre><pre>Nmap done: 1 IP address (1 host up) scanned in 40.32 seconds</pre><p>TCP ports 1400, 1410 and 1443 are open. Using curl it was clear that 1400 and 1443 are the same or similar services with the difference that 1443 uses TLS.</p><pre>$ curl -v 192.168.0.24:1400/<br>*   Trying 192.168.0.24...<br>* TCP_NODELAY set<br>* Connected to 192.168.0.24 (192.168.0.24) port 1400 (#0)<br>&gt; GET / HTTP/1.1<br>&gt; Host: 192.168.0.24:1400<br>&gt; User-Agent: curl/7.54.1<br>&gt; Accept: */*<br>&gt; <br>&lt; HTTP/1.1 403 Forbidden<br>&lt; Cache-Control: no-cache<br>&lt; Content-type: text/html<br>&lt; Server: Linux UPnP/1.0 Sonos/36.4-42130 (ZPS5)<br>&lt; Connection: close<br>&lt; <br>* Closing connection 0<br>&lt;HTML&gt;&lt;HEAD&gt;&lt;TITLE&gt;Error 403&lt;/TITLE&gt;&lt;/HEAD&gt;&lt;BODY&gt;&lt;H1&gt;Error 403&lt;/H1&gt;&lt;P&gt;Forbidden&lt;/P&gt;&lt;/BODY&gt;&lt;/HTML&gt;</pre><p>Ok, that’s interesting. The Server string contains UPnP in it what looks like this device has some UPnP capability. Searching the internet I found that UPnP uses SSDP for discovery so I installed the gssdp-device-sniffer on my Linux system. One of the responses which were caught look like this:</p><pre>CACHE-CONTROL: max-age = 1800<br>EXT: <br>LOCATION: http://192.168.0.24:1400/xml/device_description.xml<br>Server: Linux UPnP/1.0 Sonos/36.4-42130 (ZPS5)<br>ST: urn:schemas-upnp-org:service:MusicServices:1<br>USN: uuid:RINCON_B8E9XXXXXXXXXXXXX::urn:schemas-upnp-org:service:MusicServices:1<br>X-RINCON-HOUSEHOLD: Sonos_xxxxxxxxxxxxxxxxxxxxx<br>X-RINCON-BOOTSEQ: 162<br>X-RINCON-WIFIMODE: 1<br>X-RINCON-VARIANT: 0</pre><p>Remark: The port 1410 did also respond to a HTTP request with an UPnP Server string but I couldn’t find any description document URI.</p><h3>Understanding UPnP</h3><p>At this point we know this device uses UPnP and a special URI was discovered which seems like a step forward. But first I had to learn something about UPnP. On <a href="https://openconnectivity.org/developer/specifications/upnp-resources/upnp">https://openconnectivity.org/developer/specifications/upnp-resources/upnp</a> you can find very helpful specifications. As an introduction <a href="http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v2.0.pdf">http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v2.0.pdf</a> is enough as it explains UPnP basics down to a common protocol layer. Following steps are defined, namely <em>Addressing</em>, <em>Discovery</em>, <em>Description</em>, <em>Control</em>, <em>Eventing</em>, <em>Presentation</em>.</p><p>The <em>discovery</em> step we already have above, where I caught the SSDP message. It provided us with an URI which is specified in the <em>description</em> step. Looking at the data from http://192.168.0.24:1400/xml/device_description.xml shows a list of all so called services where the following definition looks interesting:</p><pre>&lt;service&gt;<br>  &lt;serviceType&gt;urn:schemas-upnp-org:service:RenderingControl:1&lt;/serviceType&gt;<br>  &lt;serviceId&gt;urn:upnp-org:serviceId:RenderingControl&lt;/serviceId&gt;<br>  &lt;controlURL&gt;/MediaRenderer/RenderingControl/Control&lt;/controlURL&gt;<br>  &lt;eventSubURL&gt;/MediaRenderer/RenderingControl/Event&lt;/eventSubURL&gt;<br>  &lt;SCPDURL&gt;/xml/RenderingControl1.xml&lt;/SCPDURL&gt;<br>&lt;/service&gt;</pre><p>Going to http://192.168.0.24:1400/xml/RenderingControl.xml it reveals several actions like <em>GetVolume</em> and <em>SetVolume</em> which are described with its parameters like this example shows (stripped <em>relatedStateVariable</em> for readability away):</p><pre>&lt;action&gt;<br>  &lt;name&gt;GetVolume&lt;/name&gt;<br>  &lt;argumentList&gt;<br>    &lt;argument&gt;<br>      &lt;name&gt;InstanceID&lt;/name&gt;<br>      &lt;direction&gt;in&lt;/direction&gt;<br>    &lt;/argument&gt;<br>    &lt;argument&gt;<br>      &lt;name&gt;Channel&lt;/name&gt;<br>      &lt;direction&gt;in&lt;/direction&gt;<br>    &lt;/argument&gt;<br>    &lt;argument&gt;<br>      &lt;name&gt;CurrentVolume&lt;/name&gt;<br>      &lt;direction&gt;out&lt;/direction&gt;<br>    &lt;/argument&gt;<br>  &lt;/argumentList&gt;<br>&lt;/action&gt;</pre><p>Now we are in the step/chapter <em>Control. </em>Explanations can be found in the <a href="http://upnp.org/specs/av/UPnP-av-RenderingControl-v1-Service.pdf">UPnP-av-RenderingControl-v1-Service</a> document.</p><h4>Sending a request</h4><p>It’s time to send a request. <a href="http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v2.0.pdf">UPnP-arch-DeviceArchitecture</a> explains on page 78 an <em>Action Invocation</em> which I used as template for the SOAP request to get the actual volume level.</p><pre>echo &#39;<br>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;s:Envelope xmlns:s=&quot;<a href="http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>&quot; s:encodingStyle=&quot;<a href="http://schemas.xmlsoap.org/soap/encoding/">http://schemas.xmlsoap.org/soap/encoding/</a>&quot;&gt;<br> &lt;s:Body&gt;<br>  &lt;u:GetVolume xmlns:u=&quot;urn:schemas-upnp-org:service:RenderingControl:1&quot;&gt;<br>   &lt;InstanceID&gt;0&lt;/InstanceID&gt;<br>   &lt;Channel&gt;Master&lt;/Channel&gt;<br>  &lt;/u:GetVolume&gt;<br> &lt;/s:Body&gt;<br>&lt;/s:Envelope&gt;<br>&#39; | curl -v -d @- \<br> -H &#39;SOAPAction: &quot;urn:schemas-upnp-org:service:RenderingControl:1#GetVolume&quot;&#39; \<br> -H &#39;content-type: text/xml; charset=&quot;utf-8&quot;&#39; \<br> http://192.168.0.24:1400/MediaRenderer/RenderingControl/Control</pre><p>Invoking this command it responds with the volume level 22:</p><pre>&lt;s:Envelope xmlns:s=&quot;<a href="http://schemas.xmlsoap.org/soap/envelope/">http://schemas.xmlsoap.org/soap/envelope/</a>&quot; s:encodingStyle=&quot;<a href="http://schemas.xmlsoap.org/soap/encoding/">http://schemas.xmlsoap.org/soap/encoding/</a>&quot;&gt;<br>  &lt;s:Body&gt;<br>    &lt;u:GetVolumeResponse xmlns:u=&quot;urn:schemas-upnp-org:service:RenderingControl:1&quot;&gt;<br>      &lt;CurrentVolume&gt;22&lt;/CurrentVolume&gt;<br>    &lt;/u:GetVolumeResponse&gt;<br>  &lt;/s:Body&gt;<br>&lt;/s:Envelope&gt;</pre><p>Now my goal is reached, I established some basic communication with the Sonos device and all other controls are straight forward.</p><h4>Learnings</h4><ul><li>The UPnP specification is easy understandable and the device and service description format is human readable</li><li>UPnP uses different (well known) protocols and is very powerful as it covers a wide application spectrum</li><li>The error code 402 (Invalid Args) occurred a few times, always without a pointer to the error. This can be nasty</li><li>It looks like the Sonos device is more open as many know</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e10e080a232" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL physical storage of rows]]></title>
            <link>https://blog.microfast.ch/postgresql-physical-storage-of-rows-da20a1389509?source=rss-bb447eceb1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/da20a1389509</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Boris Djurdjevic]]></dc:creator>
            <pubDate>Tue, 11 Oct 2016 17:38:07 GMT</pubDate>
            <atom:updated>2016-10-11T17:38:07.157Z</atom:updated>
            <content:encoded><![CDATA[<p>Data is money, data is business. After reading this you will know how and where PostgreSQL stores your important data.</p><h4>Directory structure</h4><p>PostgreSQL holds all of its data and configuration in one directory called <em>PGDATA</em> which you can find on most systems under <em>/var/lib/pgsql/data</em>/. There are three directories where tables will be stored:</p><ul><li>base: Databases in <em>pg_default</em> tablespace</li><li><em>global</em>: Cluster wide tables which don’t belong to a database e.g. <em>pg_authid</em> (tablespace <em>pg_global</em>)</li><li><em>pg_tblspc</em>: Symbolic links to other tablespaces, which can reside outside <em>PGDATA</em></li></ul><p>Every database has its own directory named after the <em>OID</em> (Object Identifier) which you can query with an SQL statement:</p><pre>postgres=# select datname, oid from pg_database;<br> datname    | oid <br> — — — — — -+ — — — -<br> template1  | 1<br> template0  | 12375<br> postgres   | 12380<br> djboris    | 16385<br>(4 rows)</pre><p>For this example we will have a look on table <em>pgbench_accounts</em> of database <em>djboris</em>.</p><pre>djboris=# \d pgbench_accounts<br>   Table &quot;public.pgbench_accounts&quot;<br>  Column  |     Type      | Modifiers <br>----------+---------------+-----------<br> aid      | integer       | not null<br> bid      | integer       | <br> abalance | integer       | <br> filler   | character(84) | </pre><p>Tables store its data in files usually named after tables <em>OID</em> which grow until 1 GB. Afterwards new files are created with an numeric suffix: <em>.1</em>, <em>.2</em> and so on. Because there are cases where the filename isn’t the <em>OID </em>but a <em>relfilenode </em>identifier, PostgreSQL offers the helpful function <em>pg_relation_filenode()</em> which shows the relative path to the basefile<em>.</em></p><pre>djboris=# select relname, relfilenode, relpages, reltuples, relallvisible, oid from pg_class where relname=&#39;pgbench_accounts&#39;;<br>-[ RECORD 1 ]-+-----------------<br>relname       | pgbench_accounts<br>relfilenode   | 16426<br>relpages      | 1640<br>reltuples     | 100000<br>relallvisible | 0<br>oid           | 16392</pre><pre>djboris=# select pg_relation_filepath(&#39;pgbench_accounts&#39;);<br>-[ RECORD 1 ]--------+-----------------<br>pg_relation_filepath | base/16385/16426</pre><p>Now we have the base path of the table. Every file within this path is somehow related to our table.</p><pre>[postgres@arch data]$ pwd<br>/var/lib/postgres/data<br>[postgres@arch data]$ ls -1 base/16385/16426*<br>base/16385/16426<br>base/16385/16426_fsm<br>base/16385/16426_vm</pre><p>You can ignore the 16426<em>_fsm</em> and 16426<em>_vm</em> file, which are the “<em>Free Space Map</em>” and “<em>Visibility Map</em>” and are not interesting in this case.</p><h4>Page layout</h4><p>Every table file consists of pages, which are 8 kB large and are divided as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*fj9EpKvox8hzQ6Dm1oTkKg.png" /><figcaption><a href="https://www.postgresql.org/docs/9.6/static/storage-page-layout.html">https://www.postgresql.org/docs/9.6/static/storage-page-layout.html</a></figcaption></figure><p>It’s important to mention, that the <em>ItemsIdData</em> array grows from top to down where the Items go bottom up. <em>ItemIdData</em> fields are used as pointers to the <em>Items</em> which in our case are table rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*nTbqVYefcaVP6tXc0MOnvA.png" /><figcaption>Simplified structure of a ”table” file with two pages, 2x3 ItemIdData and 2x3 Items</figcaption></figure><p>On the following picture you can see the hex dump of the first part (and first page of course) of <em>base/16385/16426</em>. Make sure to run <em>VACUUM FULL </em>before dumping it to ensure, that your first page isn’t empty when analysing it on your own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmhiQMwqBAx__vNbz8tTZw.png" /><figcaption>hexdump of base/16385/16426</figcaption></figure><p>The red and blue coloured parts are the <em>PageHeaderData</em> which is 24 bytes long. I’ve coloured the <em>pd_upper</em> and <em>pd_lower</em> fields blue, these describe where the <em>ItemIdData</em> struct array (green coloured) stops and the free space begins. The <em>pd_upper</em> points at the end of the free space, so it’s the beginning of the Item area.</p><p>You can find the following definition of type <em>ItemIdData</em> in <a href="http://doxygen.postgresql.org/structItemIdData.html">itemid.h</a>:</p><pre>lp_off:15,  /* offset to tuple (from start of page)*/<br>lp_flags:2, /* state of item pointer, see below */<br>lp_len:15;  /* byte length of tuple */</pre><h4>Getting Items</h4><p>As explained, the green ones act as pointers to the <em>Item</em>s, thus we will take the first one as an example and <a href="https://gist.github.com/djboris9/b3762a8a840cf35ac6684351c6db6965">calculate</a> the fields. This results in:</p><pre>ItemIdData: 0x809ff200<br>lp_off:     0x1f80<br>lp_flags:   0x0001<br>lp_len:     0x0079 (121 Bytes)</pre><p>Finally we found the Item at end of the page. But we don’t know the columns yet:</p><pre>00001f80: 7902 0000 0000 0000 0100 0000 0000 0000<br>00001f90: 0100 0400 020b 1800 0200 0000 0100 0000<br>00001fa0: 0000 0000 ab20 2020 2020 2020 2020 2020<br>00001fb0: 2020 2020 2020 2020 2020 2020 2020 2020<br>00001fc0: 2020 2020 2020 2020 2020 2020 2020 2020<br>00001fd0: 2020 2020 2020 2020 2020 2020 2020 2020<br>00001fe0: 2020 2020 2020 2020 2020 2020 2020 2020<br>00001ff0: 2020 2020 2020 2020 20      (121 Bytes)</pre><p>Now it’s time to disassemble our table structure by reading <em>pg_attribute.</em> You can ignore the virtual fields (<em>attnum</em>&lt;1) which aren’t part of the <em>Item</em> body.</p><pre>djboris=# select attname, attlen, attnum, attalign from pg_attribute where attrelid = 16392;<br> attname  | attlen | attnum | attalign <br>----------+--------+--------+----------<br> tableoid |      4 |     -7 | i<br> cmax     |      4 |     -6 | i<br> xmax     |      4 |     -5 | i<br> cmin     |      4 |     -4 | i<br> xmin     |      4 |     -3 | i<br> ctid     |      6 |     -1 | s<br> aid      |      4 |      1 | i<br> bid      |      4 |      2 | i<br> abalance |      4 |      3 | i<br> filler   |     -1 |      4 | i<br>(10 rows)</pre><p>Back to the hex-dump we have a header again (yellow). The last byte (Hex: 18) shows us the offset to data which is the 24st byte. There begin our columns in order of the seen <em>attnum</em> value ascending:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*mRP5QslA07-LIev1x3Exjg.png" /><figcaption>Item with header and fields separated</figcaption></figure><p>So you see the value 2 in our purple block, value 1 in the green, value 0 in the red and the <em>varlena</em> (<em>attlen</em>=-1) blue block. Did you look at the virtual fields from <em>pg_attribute</em>? There are by default not shown if you don’t specify them explicitly. <em>CTID</em> is a helpful one, because it’s value is (<em>pagenum</em>, <em>itemnum</em>) which means (page number index, <em>ItemIdData</em> index + 1).</p><pre>djboris=# select *, ctid from pgbench_accounts limit 1;<br>-[ RECORD 1 ]-----------------------------------------------------<br>aid      | 2<br>bid      | 1<br>abalance | 0<br>filler   | `many spaces`<br>ctid     | (0,1)</pre><p>We were in the first page and followed the first <em>ItemIdData</em> which gives us the reference (0, 1). Note that <em>pagenum</em> starts with zero, <em>itemnum</em> with one. This way, we can identify in which page and where an actual row is stored.</p><h4>Where to continue</h4><p>If you’ve wondered, how data which would span multiple pages can be stored, you have to study <a href="https://www.postgresql.org/docs/9.6/static/storage-toast.html"><em>TOAST</em></a> as it provides a solution for it. There are also other interesting structures like Indexes which are not covered. <a href="https://www.postgresql.org/docs/9.6/static/storage-vm.html"><em>Visibility Maps</em></a> and <a href="https://www.postgresql.org/docs/9.6/static/storage-fsm.html"><em>Free Space Maps</em></a> are also important for this database. MVCC stuff is also not covered so you don’t know if you are consistent. PostgreSQL has a good <a href="https://www.postgresql.org/docs/9.6/static/storage.html">documentation</a> and readable, well documented <a href="http://doxygen.postgresql.org/">source</a> in which you can find everything you need to dive deeper.</p><h4>Information</h4><p>At time of writing PostgreSQL 9.6 was used on a Linux <em>x86_64</em>. The purpose of this article is to wake up your interest and give you a general overview. This is far from complete. Many thanks to the PostgreSQL developers for this wonderful piece of software.</p><p>Many thanks <a href="https://github.com/karras">karras</a> for reviewing this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da20a1389509" width="1" height="1" alt=""><hr><p><a href="https://blog.microfast.ch/postgresql-physical-storage-of-rows-da20a1389509">PostgreSQL physical storage of rows</a> was originally published in <a href="https://blog.microfast.ch/">microfast</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>