<?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 Moshe Beladev on Medium]]></title>
        <description><![CDATA[Stories by Moshe Beladev on Medium]]></description>
        <link>https://medium.com/@moshe-beladev-mb?source=rss-c20127995873------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5wXzStiL_hj1FpR3GMGbWA.jpeg</url>
            <title>Stories by Moshe Beladev on Medium</title>
            <link>https://medium.com/@moshe-beladev-mb?source=rss-c20127995873------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:47:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@moshe-beladev-mb/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[o11y Done Wrong — Lessons Learned from Monitoring Production Systems]]></title>
            <link>https://medium.com/torq-io/o11y-done-wrong-lessons-learned-from-monitoring-production-systems-1d1024973eaf?source=rss-c20127995873------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d1024973eaf</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[Moshe Beladev]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 12:45:27 GMT</pubDate>
            <atom:updated>2023-07-20T12:45:27.202Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>o11y Done Wrong — Lessons Learned from Monitoring Production Systems</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIoWTWzlMbCFR5ZgM0WLiA.png" /></figure><p>You wake up dizzy at 3AM from your “nice friend” PagerDuty yelling, “I have something broken in production. Please come and help me!” You open one of your system monitoring dashboards, and the first feeling that comes up is, “What the heck is going on 🤯?”</p><p>Does that sound familiar?</p><p>I found myself in this exact situation, looking for a needle in a haystack in a bunch of metrics, visualizations and overwhelming data, which we all know is the worst enemy of our cognitive load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/0*tutErIyAmAPYKdKd" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VzpAVPAt_YCi4mxd" /><figcaption>Two approaches to visualize data. Where do you feel more of the cognitive load burden?<br>Image credit <a href="http://arngren.net/">Arngren</a>, <a href="https://xd.adobe.com/ideas/wp-content/uploads/2020/07/6-ways-to-reduce-cognitive-load-for-a-better-ui-3.png.webp">https://xd.adobe.com/ideas/wp-content/uploads/2020/07/6-ways-to-reduce-cognitive-load-for-a-better-ui-3.png.webp</a></figcaption></figure><p>In the following post, I will share with you what I learned after this incident, as well as a bit of our o11y stack and some practical tips to design, implement and maintain dashboards that I found very useful.</p><h3>Before we go forward, let’s go back</h3><p>At Torq, we help organizations automate their security workflows. That means that we handle a very critical and sensitive process in our customers’ organizations, and they trust us and our system’s reliability.</p><p>As a result, we invest a lot in monitoring our systems to make sure our critical services are healthy and, if not, to quickly pinpoint the problematic areas.</p><p>We utilize many tools to achieve our system o11y, but the core parts are:</p><h3>Metrics</h3><p>We collect metrics from our infrastructure services (K8S, Temporal, etc.) as well as some defined metrics for monitoring high-level or more focused events.<br>With Grafana &amp; Alert Manager, we visualize and alert on abnormal metrics streamed into Prometheus.</p><h3>Google Traces &amp; Logs</h3><p>These serve us for tracing requests between services, which is nicely integrated with Logs that we mainly use for error reporting (“no news = good news”).</p><p>We also created a super-cool open-source CLI tool called <a href="https://github.com/moshebe/gtrace">gtrace</a> to work with Google Traces much more effectively — but that’s for another post.</p><h3>Is what was good before, still good now?</h3><p>Let’s go back to the night when we had our lovely incident. After finding and fixing the issue, we went back to sleep and woke up the next morning to analyze what went wrong. The biggest problem I had, was that we had a dashboard filled with irrelevant data that caught my attention and made me spend time on it.</p><p>As a result, we decided to re-evaluate our monitoring dashboard and, more importantly, our monitoring strategy.</p><p>Here is a digestible list of the most valuable tips we found useful along the way:</p><p><strong>Define your KPI</strong> — how do you know if a latency of 500ms is good, bad, or normal? Setting a clear goal is important for every project, especially in your monitoring ones. You have to set a goal to know what you’re aiming for (be ambitious, but not too much). Sometimes, especially at the beginning, it’s hard to decide on those goals. My suggestion is to pinpoint something that is reasonable and schedule a self-revisit to tune it better.</p><p><strong>Graphs must answer a question</strong> — a dashboard should tell a story or answer a question. Make sure to keep them simple and focused on a specific question. This is another reminder to the great UNIX idiom of “do one thing and do it well.”</p><p><strong>Show only the most relevant information </strong>— if the question for the graph is “which servers are affected by an issue right now?” choose to display only the problematic ones instead of listing all the services and indicating which are healthy and which are not.</p><p><strong>Reviewing the process — </strong>as we do with code and design documents, getting feedback is a crucial part of keeping quality up, sharing knowledge, and making sure your teammates (and even future you) understand the dashboard and reduce the voodoo parts.</p><p><strong>Decide what you (do not) monitor</strong> — we have a lot to monitor, and this is the hard part, in my opinion. To keep things focused, we must decide what is important enough to be monitored and what is not. Too many alerts and data can take over our more important parts.</p><p>Last but not least, familiarizing yourself with prevalent monitoring approaches can assist in focusing and finding inspiration while constructing your dashboard and clarifying its objectives. Let’s explore several well-known methods and determine the best fit for each one.</p><p><strong>USE method</strong><br><em>Utilization</em>: % time the resource is busy (node CPU usage)<br><em>Saturation</em>: # work items the resource has to do (queue backlog)<br><em>Errors</em>: # of error events</p><p>This method is more focused on reporting causes of issues and is mostly used for infrastructure resources such as CPU, memory, network, etc.</p><p><strong>RED method</strong> <br>Rate: Requests per second<br>Errors: # of failed requests<br>Duration: time it takes for these requests to be handled</p><p>This method is more suitable for services, especially in a microservices environment. It is good for alerting and measuring SLAs. A well-designed RED dashboard can be a user-experience representation.</p><p>There is a nice quote by Grafana that I like: “The USE method tells you how happy your machines are, the RED method tells you how happy your users are.”</p><p><strong>The Four Golden Signals</strong><br>The great <a href="https://landing.google.com/sre/sre-book/chapters/monitoring-distributed-systems/#xref_monitoring_golden-signals">Google SRE handbook</a> states that if you can measure only 4 metrics of a user-facing system, your focus should be on these four:</p><ul><li>Latency: time taken to serve a request</li><li>Traffic: how much demand is placed on the system</li><li>Errors: rate of requests that are failing</li><li>Saturation: how “full” the system is</li></ul><p>This method is very similar to the RED one, but it also includes saturation.</p><p>Let’s take a look at how these theoretical concepts are represented in dashboards and visualizations.</p><h3>Playground time</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl41lKy6p2jDMyHuDe%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl41lKy6p2jDMyHuDe%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl41lKy6p2jDMyHuDe%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="332" frameborder="0" scrolling="no"><a href="https://medium.com/media/9532b539ecf11d827465892ffb48b009/href">https://medium.com/media/9532b539ecf11d827465892ffb48b009/href</a></iframe><p>Grafana Labs has introduced an innovative sandbox where users can test their query visualizations and be inspired by many examples. I’ll showcase some dashboards that effectively illustrate the concepts we discussed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y9oIL6k_4tIx2ENO" /><figcaption>Four Golden Signals visualization of a generic service</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tvTQHLzc8aX4ZLEh" /></figure><p>[When presenting data, it’s important to set a threshold to provide context to understand if the data falls outside of normal ranges]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n4EVlRJJXAHwaqBM" /><figcaption>Well-defined KPIs can aid in focusing on what really matters</figcaption></figure><p><strong>To Sum Up</strong></p><p>I hope you enjoyed learning about our approach to monitoring and that it sparked your interest in examining your own monitoring strategies. More importantly, I hope it prompted you to consider ways to make your response to future production incidents more streamlined and efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d1024973eaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/torq-io/o11y-done-wrong-lessons-learned-from-monitoring-production-systems-1d1024973eaf">o11y Done Wrong — Lessons Learned from Monitoring Production Systems</a> was originally published in <a href="https://medium.com/torq-io">torq</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure your Kubernetes Workloads with gVisor]]></title>
            <link>https://moshe-beladev-mb.medium.com/secure-your-kubernetes-workloads-with-gvisor-f189321792e1?source=rss-c20127995873------2</link>
            <guid isPermaLink="false">https://medium.com/p/f189321792e1</guid>
            <category><![CDATA[gvisor]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Moshe Beladev]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 08:00:27 GMT</pubDate>
            <atom:updated>2022-11-11T08:00:27.812Z</atom:updated>
            <content:encoded><![CDATA[<p>We are all familiar with and love containers. Containers share the same host kernel which makes them a pretty portable and lightweight solution. On the other hand, we would prefer to mitigate the risk of harming the host machine or operating system which can be achieved with sandbox technologies, and gVisor is one of them.</p><h3>Let’s start with some motivation</h3><p>Check out CVE-2020–14386 — it is a Linux kernel vulnerability resulting in container escape. Basically, this vulnerability takes advantage of the CAP_NET_RAW capability to cause memory corruption resulting in attacker root access.</p><p>In Docker, this capability is enabled by default (I believe is it probably due to the fact that it is commonly used by networking tools such as ping and tcpdump and might be re-enabled for troubleshooting purposes)</p><p>Workloads that run with gVisor were not affected by this CVE — which leads us to our next part: understand <strong>what is gVisor and how we can enjoy it too</strong>.</p><h3>What is gVisor?</h3><p>A gVisor container runtime sandbox is an environment of processes to run containers.<br>It’s basically an application kernel (written in Go 🎉) that implements a substantial portion of the Linux system call interface and provides an additional layer of isolation between running applications and the host operating system.<br>This architecture provides significant security while lowering the cost associated with virtualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*ABPGZ0DoZOCqXYaC" /></figure><h3>How does it work?</h3><p>Each sandbox has its own isolated instance of <strong>Sentry</strong> and <strong>Gofer</strong>.</p><p><strong>Gofer — provides file system access to the containers<br></strong>Host process that starts with each container. Communicates with the Sentry. The Sentry process is started in a restricted seccomp container without access to file system resources. The Gofer mediates all access to these resources, providing an additional level of isolation.</p><p><strong>Sentry — application kernel for the containers<br></strong>Supplying all the kernel functionality needed by the application, including system calls, signal delivery, memory management, and more.<br>When the application makes a system call, the calls are redirected to the Sentry, which will do the necessary work to service it.</p><p>For example, the Sentry is not able to open files directly: file system operations that extend beyond the sandbox are sent to the Gofer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*o-H4_JRp6NoQFfPm" /></figure><p><strong>Platform &amp; runsc<br></strong>The gVisor P<a href="https://gvisor.dev/docs/user_guide/platforms/">latform</a> implements interception of syscalls, basic context switching, and memory mapping functionality.</p><p>The entrypoint to running a sandboxed container is runsc executable. runsc implements the <a href="https://www.opencontainers.org/">OCI</a> runtime specification, which is used by Docker and Kubernetes resulting in such a seamless integration.<br>By configuring the runsc context we can choose between a number of implementations for the platform:</p><p><strong>ptrace</strong> — utilizing <a href="https://man7.org/linux/man-pages/man2/ptrace.2.html">PTRACE_SYSEMU</a> to execute user code without allowing it to execute host system calls. Very common utility and it’s usually the better choice when running inside a VM or when virtualization is not supported.</p><p><strong>KVM</strong> — using <a href="https://www.linux-kvm.org/page/Main_Page">Linux KVM</a> to allow the sentry to act as both Guest OS and VMM (which is responsible for creating and managing VMs on the physical host machine). Will provide better performance and will mostly be used on bare-metal and not under a virtual machine.</p><p><strong>GKE Sandbox</strong> — uses a custom platform implementation that provides better performance than ptrace and KVM.</p><h3>What’s wrong with the existing container security tools?</h3><p>That’s a good question. AppArmor, SELinux, and Seccomp are some great examples of such tools that can help us specify fine-grained policies for applications with native performance. They mostly rely on hooks implemented in the kernel for enforcement. <br>Also, besides the additional overhead, we might face there are some <a href="https://gvisor.dev/docs/user_guide/compatibility">compatibility issues</a> with gVisor.</p><p>Having said that, in practice, it’s extremely difficult to define it universally which makes it usable for very few applications where the application surface is small enough to define a tailor-made security policy.</p><h3>I am convinced, how can I have it?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fgvrnmr6mzJXBm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fgvrnmr6mzJXBm%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fgvrnmr6mzJXBm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9c7729acaa4fcacaf4e5077b80f5349/href">https://medium.com/media/a9c7729acaa4fcacaf4e5077b80f5349/href</a></iframe><p>Thanks to the OCI runtime specification, integrating gVisor is a piece of cake. Let’s demonstrate how you can run (and validate) your secure workflows on GKE with a few steps:</p><ol><li>Make sure you have a node pool with gvisor sandbox enabled. For example, if the CLI command is used make sure to include the --sandbox type=gvisor (See: <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/sandbox-pods">https://cloud.google.com/kubernetes-engine/docs/concepts/sandbox-pods</a>)</li></ol><pre>gcloud container node-pools create smt-enabled \<br>    --cluster=CLUSTER_NAME \<br>    --machine-type=MACHINE_TYPE \<br>    --node-labels=cloud.google.com/gke-smt-disabled=false \<br>    --image-type=cos_containerd \<br>    --sandbox type=gvisor</pre><p>2. Verify gVisor is enabled. Can be done using the following command:</p><pre>› kubectl get runtimeclasses<br>NAME     HANDLER   AGE<br>gvisor   gvisor    1d</pre><p>if you find gvisorruntime class like the above — it’s a good sign.</p><p>3. Make sure your pod spec YAML fieldspec.template.spec.runtimeClassName is set to gvisor. For example:</p><pre># httpd.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: httpd<br>  labels:<br>    app: httpd<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: httpd<br>  template:<br>    metadata:<br>      labels:<br>        app: httpd<br>    spec:<br>      <strong>runtimeClassName: gvisor</strong><br>      containers:<br>      - name: httpd<br>        image: httpd</pre><p>Tip specifically for GKE to make sure all your configuration is wrapped up together — you can kubectl exec your workload pods and make sure this command will return an empty response:</p><pre><strong>curl -s &quot;http://metadata.google.internal/computeMetadata/v1/instance/attributes/kube-env&quot; -H &quot;Metadata-Flavor: Google&quot;</strong></pre><h3>To Sum Up</h3><p>gVisor can be a great solution to secure your workloads with a super-easy setup on Docker and Kubernetes environment thanks to the <a href="https://github.com/opencontainers/runtime-spec">OCI runtime spec</a>. Enjoy your newly (more) secured workloads!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f189321792e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips For Effective Go Tests]]></title>
            <link>https://moshe-beladev-mb.medium.com/tips-for-effective-go-tests-6b9f1e242f02?source=rss-c20127995873------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9f1e242f02</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Moshe Beladev]]></dc:creator>
            <pubDate>Tue, 31 Aug 2021 06:46:45 GMT</pubDate>
            <atom:updated>2021-08-31T07:46:24.150Z</atom:updated>
            <content:encoded><![CDATA[<p>Skipping tests is common practice, especially in startups that sacrifice testing in favor of rapid development. We all know that this is not a best practice, but yet we still do it. A great solution incorporating testing in a fast-paced SDLC is to embed testing in the lifecycle. I’ll explain the benefits of this approach and provide some practical tips.</p><h3><strong>Why</strong></h3><p>It’s counterintuitive, but I believe that when embedded testing is implemented correctly, the velocity of the development lifecycle will improve, not decline. When you write your own tests, you’re sort of the first beta tester for your code, which results in improved, decoupled, and more reliable code.<br>Last but not least, tests with a wide coverage build the developer’s confidence to refactor on the fly and reduce the legacy code that we really should be maintaining. This will dramatically improve code velocity and reliability.</p><h3><strong>What</strong></h3><p>First and foremost, we need to define the scope of our tests. When writing a simple utility function, it might be convenient to use a unit test that tries using valid and invalid inputs. Struggling to write a unit test for such a function might be a good opportunity to re-check our dependencies, and perhaps even rethink our design altogether.</p><p>A good example of a test that should be out of scope is when you use an external, 3rd-party email service. There’s no need to test this (you can easily do this using an E2E, but that’s a story for another blog) since we can assume it has already been tested quite well by its developers. In this case, you just need to make sure your code handles success and failure cases as you expected.</p><p>A well-defined testing scope frees up your time and enables you to direct your energies where they’re needed. And most importantly, it ensures you will not overcomplicate your tests code.</p><h3><strong>How</strong></h3><p>Testing is an endless topic, so how do we attack it? I’m going to focus on some best practices that will help you make a great return out of your testing efforts.</p><p><strong>Testable Code</strong></p><p><em>Global State<br></em>Just avoid it whenever possible. It makes parallelism cumbersome and might affect subsequent tests. Let each test initialize its own instance to work on, it may take a few additional lines of code, but I assure you it&#39;s worth it.</p><p><em>Configuration<br></em> Many times we find ourselves using constants like server listening ports, timeouts, paths to configurations files, and many others. Make those parameters configurable so your tests will have more flexibility. Remember that tests run as part of your package so you also have the option to include them without export to external usage.</p><p><em>Immutability</em><br>Make sure you have minimum side effects and mutations to the current state. For example, putting values inside environment variables can affect our subsequent test runs so we need to think carefully if we do want it.</p><p><strong>Interfaces &amp; Mocks</strong></p><p>From your service perspective, you need to make sure that your code will handle external interactions correctly. Defining the behavior of the external service not only will prevent you from vendor-lock but also can be easily converted to a mock implementation that can behave just the way you want for each test. To generate the mock code you can use this tool: <a href="https://github.com/golang/mock">https://github.com/golang/mock</a></p><p><strong>Test Containers</strong></p><p>A mock is nice, but there’s nothing like the real McCoy. For a good integration test, set up your dependencies as containers whenever possible. You can find a lot of ready-to-use examples of using PostgreSQL, Redis, MongoDB, Cassandra, and more here: <a href="https://github.com/ory/dockertest">https://github.com/ory/dockertest</a>.<br>Running a local PostgreSQL is as easy as this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2RUr8js3VXeHL5_qhkOVw.png" /><figcaption>from ory/dockertest examples</figcaption></figure><p><strong>Text Fixtures &amp; Golden Files</strong></p><p>Tests can hold ancillary data, just put your files under a directory named testdata, the go tooling will ignore this directory.</p><p>The files can be easily accessed because go test run with the package directory as the current working directory so your code use relative paths.</p><p>It is the right place to put large textual or binary content for both inputs and expected results, which are called <em>golden files.</em></p><p>Putting those files separately helps you watch and edit in the right context, for example, JSON can be formatted and highlighted using your favorite editor instead of holding it as a giant string inside the test code.</p><p>Also, by staging the test results as part of our Git repository we can track the changes on our desired result for each pull request, which is super convenient.</p><p><strong>Table Driven Tests</strong></p><p>Make it a rule of thumb that tests should have more than one test case. You can always check for both valid and invalid input for example but most importantly in my opinion is preparing the ground for future extensions of your test functions.<br>Let’s write a simple Reverse() function and write table-driven tests for it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwwubFMJCtsuEdOvr9wEjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuqb_96WPtPvPBJg3_T9IA.png" /><figcaption>specific test can be run using: go test -run=TestReverse/&lt;name&gt;</figcaption></figure><p><strong>Coverage</strong></p><blockquote><em>Test coverage is a term that describes how much of a package’s code is exercised by running the package’s tests. If executing the test suite causes 80% of the package’s source statements to be run, we say that the test coverage is 80%.</em></blockquote><p>Thanks to the amazing Go tooling system, it is super easy to get a summary measurement of our code. Let’s run it on our previous Reverse example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGQtBY9psQp_uttq6uJV2A.png" /></figure><p>Okay, the percentage is great and gives us a sense of how much code our tests have been covered. But we can dig deeper and identify the specific branches in our code that are not covered.</p><p>Running the following command will open the report we’ve just created in the browser and clearly displays the uncovered parts of our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FoFW_5cMHVguCdt6" /><figcaption>go tool cover -html=coverage.out</figcaption></figure><p>To cover this missing case we just need to add a suitable case to our table test cases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMojk8QJS_JeiG2qLeYHpQ.png" /></figure><p>Running the go tool command again will result with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gyITFAgHcza3jv0I" /></figure><p>Perfect! We got our code fully covered and it was super simple thanks to our table-driven test.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl3q2LH45XElELRzRm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl3q2LH45XElELRzRm%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl3q2LH45XElELRzRm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="294" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ed2580bdf9f21035c418cc73ee21077/href">https://medium.com/media/9ed2580bdf9f21035c418cc73ee21077/href</a></iframe><h3><strong>Summary</strong></h3><p>When implemented properly and with a purposeful scope, writing testable code will result in a clean, de-coupled, and maintainable code, without compromising on velocity. After a few cycles, you’ll wonder how you have lived without it.</p><h4>References</h4><p>[-] <a href="https://speakerdeck.com/mitchellh/advanced-testing-with-go?slide=6">https://speakerdeck.com/mitchellh/advanced-testing-with-go?slide=6</a><br>[-] <a href="https://about.sourcegraph.com/go/advanced-testing-in-go/">https://about.sourcegraph.com/go/advanced-testing-in-go/</a><br>[-] <a href="https://www.youtube.com/watch?v=8hQG7QlcLBk">https://www.youtube.com/watch?v=8hQG7QlcLBk</a> <br>[-] <a href="https://dave.cheney.net/2016/05/10/test-fixtures-in-go">https://dave.cheney.net/2016/05/10/test-fixtures-in-go</a><br>[-] <a href="https://blog.golang.org/cover">https://blog.golang.org/cover</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9f1e242f02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debug AWS Lambda Functions with Gebug]]></title>
            <link>https://moshe-beladev-mb.medium.com/debug-aws-lambda-functions-with-gebug-bc643788c247?source=rss-c20127995873------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc643788c247</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Moshe Beladev]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 13:11:20 GMT</pubDate>
            <atom:updated>2021-01-20T16:24:39.388Z</atom:updated>
            <content:encoded><![CDATA[<p>Debugging your Golang Lambda locally can be really annoying. You have great tools on your machine but you don’t always get the most out of them.</p><p>I experienced with Serverless Application Model (sam local) and it was actually really nice but was not there yet, at least for Go.</p><p>Some elementary features like auto-build and live code updates were missing and the development experience was not as smooth and fast as I wished it would be.</p><p>Quote from `sam local start-api` <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-start-api.html">documentation</a>:</p><blockquote>If you’re using an interpreted language, local changes are available immediately in the Docker container on every invoke. <strong>For more compiled languages or projects that require complex packing support, we recommend that you run your own building solution, and point AWS SAM to the directory or file that contains the build artifacts</strong>.</blockquote><p>So we will embrace their suggestion and build our own complex packing support. Fortunately, with Gebug it won’t be complex at all.</p><blockquote>Gebug is an open-source tool that makes debugging of Dockerized Go applications super easy by enabling Debugger and Hot-Reload features. Check it out: <a href="https://github.com/moshebe/gebug">https://github.com/moshebe/gebug</a></blockquote><h3>How it’s done</h3><p>(If you don’t mind how it works behind the scenes, just jump to the setup instructions, no hard feelings)</p><p>AWS released a very interesting project called <a href="https://github.com/aws/aws-lambda-runtime-interface-emulator">AWS Lambda Runtime Interface Emulator</a> (a.k.a <em>aws-lambda-rie</em>) which is basically a proxy for the Lambda’s runtime.</p><p>Think about it, you are able to invoke your function using an HTTP trigger locally but you didn’t set up either a web-server to handle the request or a parser to translate the payload into JSON and structs that fit into the Lambda Runtime API.<br>You guessed right, <em>aws-lambda-rie</em> is a tiny web-server that handles the invocation stuff for us.<br>Be aware that it does not presume to simulate a full Lambda environment but only the invocation part, which for most of the common debugging scenarios that’s all you need. Thus, you won’t find orchestration, security, or authentication simulations here.</p><p>In order to install the tool in your local development Docker image you can start by downloading the binary from here:<br><a href="https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie">https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie</a></p><p>We will add a Gebug pre-run-command that will download the binary, enable execution, and put it in the right place:</p><pre>pre_run_commands:<br>- curl -sLo /tmp/aws-lambda-rie <a href="https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie">https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie</a> &amp;&amp; mv /tmp/aws-lambda-rie /usr/local/bin/aws-lambda-rie &amp;&amp; chmod +x /usr/local/bin/aws-lambda-rie</pre><p>on a real AWS Lambda environment, our Lambda binary will be placed at <em>/var/task</em> so we will set the following configurations as well:</p><pre>build_command: go build -o /var/task/main<br>output_binary: /usr/local/bin/aws-lambda-rie /var/task/main</pre><h3>Setup Instructions</h3><p>Ok, I don’t want to waste your time anymore so I’ll just share with you the complete Gebug configurations:</p><p><em>.gebug/config.yaml</em></p><pre>name: lambdagebug<br>output_binary: /usr/local/bin/aws-lambda-rie /var/task/main<br>build_command: go build -o /var/task/main<br>build_dir: /src<br>run_command: &#39;{{.output_binary}}&#39;<br>runtime_image: golang:1.15.2<br>debugger_enabled: false<br>debugger_port: 0<br>expose_ports:<br>- 8080:8080<br>networks: []<br>environment: []<br>pre_run_commands:<br>- curl -sLo /tmp/aws-lambda-rie <a href="https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie">https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie</a> &amp;&amp; mv /tmp/aws-lambda-rie /usr/local/bin/aws-lambda-rie &amp;&amp; chmod +x /usr/local/bin/aws-lambda-rie</pre><p>I used a really simple hello-world Lambda just for the demo:</p><p><em>main.go</em></p><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;context&quot;<br>    &quot;github.com/aws/aws-lambda-go/lambda&quot;<br>)</pre><pre>type Event struct {<br>    Name string `json:&quot;name&quot;`<br>}</pre><pre>func HandleRequest(ctx context.Context, event Event) (string, error) {<br>    return fmt.Sprintf(&quot;Hello %s&quot;, event.Name), nil<br>}</pre><pre>func main() {<br>    lambda.Start(HandleRequest)<br>}</pre><p>Now, just simply run <em>gebug start</em> and you can start accessing your Lambda locally using a simple HTTP endpoint.</p><pre>curl -XPOST &quot;<a href="http://localhost:8080/2015-03-31/functions/function/invocations">http://localhost:8080/2015-03-31/functions/function/invocations</a>&quot; -d &#39;{}&#39;</pre><h3>Demo</h3><p>Seeing is believing. Watch a short demo to feel how simple it is to get your local Lambda debugging environment to become really awesome:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNMrVS3u2O7bPiit_vJzzQ.gif" /><figcaption>Live code update of Go Lambda Function</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc643788c247" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Debugging Environment for your Micro-Services]]></title>
            <link>https://moshe-beladev-mb.medium.com/better-debugging-environment-for-your-micro-services-9420a71b8a37?source=rss-c20127995873------2</link>
            <guid isPermaLink="false">https://medium.com/p/9420a71b8a37</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[telepresence]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gebug]]></category>
            <dc:creator><![CDATA[Moshe Beladev]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 10:35:48 GMT</pubDate>
            <atom:updated>2020-10-01T10:35:48.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Debugging a micro-service in a Kubernetes cluster can be a real pain.<br>Sometimes we face burdensome bugs which might be hard to reproduce in a non-realistic environment.<br>What if I told you debugging on your local machine with your favorite tools feeling like your service is running remotely inside your cluster is just a few command-lines away?</p><h3>Meet the Tools</h3><p>In order to reach our desired environment I’ll mainly use the following tools:<br>- <a href="https://github.com/moshebe/gebug">Gebug</a>: an open-source tool that makes debugging of Dockerized Go applications much easier by enabling hot reload and debugger configurations (Disclaimer: I’m this tool’s author 😊)<br>- <a href="https://www.telepresence.io/">Telepresence</a>: an amazing CNCF project which helps us set up network tunneling with our cluster network</p><p>In my book, the best way to get familiar with a new tool is by getting your hands dirty. So, let’s set up our demo environment.</p><h3>Kubernetes cluster</h3><p>We’ll use a tiny Kubernetes cluster running a “hello-world” deployment and an exposed service.<br>For the demo’s sake, I’ll use minikube. If you have a cluster up and running (and it’s not a production one) you can use it too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8102b87437171b84c6da8ae0aa82ed/href">https://medium.com/media/be8102b87437171b84c6da8ae0aa82ed/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3aQseNFvSTDM2Brm9hWZNQ.png" /><figcaption>Our current Kubernetes cluster state</figcaption></figure><p>We can retrieve our service external endpoint and run a little test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlNX_1KVLsWI0t9g3POcYA.png" /><figcaption>We retrieve the external address using minikube command. It can be also done via `kubectl get service hello world` and look for the EXTERNAL_IP field</figcaption></figure><h3>Hello-World Service</h3><p>Our hello-world deployment is nice. But, let’s say we want to change the HTTP response to a JSON one.<br>You can of course compile your application, build a Docker image, push it, edit the deployment, and… you get it.<br>We’re here to make things faster and more fun.</p><p>This will be our tiny HTTP server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d222aecbc643bca32c7b38a0cb9d195/href">https://medium.com/media/7d222aecbc643bca32c7b38a0cb9d195/href</a></iframe><p>Along with the following Gebug configurations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1db3caea470ccd157d6e930ea3d37694/href">https://medium.com/media/1db3caea470ccd157d6e930ea3d37694/href</a></iframe><blockquote>If you don’t have Gebug installed you can simply run: <br>go get -u github.com/moshebe/gebug</blockquote><h3>Telepresence</h3><p>This awesome tool enables us to connect our service to the cluster without the hassle of the network configuration.</p><blockquote>The Installation Guide can be found here: <a href="https://www.telepresence.io/reference/install">https://www.telepresence.io/reference/install</a></blockquote><p>The next step in exposing our local service and rewire the traffic to and from the cluster so we replace the existing deployment.</p><p>Our deployment name is “hello-world” and the exposed port is 8000. So the command we should use will be something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4df2ab0ab157d95d079c7271a1d1d2ee/href">https://medium.com/media/4df2ab0ab157d95d079c7271a1d1d2ee/href</a></iframe><p>This command does a few things:</p><ul><li>Starts a VPN-like process that sends queries to the appropriate DNS and IP ranges to the cluster.</li><li>— swap-deployment tells Telepresence to replace the existing hello-world pod with one running the Telepresence proxy. On exit, the old pod will be restored.</li><li>The —-run option tells Telepresence to run the Gebug tool along with our service and hook it up to the networking proxy.<br>As long as you leave the HTTP server running inside telepresence it will be accessible from inside the Kubernetes cluster.</li></ul><h3>It’s Show Time</h3><p>Let’s see how can we grab a request that sent to our Kubernetes exposed endpoint, catch it using a breakpoint and return the result we want</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGVyyysLO4CcQHqJTTMiWw.gif" /></figure><p>That’s it. I hope you benefited and learned some new techniques to improve your micro-services debugging.</p><p>Feel free to contact me for any kind of question!</p><p>References:<br>[Gebug — <a href="http://github.com/moshebe/gebug">http://github.com/moshebe/gebug</a>]<br>[Telepresence — <a href="https://www.telepresence.io/tutorials/kubernetes">https://www.telepresence.io/tutorials/kubernetes</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9420a71b8a37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containers Under The Hood]]></title>
            <link>https://moshe-beladev-mb.medium.com/containers-under-the-hood-68ed9d0676ef?source=rss-c20127995873------2</link>
            <guid isPermaLink="false">https://medium.com/p/68ed9d0676ef</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Moshe Beladev]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 18:56:07 GMT</pubDate>
            <atom:updated>2020-06-06T19:01:29.993Z</atom:updated>
            <content:encoded><![CDATA[<p>The containers eco-system raises a huge hype, almost every infrastructure contains a sleek Kubernetes cluster or at least some Docker containers running in the wild.</p><p>I think containers are a great tool for deploying your software without worrying about issues like missing dependencies and services coordination for example. But, have you ever wondered what’s underneath the hood?</p><p>Let’s take a look on the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIgXLvTDpr96qQgjMV1Eaw.png" /></figure><p>Curiously, we got a new shell on something that looks like another machine (believe me, it’s not). Even more interesting, when running ps we can see only our process and it appears with PID 1 which usually assigned to init/systemd.</p><p><strong>File System</strong>:</p><p>One of the great advantages of containers is the ease and consistency of your deployment. No more missing libraries or other dependencies — You get your application battery-included.</p><p>The Docker image is just a bundle that includes a filesystem with some meta-data. All we have to do is just manipulate the process’s file system point of view.</p><p>There are two techniques for achieving this part: chroot and pivot-root.<br>chroot is a syscall that changes the root directory for a process, whereas pivot-root changes the root directory for all the processes in our mount namespace (if you got scared from the term &quot;namespace&quot;, don&#39;t worry we will soon cover it).</p><p>One of the reasons pivot-root is preferred over chroot is the fact that the latter is more vulnerable to escaping (mostly because the old root is still accessible) while with pivot-root you can umount it.</p><p>When we run multiple container instances we don’t really need to clone the whole image which can be very expensive. This is where <strong>CoW</strong> (Copy-On-Write) and the <strong>Layered file system </strong>come<strong> </strong>to<strong> </strong>the rescue.</p><p>The CoW concept is very simple: all instances share the same common layer and once someone needs to make a change it will get his own copy and do whatever he wants there without bothering the other instances. Then, instead of copying the whole image upon a change, we can use a common read-only branch and the new changes will be in a different layer (this is the basic idea, you can read more about <a href="https://wiki.archlinux.org/index.php/Overlay_filesystem">overlayfs</a> as it is now part of the mainline kernel)</p><p>Another important concept in terms of the file system is mounts, or more specifically “bind mount” which basically maps between two inodes in the VFS (<a href="https://en.wikipedia.org/wiki/Virtual_file_system">Virtual File System</a>).</p><p>There are a few modes of this mount type, which are differentiated by the way events are synchronized between the two nodes we link:<br>- <em>shared</em>: all the replicas are fully synchronized<br>- <em>slave</em>: only mount and umount events are passed in one direction<br>- <em>private</em>: no propagations will be received or forwarded<br>- <em>unbindable</em>: like private + other bindings are forbidden</p><p>This mount is really useful in cases where you want to use external configurations or volumes for the container (e.g: /tmp as writable storage)</p><p>Cool, so we know how the dependencies are handled. But, why don’t we see other processes when running ps? That is where <a href="https://en.wikipedia.org/wiki/Linux_namespaces"><strong>Linux Namespaces</strong></a> fit in.</p><p>Namespaces is a Linux feature that enables us to isolate our process and create a restricted view of system resources like network interfaces, mounts, and processes. This isolation is good not only for security and access control but also for making sure that we won’t collide with other applications or services on the same host, and get a consistent point of view.</p><p>There are some syscalls that help manage those namespaces:<br>clone - Creates a new process in a new namespace<br>unshare - Creates a new namespace for the current process<br>setns - Change process namespace by a given namespace file descriptor</p><p>Here is a list of some Linux namespaces you should be familiar with:<br>- Mount: filesystem mount points<br>- UTS: host and domain names<br>- IPC: interprocess communication resources<br>- PID: processes tree<br>- Network: network interfaces<br>- User: UID/GID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2O7vFRfXtBrgBVB9rgNUQ.png" /><figcaption>We can list our process namespaces which are accessible by /proc/&lt;pid&gt;/ns</figcaption></figure><p>So, we have pretty good isolation (not really) with those namespaces. But what will happen if one process will start to hog the RAM? His neighbor containers will probably not like it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FbRAGIMlRM39GE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FbRAGIMlRM39GE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FbRAGIMlRM39GE%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="420" frameborder="0" scrolling="no"><a href="https://medium.com/media/f220814a3618f1dd7e68b7ab902097a6/href">https://medium.com/media/f220814a3618f1dd7e68b7ab902097a6/href</a></iframe><p>It’s time to meet Control Groups (aka <strong>cgroups</strong>) — a Linux mechanism that helps us manage system resources like CPU, memory, and network by setting quotas and access control.</p><p>In order to enter a process to the group (or more generally — task, which can also be a thread) you just need to write its id to the relevant task file:</p><pre>/sys/fs/cgroup/&lt;resource-type&gt;/&lt;user-class&gt;/tasks</pre><p>and from now on, the cgroups configuration will be applied to your process.</p><p>Pay attention that when you create a directory inside sys/fs/cgroup the kernel will auto-fill it with default values.</p><p>For example, if you want to change the maximum allowed RAM a process can consume it can be achieved by simply writing the desired limit to /sys/fs/cgroup/memory/&lt;name&gt;/memory.limit_in_bytes and that’s it, the cgroups mechanism will take it from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_i10sWZJEI-p28_9O42B_Q.png" /><figcaption>Nice way to get our process memory usage, can be very useful for monitoring and profiling</figcaption></figure><p>A few words about security. We should now have an understanding that container and Virtual Machines are two different things, given the fact the containers share the host’s kernel/OS which makes it easier to break out. I’ll briefly explain some of the common tools and technologies that try to make the attacker’s life harder:<br>- AppArmor/SELinux — they are both LSM (<a href="https://en.wikipedia.org/wiki/Linux_Security_Modules">Linux Security Module</a>) implementations that supply us MAC (<a href="https://en.wikipedia.org/wiki/Mandatory_access_control">Mandatory Access Control</a>) that is used to whitelist/blacklist access to resources<br>- Seccomp — allows us to set up syscalls filters<br>- Capabilities — breaking up the monolithic root privilege so we can reduce the risk of that by compromising a single process the attacker gets full control</p><p><strong>Let’s Get Our Hands Dirty</strong></p><p>After discussing the containers theory, let’s implement a minimal container runtime using the concepts we just overviewed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f807a3008fc0abadf7ff759f14434f/href">https://medium.com/media/87f807a3008fc0abadf7ff759f14434f/href</a></iframe><p>First, we need to make sure we don’t see the host process anymore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCG4bVObFY_SYUaom19FWQ.png" /></figure><p>Now, let’s check if our memory limit (~100MB) is handled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkbziL5cv5a6-lMc_3yfMQ.png" /><figcaption>we can see that our process was killed when it tried to allocate more memory than it allowed to</figcaption></figure><p>Voila! we got our minimal container up running and functional the way we want.</p><p>A few things to mention:</p><ul><li>The code is written in Go but can be implemented in many other ways.</li><li>you should NOT implement your own container runtime. This example looks functional and running but we did some tricks in order to keep the code clear and simple (for example we wrote the cgroups attributes in the container process which means one can change it if he wants to exceed the limitation, we used chroot instead of pivot-root etc.)</li></ul><p>I hope now you better understand what container means and how it works internally. There is a lot more to cover but I think it’s a really good start and you can take it from here.</p><p>Feel free to contact me for any question, correction or just to talk :-)</p><p>References:<br>[<a href="https://blog.gojekengineering.com/building-containers-from-scratch-c2368a8c8701">https://blog.gojekengineering.com/building-containers-from-scratch-c2368a8c8701</a>]<br>[<a href="https://www.youtube.com/watch?v=8fi7uSYlOdc">https://www.youtube.com/watch?v=8fi7uSYlOdc</a>]<br>[<a href="https://ericchiang.github.io/post/containers-from-scratch/">https://ericchiang.github.io/post/containers-from-scratch</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68ed9d0676ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Watch out for Compiler Optimizations]]></title>
            <link>https://moshe-beladev-mb.medium.com/watch-out-for-compiler-optimizations-bdd027071843?source=rss-c20127995873------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdd027071843</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[compilation]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Moshe Beladev]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 13:41:04 GMT</pubDate>
            <atom:updated>2019-07-02T14:22:17.572Z</atom:updated>
            <content:encoded><![CDATA[<p>Every compiler, including Golang’s, optimizes our code to an extent. This makes our build faster and outputs a smaller and probably more efficient binary.</p><p>However, I believe that sometimes you should take a look under the hood to understand how things work. It will surely step up your programming and debugging skills.</p><p>Recently I faced a really strange behavior while benchmarking one of the functions I wrote:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*gUwNtacamCHwyHDQiC2wFQ.png" /><figcaption>0.31 ns/op is extremely fast, even for our super-efficient function 😆</figcaption></figure><p>Although it made me happy thinking my code runs so fast, I figured out that probably something went wrong and the test is misleading so I started digging for answers for this phenomenon.</p><p>Let’s start with a simple feature: <strong>Function Inlining</strong>.</p><h3>What Does It Mean?</h3><p>The compiler takes our function’s code and substitutes it with the function calls.</p><h3>Why Inline At All?</h3><p>Function call has its own burden of creating a new stack frame which generally includes:</p><ul><li>Return address</li><li>Argument variables passed on the stack</li><li>Local variables</li><li>Modified registers</li></ul><p>All of the above, affect our program execution with unwanted operations.</p><p>To make our application even faster, the compiler comes to the rescue and changes the code to include the function’s content on each call.</p><p>We need to remember there are always some strings attached and in our case, it results with a larger output binary which has its own cons as well.</p><p>Hence, most of the compilers define a threshold (which you can play with) that determines whether or not to inline the function.</p><p>From <a href="https://github.com/golang/go/wiki/CompilerOptimizations#function-inlining">Go Wiki</a>:</p><blockquote><em>Only short and simple functions are inlined. To be inlined a function must contain less than ~40 expressions and does not contain complex things like function calls, loops, labels, closures, panic’s, recover’s, select’s, switch’es, etc.</em></blockquote><h3>Talk Is Cheap, Show Me The Code!</h3><p>First, let’s implement a really cool and efficient sine approximation called <a href="https://en.wikipedia.org/wiki/Bhaskara_I&#39;s_sine_approximation_formula">Bhaskara I’s</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzB0GVPn8CGZnSnfQHKOTw.png" /></figure><p>Using the gcflags -m option for go build may reveal some inner compiler decisions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6cTrJnn9Sou8GQcouPkLw.png" /><figcaption>I found many useful Go tools tricks <a href="https://rakyll.org/go-tool-flags/">here</a></figcaption></figure><p>Cool, the compiler inlined our function. Now we can dive deeper and inspect the build disassembly using the -S flag to see how our functions are translated and disable the compiler optimizations using the -N flag to reduce uncertainty.</p><pre>$ go build -gcflags &#39;-S -N&#39; main.go 2&gt;&amp;1</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F7E2sUE4OTJCicIgiur%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F7E2sUE4OTJCicIgiur%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F7E2sUE4OTJCicIgiur%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/51caf247d691769e70fba57cb16a5562/href">https://medium.com/media/51caf247d691769e70fba57cb16a5562/href</a></iframe><p>You can watch the full output in your terminal, but for the sake of readability I’ll <strong>filter the output</strong> a bit so we can take a look only at the parts that are important for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9c6c082aa31b38b09ea503d812c6f0c/href">https://medium.com/media/f9c6c082aa31b38b09ea503d812c6f0c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou6UNnz-O4F4yg0vCCW7yg.png" /><figcaption>We can see part of the disassembled main function’s code</figcaption></figure><blockquote>The command output is not a final machine code. For example, we can see the FUNCDATA and PCDATA which use as hints for the linker&#39;s garbage collecting arrangements. For our purpose, we can simply ignore them.</blockquote><p>To understand how the optimizations processes affect our code, I’ll re-do the previous step without disabling the compiler optimizations. Let’s see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLDcm53QX8E44UGQMnHJwQ.png" /><figcaption>The operations that were in the main function vanished and only an immediate return remained</figcaption></figure><p>If you already checked the output, you probably noticed a strange thing — Our <strong>main function is empty</strong>!</p><h3>Why Does This Happen?</h3><p>The compiler sees that the function has no calling side effects (e.g: neither calling any other third-party function nor changing a global variable)</p><p>If we change the code and add a global variable to hold the function’s result as seen in the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Kyi97__kdrIjM57yc5s-Ag.png" /><figcaption>A global variable was added to hold the function’s result</figcaption></figure><p>The output of the main function will not be empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RT6SGUaD-r7wUwsvK5eZnA.png" /><figcaption>The main function is not empty anymore!</figcaption></figure><h3>Where Can We Face It?</h3><p>A common use case of unwanted compiler optimization might occur in benchmark tests.</p><p>To prevent the unwanted optimization (that could compromises our function’s performance measurement) one can disable optimizations when running the tests, which, in my opinion, does not reflect reality.</p><p>I would like to show you <strong>another possible solution</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*ccetltMX9CS-OONyKz5sIQ.png" /><figcaption>(1) Used to prevent the compiler from eliminating the sin function call (2) Store the result in a package level variable to protect the BenchmarkSin function</figcaption></figure><h3>Summary</h3><p>We started by playing a little with Go build tools to understand a simple optimization of function inlining. Then we dived a little deeper to understand the compiled code and the optimization flags affections and finished by a real-world example we may face in our next benchmark tests.</p><p>I hope you now have a profound understanding of compiler optimization and some Go build tools, but most importantly curiosity to check other internal stuff.</p><p>Read more:</p><p>[1] <a href="https://github.com/golang/go/wiki/CompilerOptimizations">https://github.com/golang/go/wiki/CompilerOptimizations</a></p><p>[2] <a href="https://dave.cheney.net/high-performance-go-workshop/">https://dave.cheney.net/high-performance-go-workshop/</a></p><p>[3] <a href="https://stackoverflow.com/a/36975497">https://stackoverflow.com/a/36975497</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdd027071843" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>