<?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 Ed King on Medium]]></title>
        <description><![CDATA[Stories by Ed King on Medium]]></description>
        <link>https://medium.com/@teddyking?source=rss-c028e49f8ebb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5I_-ouu3NufqUiIs5IlKrg.jpeg</url>
            <title>Stories by Ed King on Medium</title>
            <link>https://medium.com/@teddyking?source=rss-c028e49f8ebb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:57:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@teddyking/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[The Night Is Dark and Full of Flakes]]></title>
            <link>https://medium.com/@teddyking/the-night-is-dark-and-full-of-flakes-29c529404c3c?source=rss-c028e49f8ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/29c529404c3c</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[cloud-foundry]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Ed King]]></dc:creator>
            <pubDate>Tue, 05 Jun 2018 12:12:17 GMT</pubDate>
            <atom:updated>2018-06-07T05:07:31.802Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lessons learnt from running all the tests all the time</h4><p>About a year ago, here on the Cloud Foundry container team, we decided to start running every one of our test suites every 20 minutes. The implications of such madness have been profound. This article details everything the team and I have learnt from the whole ordeal so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISS8-IjRs97B5M5AmvIBiw.png" /></figure><p>Let’s begin by discussing why we did this and what we hoped to achieve. The goal was to reduce the number of flaky tests in our codebase to near zero. Why? Because flakes are bad, they:</p><p>👎 Screw up our CI pipelines<br>👎 Make refactoring difficult and error-prone<br>👎 Lead to reduced confidence in the codebase<br>👎 Make me feel like an amateur who doesn’t know how to write good tests<br>👎 Waste valuable engineering time<br>👎 Are just generally are the worst</p><p>And we’d had quite enough of all that. But before we could deal with the flakes we first needed to flush them out. And what better way to flush them out than by running all our test suites periodically every 20 minutes forever!</p><p>This was the genius idea of the team’s Anchor at the time, <a href="https://twitter.com/wlamartin">Will Martin</a>, who then immediately stepped down as Anchor and left me to deal with the fallout.</p><p>Fast forward to the present day and we’ve been running our tests like this for over a year now. So, what lessons have we learnt?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv4Zn1fvRWQxuQX412mi9w.png" /></figure><p>The first and most obvious lesson learnt was that more test runs = more flakes. This was of course expected, but what was less expected was the sheer quantity of flakes that started to crop up. In fact it was absolutely relentless, and it pushed the team’s strategy for dealing with flakes to the limit.</p><p>In the past, our flake strategy had always been as follows:</p><p>➡️ Engineer notices a flaky test<br>➡️ Engineer creates a chore in the backlog for the flake<br>➡️ The chore is immediately prioritised at the top of the backlog</p><p>That’s a solid strategy to have in place as it forces flakes to be dealt with immediately, i.e. before context is lost on recent code changes that likely introduced the flake in the first place. However, this strategy is less effective when suddenly faced with a thousand new flakes that have been hiding in the test suites for a long time.</p><p>If we were to have prioritised every new flake at the top of the backlog, we wouldn’t have been able to deliver any new features for weeks. Now, there is a super interesting question regarding whether or not we <em>should</em> have stopped work on new features and addressed the flakes before continuing, but that’s a discussion for another day.</p><p>For better or worse we continued with feature development and dedicated a track of work to dealing with the flakes - the much-feared flake track. The pair working on the flake track were responsible for identifying the flakiest of flakes and triaging them into actionable chores in the backlog.</p><p>This in itself was a challenge and highlighted the need for better tooling around detection and triage of flaky tests. We did briefly experiment with a tool called concourse-flake-hunter, but it turns out that accurately automating the detection of flakes is a lot harder than you might imagine…</p><p>The need for such tooling was also called into question, the assumption being that surely it’s better to focus on preventing flakes rather than building tools to help treat them. While I do agree with that sentiment, it was already far too late for that by the time we kicked off this little experiment. But flake prevention is an important topic, and it’s one we’ve learnt a lot about over the past year or so, which brings us on nicely to...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKgge9584JAhYJ1yskWtAw.png" /></figure><p>The second lesson learnt was that when dealing with chaos (i.e. a sudden downpour of flakes) it can be hugely beneficial to take a step back and to look at the bigger picture. At the time we were so preoccupied with fixing flakes on a case-by-case basis that we were failing to see the patterns that were emerging.</p><p>On reflection it’s now much more clear.</p><p>The majority of flakes we saw can be categorised into one or more of the following:</p><p><strong>❄️ Timeout flake</strong> - Occurs when some timeout in the test is exceeded<br><strong>❄️ Network flake</strong> - Occurs when there is a connectivity issue on the network<br>❄️ <strong>Heisenflake</strong> - Occurs only when you are not looking at it<br><strong>❄️ State flake</strong> - Occurs when a test relies on the execution environment to be in a particular state when it is not<br><strong>❄️ Dependency flake</strong> - Occurs when some external dependency is not available at test time (e.g. DockerHub, S3, etc.)</p><p>And each type of flake requires a certain type of response. Let’s start with timeout flakes, which were by far the most prevalent.</p><p>Now the simplest thing to do when confronted with a timeout flake is to simply increase the timeout. That’s a perfectly acceptable solution to a one-off timeout flake. Much less so when you’re dealing with your thousandth one.</p><p>One idea we experimented with was <a href="https://github.com/cloudfoundry/grootfs/commit/7fd4019ef325e567c480be319ce538cbff541817">removing timeouts from our tests</a> entirely. Can’t get a timeout flake if you don’t have a timeout! I actually really like this approach. Sure, it may result in occasionally-slower-to-fail tests, but I’d argue that that’s much more desirable than a test that’s going to flake all the time.</p><p>Of course, when removing test timeouts you do then run the risk of some test runs hanging forever. In order to combat this risk we developed a little helper script called <a href="https://github.com/cloudfoundry/garden-runc-release/blob/v1.13.3/ci/helpers/slowmobius">slowmobius</a>. slowmobius watches over all our test runs and notifies us of any that are taking an unusually long time to complete. The end result is no more test timeouts + confidence that we are still made aware of hanging tests 👌.</p><p>Let’s look at dependency flakes next. Garden supports running containers from Docker images. Because of this a large number of our tests have a dependency on DockerHub. For example, it’s quite common for our tests to create a container from the docker:///alpine image.</p><p>Given the frequency at which our tests are now running, it’s not super uncommon for a test to flake with a “could not connect to DockerHub” error.</p><p>This can be very frustrating, especially given we have no control over the availability of DockerHub. One idea we discussed was to internalise the dependency and to setup our own Docker registry for use in our tests. I’m not particularly keen on that idea though. I think it makes our tests less “realistic” and moves them further away from how the majority of end users will use our product.</p><p>If an external dependency is so flaky that you are considering workarounds like this, maybe that’s a signal that some bigger change is required. For example, maybe you need to introduce some retry logic to the production code. Or maybe you should consider alternative dependencies entirely.</p><p>These days DockerHub is pretty stable so we’ve been happy to keep things as they are. Besides, whenever DockerHub does go down, our tests don’t really “flake” as such. Rather they continually fail for some period of time before then all coming back online. That’s not so bad because it doesn’t require as much engineering time to investigate.</p><p>Heisenflakes are the worst of all flakes. They are impossible to reproduce and occur only once in a lifetime. We literally had to investigate a flake that would occur once in every ~3000 runs. COME ON!</p><p>But there is hope. The pattern we’ve adopted for dealing with Heisenflakes is to not even try to reproduce them, as, by definition, they will not occur when you are trying to debug them. Instead we focus on improving our logging/debug output so that we are in a better position to understand the flake if/when it ever occurs again. This has saved us many, many hours of painfully boring debug time over the past year or so.</p><p>As for Network flakes, well to be honest there’s not a whole lot you can do about those. The best advice I can give is to make sure you’re running your tests on a solid network connection and to only use the network when absolutely necessary.</p><p>And finally state flakes - these are usually the result of improper test setup or teardown. Or perhaps an accidental and implicit dependency on the order in which tests must be run.</p><p>The best way to combat state flakes is to ensure your tests are run in a completely random order. While this may lead to the occasional Heisenflake, it will result in a healthier testing suite in the long run.</p><p>Ok. What’s next?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ifgJeSLa-oP31vb8tx2Xw.png" /></figure><p>Or more accurately your CI infrastructure will die! This was something we overlooked for <em>far</em> too long. By running our tests periodically we had inadvertently increased the load on our CI machines. This in turn led to, you guessed it, more flakes!</p><p>In other words, our big attempt to minimise flaky test runs directly contributed to the generation of even more flaky test runs… GOOD ONE!</p><p>The key thing we were missing here was proper monitoring of our CI. Once we got some graphs in place we saw that every 20 minutes the load average would jump to over 100 and it became very clear that we needed to scale up.</p><p>Once we did that the number of flakes started to drop quite significantly. Something that now seems so obvious …</p><p>There’s time for one more lesson (and one more incredibly contrived Game of Thrones quote).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ljDmje0C7GQ7exnGNAVZA.png" /></figure><p>This one’s a bit embarrassing…</p><p>We use slack messages to notify us of any flaky test runs. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9u5wyopWxit4zWSHtEK2kw.png" /></figure><p>Pretty neat right? The notification contains all the information we could possibly need to identify the build. It includes the job name, a link to view the build output in a browser and a copy-paste string we can use to jump into the build container.</p><p>Of course, during what has come to be known as “flakemageddon”, we were getting <em>a lot</em> of these notifications. Which in itself isn’t necessarily a problem, but we’d overlooked the fact that we weren’t the only ones who could see these notifications…</p><p>Our slack channel is completely public, which means anyone can jump in to ask us questions, or to just hang out in what is clearly the coolest slack channel in all of #cloudfoundry.</p><p>What’s less cool is jumping in to be greeted by pages and pages of messages about failing test runs… Not sure that’d fill me with a whole lot of confidence in the product 😬.</p><p>For some ridiculous reason we were posting flake notifications to our main channel rather than a separate, notification-only channel. I think maybe there was some concern that we would be less likely to keep an eye on a separate channel? Either way this was clearly a bad impression to be sending out and so we have since moved all notifications to a separate channel.</p><p>This actually had an unintended side effect of helping to deal with the flake triaging as well. Now we were able to see all notifications at a glance in a single place, which helped us to spot the ones that were most troublesome. While this helped us out a bit, I still reckon there’s room for improvement in the general flake triaging area.</p><p>Let’s wrap this up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ox5JiCdl7e-jo3diHkl5kA.png" /></figure><p>So, was this all worth the effort? The short answer is yes, yes it was. Our test suites are now much, <em>much</em> healthier and I also learnt a huge amount about how to write better tests. I will 100% take this practice with me onto new teams and new codebases in the future.</p><p>One really important point I’ve yet to mention is that almost all of our time spent working on this was spent fixing up the test code. There were very few changes (if any) to our production code. On the one hand that’s obviously a good thing as it means our production code is solid. But on the other hand we did invest a lot of engineering time into this.</p><p>In my opinion it was absolutely worth it. While the only “actual” output may have been improvements to our test suites, the amount we all learnt about our codebase through flake debugging has been absolutely invaluable.</p><p>In summary, we decided to run all our tests all the time and as a result are now able to better focus our engineering efforts on the things that really matter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29c529404c3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Namespaces in Go - UTS]]></title>
            <link>https://medium.com/@teddyking/namespaces-in-go-uts-d47aebcdf00e?source=rss-c028e49f8ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d47aebcdf00e</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ed King]]></dc:creator>
            <pubDate>Fri, 13 Jan 2017 13:17:18 GMT</pubDate>
            <atom:updated>2017-01-13T13:17:18.855Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@teddyking/namespaces-in-go-network-fdcf63e76100">previous article</a> we configured the Network namespace to provide ns-process with a routable IP address. Now that ns-process is able to join a network, it’d be a good idea to make sure it starts up with a unique hostname. In this article (the last in the series) we will configure the UTS namespace to make this so. Let’s start, as always, by reviewing the current behaviour.</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 5.0</pre><pre>$ hostname<br>ubuntu-xenial<br>$ go build<br>$ ./ns-process<br>-[ns-process]- # hostname<br>ubuntu-xenial</pre><p>The hostname reported inside the namespaced /bin/sh process is the same as the hostname reported on the host. Obviously this isn’t ideal and could lead to confusion further down the line.</p><p>Fortunately the fix for this is pretty simple (much easier than the network setup from before) so let’s jump straight in.</p><h4>👉 Let’s Go</h4><p>In Go, the hostname can be set via the <a href="https://golang.org/pkg/syscall/#Sethostname">SetHostname</a> func from the syscall package.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 6.0<br># Filename: ns_process.go</pre><pre>func nsInitialisation() {<br>	newrootPath := os.Args[1]<br><br>	if err := mountProc(newrootPath); err != nil {<br>		fmt.Printf(&quot;Error mounting /proc - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	if err := pivotRoot(newrootPath); err != nil {<br>		fmt.Printf(&quot;Error running pivot_root - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	if err := syscall.Sethostname([]byte(&quot;ns-process&quot;)); err != nil {<br>		fmt.Printf(&quot;Error setting hostname - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	if err := waitForNetwork(); err != nil {<br>		fmt.Printf(&quot;Error waiting for network - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	nsRun()<br>}</pre><p>The call to Sethostname occurs just before the wait for the network. As you can see, the hostname has been hardcoded to ns-process here. Most container implementations today set the hostname to the ID/name of the container, which is usually some random UUID by default.</p><p>And that’s really all there is to it! Let’s confirm our implementation works as expected.</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 6.0</pre><pre>$ hostname<br>ubuntu-xenial<br>$ go build<br>$ ./ns-process<br>-[ns-process]- # hostname<br>ns-process</pre><p>Perfect!</p><h4>🎬 That’s a wrap</h4><p>That’s all for this particular series of articles! Many congratulations on making it to the end. You should now be fully equipped to head out into container land to write your very own Docker. I hope you’ve had fun and have maybe learnt a little bit about Linux namespaces in Go in the process.</p><p>If you’ve got any feedback, questions or rants you’d like to send my way you can find me over on twitter as <a href="https://twitter.com/edking2">edking2</a> (damn you edking and edking1!).</p><h4>📺 Epilogue</h4><p>More astute readers may have noticed that in publishing the last article in this series I’ve totally ignored 2 of the 7 namespaces - IPC and Cgroup. This isn’t an oversight, rather that I’ve never actually had to configure these two myself. The IPC namespace seems to Just Work™ and the Cgroup namespace is so new that I just haven’t got round to playing with it yet. Besides, I need to save <em>some</em> material for season 2…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d47aebcdf00e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Namespaces in Go - Network]]></title>
            <link>https://medium.com/@teddyking/namespaces-in-go-network-fdcf63e76100?source=rss-c028e49f8ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdcf63e76100</guid>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Ed King]]></dc:creator>
            <pubDate>Mon, 09 Jan 2017 13:13:45 GMT</pubDate>
            <atom:updated>2017-01-13T13:21:52.088Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@teddyking/namespaces-in-go-mount-e4c04fe9fb29">previous article</a> we saw how to make use of PivotRoot and the Mount namespace to swap in a new root filesystem for ns-process. With that change in place, ns-process is starting to look and feel an awful lot like any other container. Sure, it only runs a single /bin/sh process at the moment, but it does have a number of extremely cool features:</p><ol><li>Can be run as a non-root user thanks to the User namespace</li><li>Can choose a root filesystem to run in thanks to the Mount namespace</li><li>Cannot see any of the host’s processes thanks to the PID namespace</li></ol><p>That’s pretty impressive! But there’s still a piece of vital functionality missing - networking. At the moment, ns-process doesn’t have any network connectivity!</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.1</pre><pre>$ go build<br>$ ./ns-process<br>-[ns-process]- # ifconfig<br>-[ns-process]- # route<br>Kernel IP routing table<br>Destination     Gateway         Genmask         ...   Use Iface<br>-[ns-process]- # ping 8.8.8.8<br>PING 8.8.8.8 (8.8.8.8): 56 data bytes<br>ping: sendto: Network is unreachable</pre><p>That’s slightly less impressive… The reason for this lack of connectivity is due to the fact that ns-process clones a new Network namespace, the very purpose of which is to isolate all network-related resources (IPs, ports, interfaces, etc.).</p><p>In this article we will set about configuring the new Network namespace such that it ends up with an interface and a routable IP address.</p><h4>🌐 A quick lesson in networking</h4><p>If we are to have any hope of adding network connectivity to ns-process, a solid understanding of the Network namespace is going to be essential. To that end, I highly recommend you read through <a href="http://blog.scottlowe.org/2013/09/04/introducing-linux-network-namespaces/">Introducing Linux Network Namespaces</a>. The knowledge and ideas presented in that article will form the basis for the Network namespace configuration in ns-process. To briefly summarise, here’s what we’ll need to do:</p><ol><li>Create a bridge device in the host’s Network namespace</li><li>Create a veth pair</li><li>Attach one side of the pair to the bridge</li><li>Place the other side of the pair in ns-process&#39;s Network namespace</li><li>Ensure all traffic originating in the namespaced process gets routed via the veth</li></ol><p>The general idea is to establish a connection between ns-process&#39;s Network namespace and the host’s Network namespace. Visually this looks a little something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*n0C9gVEi8XIoAuZELhy1ng.jpeg" /></figure><p>This is actually a fair amount of work! And it’s made complicated by the fact that setup and configuration needs to occur in two different Network namespaces. There’s also a further complexity in that the network setup requires root privileges, which means we <em>could</em> end up regressing on one of ns-process&#39;s most lovely features - that it can be run as a non-root user.</p><p>Fortunately this can be avoided by making use of setuid. setuid allows a process to run as the user that <em>owns</em> an executable. The idea then is to extract the network setup code into a separate executable, ensure the executable is owned by the root user and to apply the setuid permission on it. We can then call out to the executable from within ns-process (running as a non-root user) as and when we need to. With all this in mind, allow me to introduce netsetgo.</p><h4>🚦 On your marks, net set, GO!</h4><p><a href="https://github.com/teddyking/netsetgo">netsetgo</a> is a small binary that helps to setup Network namespaces for containers. It achieves this by applying the configuration outlined above. For sake of brevity I’m not going to paste the full netsetgo code here, but I will briefly point out the most useful parts so you can take a more detailed look for yourself.</p><ol><li>Bridge creation occurs <a href="https://github.com/teddyking/netsetgo/blob/0.0.1/device/bridge.go#L15-L37">here</a> via a call to netlink.LinkAdd</li><li>Veth creation occurs <a href="https://github.com/teddyking/netsetgo/blob/0.0.1/device/veth.go#L16-L41">here</a> via another call to netlink.LinkAdd</li><li>The veth is attached to the bridge <a href="https://github.com/teddyking/netsetgo/blob/0.0.1/device/bridge.go#L39-L51">here</a> via a call to netlink.LinkSetMaster</li><li>The veth is moved to the new Network namespace <a href="https://github.com/teddyking/netsetgo/blob/0.0.1/device/veth.go#L43-L50">here</a> via a call to netlink.LinkSetNsPid</li><li>A default route is added to the new Network namespace <a href="https://github.com/teddyking/netsetgo/blob/0.0.1/configurer/container.go#L47-L53">here</a> via a call to netlink.RouteAdd</li></ol><p>In order to make use of netsetgo fromns-process, we’ll need to download the binary and set the correct permissions on it, as follows.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.1</pre><pre>$ wget &quot;<a href="https://github.com/teddyking/netsetgo/releases/download/0.0.1/netsetgo">https://github.com/teddyking/netsetgo/releases/download/0.0.1/netsetgo</a>&quot;<br>$ sudo mv netsetgo /usr/local/bin/<br>$ sudo chown root:root /usr/local/bin/netsetgo<br>$ sudo chmod 4755 /usr/local/bin/netsetgo</pre><p>The 4 in the chmod 4755 signifies that the setuid bit should be set.</p><h4>👉 Let’s Go</h4><p>Now that netsetgo is primed and ready it’s time to turn our attention back to ns-process. We need to modify ns-process so that it calls out to netsetgo to configure the network. At first glance this would appear to be relatively simple - we can just create a *exec.Cmd pointing to netsetgo and run it at the appropriate moment?</p><p>Of course, nothing’s ever quite as easy as it seems, and here the question of when to run netsetgo requires a bit more thought. Let’s start by looking at how we kick off Namespace creation at the moment (output trimmed for simplicity).</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.1<br># Filename: ns_process.go</pre><pre>func main() {<br>	cmd := reexec.Command(&quot;nsInitialisation&quot;, rootfsPath)<br><br>	cmd.SysProcAttr = &amp;syscall.SysProcAttr{<br>		Cloneflags: syscall.CLONE_NEWNS |<br>			syscall.CLONE_NEWUTS |<br>			syscall.CLONE_NEWIPC |<br>			syscall.CLONE_NEWPID |<br>			syscall.CLONE_NEWNET |<br>			syscall.CLONE_NEWUSER,<br>	}<br><br>	if err := cmd.Run(); err != nil {<br>		fmt.Printf(&quot;Error running Command - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br>}</pre><p>Here we’re using cmd.Run() to run a reexec command with a number of CLONE_NEW* flags set. Note that cmd.Run() does not return until the underlying process has exited. Up until now this has been fine because all subsequent namespace configuration has taken place inside the newly-cloned namespaces (via the nsInitialisation func to be specific).</p><p>However, netsetgo needs to configure the host’s Network namespace as well as the new one, which means we can no longer rely on the blocking call to cmd.Run().</p><p>Fortunately cmd.Run() can be split into two separate calls - cmd.Start() (which returns immediately) and cmd.Wait() (which blocks until the started command exits). This is exactly what we need as it allows us to run netsetgo after the new namespaces have been created but while still executing in the host’s namespaces. Let’s see this in action.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 5.0<br># Filename: ns_process.go</pre><pre>if err := cmd.Start(); err != nil {<br>	fmt.Printf(&quot;Error starting the reexec.Command - %s\n&quot;, err)<br>	os.Exit(1)<br>}<br><br>pid := fmt.Sprintf(&quot;%d&quot;, cmd.Process.Pid)<br>netsetgoCmd := exec.Command(netsetgoPath, &quot;-pid&quot;, pid)<br>if err := netsetgoCmd.Run(); err != nil {<br>	fmt.Printf(&quot;Error running netsetgo - %s\n&quot;, err)<br>	os.Exit(1)<br>}<br><br>if err := cmd.Wait(); err != nil {<br>	fmt.Printf(&quot;Error waiting for reexec.Command - %s\n&quot;, err)<br>	os.Exit(1)<br>}</pre><p>Great! This change allows netsetgo to configure the networking across both Network namespaces as required. All that’s left to do now is to ensure that the namespaced /bin/sh process doesn’t start until the network is ready.</p><p>Let’s consider the network to be ready once a veth interface has appeared in the new Network namespace. We can use a simple for loop to wait until this is true, as follows.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 5.0<br># Filename: net.go</pre><pre>func waitForNetwork() error {<br>	maxWait := time.Second * 3<br>	checkInterval := time.Second<br>	timeStarted := time.Now()<br><br>	for {<br>		interfaces, err := net.Interfaces()<br>		if err != nil {<br>			return err<br>		}<br><br>		// pretty basic check ...<br>		// &gt; 1 as a lo device will already exist<br>		if len(interfaces) &gt; 1 {<br>			return nil<br>		}<br><br>		if time.Since(timeStarted) &gt; maxWait {<br>			return fmt.Errorf(&quot;Timeout after %s waiting for network&quot;, maxWait)<br>		}<br><br>		time.Sleep(checkInterval)<br>	}<br>}</pre><p>Here we have a very basic for loop which blocks until either more than one network interface is reported or a timeout of 3 seconds is reached. As the comment mentions, we check for more than one interface as the loopback interface will already exist by default.</p><p>Finally, let’s update nsInitialisation to call the above function.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 5.0<br># Filename: ns_process.go</pre><pre>func nsInitialisation() {<br>	newrootPath := os.Args[1]<br><br>	if err := mountProc(newrootPath); err != nil {<br>		fmt.Printf(&quot;Error mounting /proc - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	if err := pivotRoot(newrootPath); err != nil {<br>		fmt.Printf(&quot;Error running pivot_root - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	if err := waitForNetwork(); err != nil {<br>		fmt.Printf(&quot;Error waiting for network - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	nsRun()<br>}</pre><p>With all that in place, let’s run the updated Go program.</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 5.0</pre><pre>$ go build<br>$ ./ns-process<br>-[ns-process]- # ifconfig<br>veth1     Link encap:Ethernet  HWaddr 6A:DD:B4:30:1A:49<br>          inet addr:10.10.10.2  Bcast:0.0.0.0  Mask:255.255.255.0<br>          inet6 addr: fe80::68dd:b4ff:fe30:1a49/64 Scope:Link<br>          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1<br>          RX packets:18 errors:0 dropped:0 overruns:0 frame:0<br>          TX packets:7 errors:0 dropped:0 overruns:0 carrier:0<br>          collisions:0 txqueuelen:1000<br>          RX bytes:2359 (2.3 KiB)  TX bytes:578 (578.0 B)</pre><pre>-[ns-process]- # route<br>Kernel IP routing table<br>Destination     Gateway         Genmask         ... Iface<br>default         10.10.10.1      0.0.0.0         ... veth1<br>10.10.10.0      *               255.255.255.0   ... veth1<br>-[ns-process]- # ping 10.10.10.1<br>PING 10.10.10.1 (10.10.10.1): 56 data bytes<br>64 bytes from 10.10.10.1: seq=0 ttl=64 time=0.098 ms<br>^C<br>--- 10.10.10.1 ping statistics ---<br>1 packets transmitted, 1 packets received, 0% packet loss<br>round-trip min/avg/max = 0.098/0.098/0.098 ms</pre><p>Much better! We now have a network interface veth1 available and a routable IP address of 10.10.10.2.</p><h4>☁️ Internet connectivity</h4><p>Enabling Internet access for ns-process is a little out of scope for this particular article. This is mostly because a lack of Internet connectivity could be the result of any number of things, and attempting to cover all environmental setups would be pretty difficult.</p><p>Having said that, the following steps do enable Internet connectivity for ns-process on my generic Ubuntu 16.04 Xenial machine. There’s no guarantee this will work for you, but feel free to try it out if you’re interested.</p><p>First up we need to configure a few iptables rules on the host.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 5.0</pre><pre>$ sudo iptables -tnat -N netsetgo<br>$ sudo iptables -tnat -A PREROUTING -m addrtype --dst-type LOCAL -j netsetgo<br>$ sudo iptables -tnat -A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j netsetgo<br>$ sudo iptables -tnat -A POSTROUTING -s 10.10.10.0/24 ! -o brg0 -j MASQUERADE<br>$ sudo iptables -tnat -A netsetgo -i brg0 -j RETURN</pre><p>And then we also need to add a DNS nameserver for the namespaced process.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 5.0</pre><pre>$ go build<br>$ ./ns-process<br>-[ns-process]- # echo &quot;nameserver 8.8.8.8&quot; &gt;&gt; /etc/resolv.conf<br>-[ns-process]- # ping google.com<br>PING google.com (172.217.23.14): 56 data bytes<br>64 bytes from 172.217.23.14: seq=0 ttl=51 time=4.766 ms</pre><p>And there we have it - ns-process running with full Internet connectivity.</p><h4>📺 On the next…</h4><p>With network configuration complete, ns-process is now setup to configure the User, Mount, Pid and Network namespaces, but what needs to be done about the remaining namespaces? The answer to this and plenty more coming up, stay tuned…</p><p><strong>Update</strong>: Part 7, “Namespaces in Go - UTS” has been published and is available <a href="https://medium.com/@teddyking/namespaces-in-go-uts-d47aebcdf00e">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdcf63e76100" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Namespaces in Go - Mount]]></title>
            <link>https://medium.com/@teddyking/namespaces-in-go-mount-e4c04fe9fb29?source=rss-c028e49f8ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4c04fe9fb29</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ed King]]></dc:creator>
            <pubDate>Sat, 17 Dec 2016 09:55:51 GMT</pubDate>
            <atom:updated>2017-01-10T08:49:56.153Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the fundamental features of container implementations today is the ability to run containers of differing linux distros on the same host machine. It’s not uncommon, for example, to install Docker on an Ubuntu host and to then start a bunch of containers on that host using <a href="https://hub.docker.com/_/busybox/">BusyBox</a>, <a href="https://hub.docker.com/_/centos/">CentOS</a>, or any other distro you like the look of.</p><p>In this article we will will take a look at what makes this possible - namely a combination of the Mount namespace and the pivot_root system call. Let&#39;s start by reviewing the Mount namespace implementation in ns-process as it currently stands. If you’ve not been following along with this series so far, be sure to check out the <a href="https://medium.com/@teddyking/namespaces-in-go-reexec-3d1295b91af8">previous article</a>(s) first.</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 3.0</pre><pre>$ go build<br>$ ./ns-process</pre><pre>&gt;&gt; namespace setup code goes here &lt;&lt;</pre><pre>-[ns-process]- # cat /proc/mounts<br>/dev/sda1 / ext4 rw,relatime,data=ordered 0 0<br>tmpfs /dev/shm tmpfs rw,nosuid,nodev 0 0<br>proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0<br># ...</pre><p>There are a number of mounts already listed in the /proc/mounts file. This may be little surprising given that we’re requesting a new Mount namespace (via the CLONE_NEWNS flag) and have yet to do any explicit Mount namespace setup.</p><p>This doesn’t feel very container-like. Our namespaced process should know as little as possible about the host it’s running on, and certainly shouldn’t be able to see a list of all the host’s mounts. So why’s this happening? Fortunately, an explanation can be found within the <a href="http://man7.org/linux/man-pages/man7/mount_namespaces.7.html">mount_namespaces(7)</a> man page.</p><p><em>“When a process creates a new mount namespace using clone(2) or unshare(2) with the CLONE_NEWNS flag, the mount point list for the new namespace is a copy of the caller’s mount point list.”</em></p><p>It seems that this is actually intended behaviour, and it explains why /proc/mounts is already populated as soon as our namespaced process starts. With this in mind the question now becomes, “What do we do about it?”. We need some way of clearing the host’s mounts from the new Mount namespace in order to keep them secure and away from prying eyes - we need to pivot_root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*_C9oQxRBlIMuIoX8FOQ6XQ.jpeg" /></figure><h4>🔄 pivot_root</h4><p>pivot_root allows you to set a new root filesystem for the calling process. I.e. it allows you to change what / is. It does this by mounting the current root filesystem somewhere else while simultaneously mounting some new root filesystem on /. Once the previous root has been moved, it is then possible to umount it. Thus we have a mechanism for &#39;clearing&#39; the hosts&#39;s mounts from inside a new Mount namespace - we simply pivot away and then umount them!</p><p>This is what allows the aforementioned Ubuntu host machine to run a CentOS container. As long as the Ubuntu host has a copy of a CentOS filesystem on disk, we can create a new Mount namespace, call pivot_root pointing to the CentOS filesystem and then run whatever processes we want to inside the &#39;pivoted&#39; namespace. The processes will believe they’re running on CentOS the entire time.</p><p>Incidentally this is where the reexec from the <a href="https://www.capsysteddy.com/namespaces-in-go-pt-3/">previous article</a> comes in handy. pivot_root must be called from within the new Mount namespace, otherwise we&#39;ll end up changing the host&#39;s / which is not the intention! And we want all this to happen before the namespaced shell starts so that the requested root filesystem is ready for when it does.</p><h4>👉 Let’s Go</h4><p>In Go, pivot_root is implemented via the <a href="https://golang.org/pkg/syscall/#PivotRoot">PivotRoot</a> func found in the syscall package.</p><pre>func PivotRoot(newroot <a href="https://golang.org/pkg/builtin/#string">string</a>, putold <a href="https://golang.org/pkg/builtin/#string">string</a>) (err <a href="https://golang.org/pkg/builtin/#error">error</a>)</pre><p>newroot is the path to the desired new root filesystem and putold is a path to a directory in which to move the current root. There are a few restrictions imposed on newroot and putold by the underlying pivot_root sys call that we need to be aware of:</p><ol><li>They must both be directories</li><li>They must not be on the same filesystem as the current root</li><li>putold must be underneath newroot</li><li>No other filesystem may be mounted on putold</li></ol><p>Most of these are fine but the second point there will require a small workaround, as we’ll see in a moment. We’re also going to need a suitable newroot in which to pivot to.</p><p>The process of preparing a newroot filesystem can be quite a detailed and complex one. Take for example Docker’s layered filesystem approach in which many filesystem “layers” are joined together to present a single coherent root. We’re going to do something much simpler, which is to to assume that a suitable root filesystem has already been prepared for use.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.0</pre><pre>$ mkdir -p /tmp/ns-process/rootfs<br>$ tar -C /tmp/ns-process/rootfs -xf assets/busybox.tar</pre><p>From now on, ns-process will expect a root filesystem to exist at this path and will raise an error if one can’t be found. Note that although we’re using BusyBox for this particular example, you could just as easily use any other distro.</p><p>Now that we have our newroot, let’s write some code to make use of it.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.0<br># Filename: rootfs.go</pre><pre>func pivotRoot(newroot string) error {<br>	putold := filepath.Join(newroot, &quot;/.pivot_root&quot;)<br><br>	// bind mount newroot to itself - this is a slight hack<br>	// needed to work around a pivot_root requirement<br>	if err := syscall.Mount(<br>		newroot,<br>		newroot,<br>		&quot;&quot;,<br>		syscall.MS_BIND|syscall.MS_REC,<br>		&quot;&quot;,<br>	); err != nil {<br>		return err<br>	}<br><br>	// create putold directory<br>	if err := os.MkdirAll(putold, 0700); err != nil {<br>		return err<br>	}<br><br>	// call pivot_root<br>	if err := syscall.PivotRoot(newroot, putold); err != nil {<br>		return err<br>	}<br><br>	// ensure current working directory is set to new root<br>	if err := os.Chdir(&quot;/&quot;); err != nil {<br>		return err<br>	}<br><br>	// umount putold, which now lives at /.pivot_root<br>	putold = &quot;/.pivot_root&quot;<br>	if err := syscall.Unmount(<br>		putold,<br>		syscall.MNT_DETACH,<br>	); err != nil {<br>		return err<br>	}<br><br>	// remove putold<br>	if err := os.RemoveAll(putold); err != nil {<br>		return err<br>	}<br><br>	return nil<br>}</pre><p>With the pivotRoot func in place, it’s time to put nsInitialisation to good use.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.0<br># Filename: ns_process.go</pre><pre>func nsInitialisation() {<br>	newrootPath := os.Args[1]<br><br>	if err := pivotRoot(newrootPath); err != nil {<br>		fmt.Printf(&quot;Error running pivot_root - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	nsRun()<br>}<br><br>func main() {<br>	var rootfsPath string<br>	// ...</pre><pre>	cmd := reexec.Command(&quot;nsInitialisation&quot;, rootfsPath)<br>}</pre><p>Notice that we’re now passing an argument, rootfsPath, to nsInitialisation. Once reexeced, this argument can be picked up by reading from os.Args[1]. Also notice how the call to pivotRoot comes <em>before</em> nsRun. By doing this, we&#39;re ensuring that the new root filesystem will already have been pivoted to before the /bin/sh process starts.</p><p>With all that in place, let&#39;s run the updated Go program and check to see which mounts, if any, are available to us now.</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.0</pre><pre>$ go build<br>$ ./ns-process<br>-[ns-process]- # cat /proc/mounts<br>cat: can&#39;t open &#39;/proc/mounts&#39;: No such file or directory</pre><p>Ah … now that we’ve pivoted to a new /, we no longer have a /proc! This is actually a good thing as it means we definitely can’t see the host’s mounts anymore, which is one of the main reasons for doing all this work in the first place. But, there’s probably only so far we can get without a working /proc, so let’s add one to our new root.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.1<br># Filename: rootfs.go</pre><pre>func mountProc(newroot string) error {<br>	source := &quot;proc&quot;<br>	target := filepath.Join(newroot, &quot;/proc&quot;)<br>	fstype := &quot;proc&quot;<br>	flags := 0<br>	data := &quot;&quot;<br><br>	os.MkdirAll(target, 0755)<br>	if err := syscall.Mount(<br>		source,<br>		target,<br>		fstype,<br>		uintptr(flags),<br>		data,<br>	); err != nil {<br>		return err<br>	}<br><br>	return nil<br>}</pre><p>And just as with pivotRoot, mountProc should be called from nsInitialisation.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.1<br># Filename: ns_process.go</pre><pre>func nsInitialisation() {<br>	newrootPath := os.Args[1]<br><br>	if err := mountProc(newrootPath); err != nil {<br>		fmt.Printf(&quot;Error mounting /proc - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	if err := pivotRoot(newrootPath); err != nil {<br>		fmt.Printf(&quot;Error running pivot_root - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br><br>	nsRun()<br>}</pre><p>Ok, that should now be everything. Let’s try it out.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.1</pre><pre>$ go build<br>$ ./ns-process<br>-[ns-process]- # cat /proc/mounts<br>/dev/sda1 / ext4 rw,relatime,data=ordered 0 0<br>proc /proc proc rw,nodev,relatime 0 0</pre><p>That’s looking much better - the host’s mounts are no longer visible to us and we have a new /proc mounted and ready for action. But wait … there is one more thing …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Fw-rWVjpcgPV6NPd5ViRqw.jpeg" /></figure><h4>🤔 PID namespace</h4><p>The changes implemented above have had an unintentional side effect on the PID namespace setup. Prior to mounting the new /proc, running ps inside the namespaced shell would’ve resulted in all the <strong>host’s</strong> processes being listed. This is because ps relies on /proc to detect running processes and we were still referencing the host’s /proc.</p><p>This is obviously a pretty terrible thing to happen from a container perspective! But fortunately now that we have our own /proc(and are requesting a new PID namespace via the CLONE_NEWPID flag), running ps shows only processes that are relevant to us.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 4.1</pre><pre>$ go build<br>$ ./ns-process<br>-[ns-process]- # ps<br>PID   USER     TIME   COMMAND<br>    1 root       0:00 {exe} nsInitialisation /tmp/ns-process/rootfs<br>    5 root       0:00 /bin/sh<br>    8 root       0:00 ps</pre><h4>📺 On the next…</h4><p>We’re nearing the season finale of “Namespaces in Go”, but we’re still missing one key piece of configuration - networking. What needs to be done to allow our namespaced shell to talk to the Internets? The answer to this and plenty more coming up, stay tuned…</p><p><strong>Update</strong>: Part 6, “Namespaces in Go - Network” has been published and is available <a href="https://medium.com/@teddyking/namespaces-in-go-network-fdcf63e76100">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4c04fe9fb29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Namespaces in Go - reexec]]></title>
            <link>https://medium.com/@teddyking/namespaces-in-go-reexec-3d1295b91af8?source=rss-c028e49f8ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d1295b91af8</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Ed King]]></dc:creator>
            <pubDate>Wed, 14 Dec 2016 21:06:32 GMT</pubDate>
            <atom:updated>2017-01-10T08:49:20.171Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@teddyking/namespaces-in-go-user-a54ef9476f2a">previous article</a> we learnt how to apply a UID/GID mapping to ns-process such that we are now running as the root user once inside the namespaced shell.</p><p>The purpose of this article is to provide an understanding of the <a href="https://github.com/docker/docker/tree/v1.12.4/pkg/reexec">reexec</a> package. reexec is part of the Docker codebase and provides a convenient way for an executable to “re-exec” itself. In all honesty reexec is a bit of a hack, but it’s a really useful one that is required to circumvent a limitation in how Go handles process forking. Before going into too much more detail, let’s take a look at the problem reexec helps to solve.</p><p>It’s probably best to demonstrate the problem by way of an example. Consider the following - we want to update ns-process such that a randomly-generated hostname is set inside the new UTS namespace we’ve cloned. For security reasons, it’s essential that the hostname has been set <strong><em>before</em></strong> the namespaced /bin/sh process starts running. After all, we don’t want programs running inside ns-process to be able to discover the Host’s hostname.</p><p>As far as I’m aware, Go doesn’t provide a built-in way to allow us to do this. Namespaces are created by setting attributes on an *exec.Cmd, which is also where we specify the process we&#39;d like to run. For example:</p><pre>cmd := exec.Command(&quot;/bin/echo&quot;, &quot;Process already running&quot;)<br>cmd.SysProcAttr = &amp;syscall.SysProcAttr{<br> Cloneflags: syscall.CLONE_NEWUTS,<br>}<br>cmd.Run()</pre><p>Once cmd.Run() is called, the namespaces get cloned and then the process gets started straight away. There’s no hook or anything here that allows us to run code after the namespace creation but before the process starts. This is where reexec comes in.</p><h4>🎤 reexec yourself before you wreck yourself</h4><p>Let’s open up the reexec package and take a look at what’s inside (I won’t paste full code snippets here for sake of simplicity, but I advise you read along with the full implementations of the methods).</p><pre>// Register adds an initialization func under the specified name<br>func Register(name string, initializer func()) {<br> # ...<br>}</pre><p>First up we have Register, which exposes a way for us to register arbitrary functions by some name and to store them in memory. We will use this to register some sort of “Initialise Namespace” function when ns-process first starts up.</p><pre>// Init is called as the first part of the exec process<br>// and returns true if an initialization function was called.<br>func Init() bool {<br> # ...<br>}</pre><p>Next up we have Init, which gives us a mechanism for determining whether or not the process is running after having been reexeced, and for running one of the registered functions if we have. It does this by checking os.Args[0] for the name of one of the previously-registered functions.</p><pre>// Command returns *exec.Cmd which have Path as current binary.<br>// ...<br>func Command(args ...string) *exec.Cmd {<br> return &amp;exec.Cmd{<br>  Path: Self(),<br>  Args: args,<br>  SysProcAttr: &amp;syscall.SysProcAttr{<br>   Pdeathsig: syscall.SIGTERM,<br>  },<br> }<br>}</pre><p>Command ties it all together by creating an *exec.Cmd with Path set to Self(), which evaluates to /proc/self/exe on Linux machines. We can choose which of the registered functions we’d like to invoke upon reexec by providing the registered name of the function in args[0].</p><p>💁 <em>/proc/self/exe is a symlink file that points to the path of the currently-running executable</em></p><p>Now that we have an understanding of how reexec works, it’s time to wire it up inside ns-process.</p><h4>👉 Let’s Go</h4><p>The first thing we need to do is to create a function and register it using reexec.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 3.0<br># Filename: ns_process.go</pre><pre># ...<br>func init() {<br>	reexec.Register(&quot;nsInitialisation&quot;, nsInitialisation)<br>	if reexec.Init() {<br>		os.Exit(0)<br>	}<br>}<br># ...</pre><p>There are two important things happening here. First, we register a function nsInitialisation under the name “nsInitialisation”. We&#39;ll add that function in a moment. Secondly, we call reexec.Init() and os.Exit(0) the program if it returns true. This is vitally important to prevent an infinite loop situation whereby the program gets stuck reexecing itself forever! Let’s add nsInitialisation next.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 3.0<br># Filename: ns_process.go</pre><pre># ...<br>func nsInitialisation() {<br>	fmt.Printf(&quot;\n&gt;&gt; namespace setup code goes here &lt;&lt;\n\n&quot;)<br>	nsRun()<br>}</pre><pre>func nsRun() {<br>	cmd := exec.Command(&quot;/bin/sh&quot;)<br><br>	cmd.Stdin = os.Stdin<br>	cmd.Stdout = os.Stdout<br>	cmd.Stderr = os.Stderr<br><br>	cmd.Env = []string{&quot;PS1=-[ns-process]- # &quot;}<br><br>	if err := cmd.Run(); err != nil {<br>		fmt.Printf(&quot;Error running the /bin/sh command - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br>}</pre><p>Here we’ve added nsInitialisation() simply as a placeholder function. It will become much more important in future articles when we actually need to start configuring the namespaces. For now, it simply passes through to nsRun(), which runs the /bin/sh process.</p><p>All that’s left to do now is modify main() such that it runs the /bin/sh process via reexec and nsInitialisation rather than calling it directly.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 3.0<br># Filename: ns_process.go</pre><pre>func main() {<br>    cmd := reexec.Command(&quot;nsInitialisation&quot;)<br>    # ...<br>}</pre><p>By specifying nsInitialisation as the first arg to Command, we&#39;re essentially telling reexec to run /proc/self/exe with os.Args[0] set to nsInitialisation. Finally, once the program has been reexeced, Init will detected the registered function and then actually Run it. Let’s give it a whirl.</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre>$ go build<br>$ ./ns-process<br><br>&gt;&gt; namespace setup code goes here &lt;&lt;</pre><pre>-[ns-process]- #</pre><p>And there we have it. We now have nsInitialisation available in which to run any namespace setup we need, including the ability, as discussed earlier, to set the hostname in the new UTS namespace if we so desire.</p><h4>📺 On the next…</h4><p>We’re now in a position to configure our namespaces, but what configuration remains to be done? The answer to this and plenty more coming up, stay tuned…</p><p><strong>Update</strong>: Part 5, “Namespaces in Go - Mount” has been published and is available <a href="https://medium.com/@teddyking/namespaces-in-go-mount-e4c04fe9fb29">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d1295b91af8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Namespaces in Go - User]]></title>
            <link>https://medium.com/@teddyking/namespaces-in-go-user-a54ef9476f2a?source=rss-c028e49f8ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54ef9476f2a</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[namespaces]]></category>
            <dc:creator><![CDATA[Ed King]]></dc:creator>
            <pubDate>Tue, 13 Dec 2016 14:41:25 GMT</pubDate>
            <atom:updated>2017-01-10T08:48:44.768Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@teddyking/namespaces-in-go-basics-e3f0fc1ff69a">previous article</a> we saw how to create and run a process in various Linux namespaces using Go. We left with some code that runs a /bin/sh process in a new Mount, UTS, IPC, PID, Network and User namespace.</p><p>You may recall that once we added the User namespace to ns-process we no longer had to run it as the root user. This is a great feature to have as it means ns-process can be run much more securely. However, in adding the User namespace to the program, we have inadvertently introduced some less desirable behaviour.</p><p>This behaviour can be demonstrated by comparing the output of whoami from within the namespaced shell both before and after we added the User namespace, as follows.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 1.0<br># Prior to adding the User namespace</pre><pre>$ go build<br>$ sudo ./ns-process<br>-[ns-process]- # whoami<br>root<br>-[ns-process]- # id root<br>uid=0(root) gid=0(root) groups=0(root)</pre><pre># Git tag: 1.1<br># After adding the User namespace</pre><pre>$ go build<br>$ ./ns-process<br>-[ns-process]- # whoami<br>nobody<br>-[ns-process]- # id nobody<br>uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)</pre><p>Although we are now able to run ns-process as a non-root user, once inside the namespaced shell we have lost our root identity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*92KoE7150PT1rfC-AGO36w.jpeg" /></figure><p>In this article we will work through a fix for this regression, and learn a little bit more about the User namespace along the way.</p><h4>🗺 UID and GID mapping</h4><p>The reason behind our loss of identity is that we’re missing some important configuration. It is not enough to simply add the CLONE_NEWUSER flag and expect the User namespace to be ready for use. In order to setup the namespace properly, we also need to provide what is know as a UID and a GID mapping.</p><p>💁 <em>If you’re not interested in the theory and are eager to crack on with the Go coding, feel free to skip the rest of this section</em></p><p>ID mapping and how it relates to User namespaces is a huge topic in itself, and it falls mostly out of scope for this article. Having said that, there are a few things you need to know in order to understand how we’re going to fix our identity crisis. Here are the TL;DR essentials.</p><ul><li>The User namespace provides isolation of UIDs and GIDs</li><li>There can be multiple, distinct User namespaces in use on the same host at any given time</li><li>Every Linux process runs in one of these User namespaces</li><li>User namespaces allow for the UID of a process in User namespace 1 to be different to the UID for the same process in User namespace 2</li><li>UID/GID mapping provides a mechanism for mapping IDs between two separate User namespaces</li></ul><p>The following diagram attempts to visualise the above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*lY9jQy-ZHnKF1fMEe0W9qQ.jpeg" /></figure><p>Pictured are two User namespaces, 1 and 2, with their corresponding UID and GID tables. Note that process C, running as non-root-user is able to spawn Process D, which is running as root.</p><p>The key implementation detail, and the thing that prevents the universe from imploding is the mapping between the two User namespaces (represented here by the dashed lines).</p><p>Process D only has root privileges within the context of User namespace 2. From the perspective of processes in User namespace 1, process D is running as non-root-user, and as such, doesn’t have those all-important root privileges.</p><p>This mapping is exactly what’s missing from ns-process at the moment, and it’s about time we sorted that out.</p><h4>👉 Let’s Go</h4><p>ID mappings can be applied by setting the UidMappings and GidMappings fields on cmd.SysProcAttr. Both fields are of type SysProcIDMap found in Go’s syscall package.</p><pre>type SysProcIDMap struct {<br>        ContainerID int // Container ID.<br>        HostID      int // Host ID.<br>        Size        int // Size.<br>}</pre><p>The ContainerID and HostID fields should be fairly self-explanatory. Size is slightly less so. Size basically determines the <em>range</em> of IDs to map, which allows us to map more than one ID at a time. Let’s update our program to include some mappings.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 2.0<br># Filename: ns_process.go</pre><pre># ...<br>cmd.SysProcAttr = &amp;syscall.SysProcAttr{<br>		Cloneflags: syscall.CLONE_NEWNS |<br>			syscall.CLONE_NEWUTS |<br>			syscall.CLONE_NEWIPC |<br>			syscall.CLONE_NEWPID |<br>			syscall.CLONE_NEWNET |<br>			syscall.CLONE_NEWUSER,<br>		UidMappings: []syscall.SysProcIDMap{<br>			{<br>				ContainerID: 0,<br>				HostID:      os.Getuid(),<br>				Size:        1,<br>			},<br>		},<br>		GidMappings: []syscall.SysProcIDMap{<br>			{<br>				ContainerID: 0,<br>				HostID:      os.Getgid(),<br>				Size:        1,<br>			},<br>		},<br>	}<br># ...</pre><p>Here we are adding a single UID and GID mapping. We set ContainerID to 0, HostID to the current user’s UID/GID and Size equal to 1. In other words, we are mapping ID = 0 (aka root) in our new User namespace to the ID of the user who invokes the ns-process command.</p><p>With all this in place, we should be able to build and run ns-process and see that we now become the root user inside the namespaced shell.</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre>$ go build<br>$ ./ns-process<br>-[ns-process]- # whoami<br>root<br>-[ns-process]- # id<br>uid=0(root) gid=0(root) groups=0(root)</pre><p>And there we have it! With the addition of a simple UidMapping/GidMapping we have been able to restore our root identity inside the namespaced shell, while retaining the ability to run ns-process as a non-root user.</p><h4>📺 On the next…</h4><p>In the next article we’ll take a look at reexec. What is reexec and why is it relevant to Namespaces in Go? The answer to this and plenty more coming up, stay tuned…</p><p><strong>Update</strong>: Part 4, “Namespaces in Go - Reexec” has been published and is available <a href="https://medium.com/@teddyking/namespaces-in-go-reexec-3d1295b91af8">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54ef9476f2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Namespaces in Go - Basics]]></title>
            <link>https://medium.com/@teddyking/namespaces-in-go-basics-e3f0fc1ff69a?source=rss-c028e49f8ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3f0fc1ff69a</guid>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ed King]]></dc:creator>
            <pubDate>Sun, 11 Dec 2016 12:33:31 GMT</pubDate>
            <atom:updated>2017-01-10T08:47:52.243Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@teddyking/linux-namespaces-850489d3ccf">previous article</a> we dipped our toes in the namespace waters with the unshare command. unshare is great for simple scripting around namespaces but it&#39;s not so well suited for when we need more fine-grained and precise control, as is the case with containers. For this use case it&#39;s much better to have the support of a fully fledged programming language.</p><p>Go has emerged as the container implementation language of choice. This is due in part to the fact that Docker was, and still is, written in Go. Docker is one of the most successful open source Go projects to date (37,680 GitHub ⭐️s at time of writing) and it showed the world that Go was a language to be taken seriously.</p><p>The Docker developers have previously <a href="http://www.slideshare.net/jpetazzo/docker-and-go-why-did-we-decide-to-write-docker-in-go">outlined the reasons</a> they chose to write Docker in Go. Some of the top reasons include static compilation, good asynchronous primitives, low-level interfaces, a full development environment and strong cross compilation support.</p><p>For me personally the real beauty of Go is in its apparent simplicity. Containers are hard! And by using a ‘simple’ language it makes it much easier to reason about what exactly is going on under the hood. There is a great talk by Rob Pike, “<a href="https://www.youtube.com/watch?v=rFejpH_tAHM">Simplicity is Complicated</a>”, in which he discusses how simplicity is part of Go’s design. It’s definitely worth a watch if you’re interested.</p><h4>👉 Let’s Go</h4><p>The aim for this series of articles is to provide an understanding of how to work with Linux namespaces inside Go programs. To achieve this, we will be building out a sample application named ns-process.</p><p>ns-process will be fairly simple to begin with - it will create a /bin/sh process in a new set of namespaces. Over the course of the next few articles it will evolve in to something much more exciting - a program capable of creating unprivileged containers! Don’t worry if you’re not sure what “unprivileged” means in this context, all will be explaining along the way.</p><p>The code for ns-process is <a href="https://github.com/teddyking/ns-process">available on GitHub</a> and I highly recommend cloning the repo so you can follow along at home.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 1.0<br># Filename: ns_process.go</pre><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;os&quot;<br>	&quot;os/exec&quot;<br>	&quot;syscall&quot;<br>)<br><br>func main() {<br>	cmd := exec.Command(&quot;/bin/sh&quot;)<br><br>	cmd.Stdin = os.Stdin<br>	cmd.Stdout = os.Stdout<br>	cmd.Stderr = os.Stderr<br><br>	cmd.Env = []string{&quot;PS1=-[ns-process]- # &quot;}<br><br>	cmd.SysProcAttr = &amp;syscall.SysProcAttr{<br>		Cloneflags: syscall.CLONE_NEWUTS,<br>	}<br><br>	if err := cmd.Run(); err != nil {<br>		fmt.Printf(&quot;Error running the /bin/sh command - %s\n&quot;, err)<br>		os.Exit(1)<br>	}<br>}</pre><p>As you can see, there’s nothing particularly complicated here. We’re simply creating a *exec.Cmd, piping through stdin/out/err from the calling process and setting the PS1 environment variable on the new process (this just makes it easier to identify the namespaced shell when executing the program).</p><p>The interesting part is cmd.SysProcAttr, but before understanding SysProcAttr we need to take a deeper look at the underlying system calls that make up the namespaces API.</p><h4>📝 The namespaces API</h4><p>The <a href="http://man7.org/linux/man-pages/man7/namespaces.7.html">namespaces(7)</a> man page tells us there are 3 system calls that make up the API:</p><ol><li><a href="http://man7.org/linux/man-pages/man2/clone.2.html">clone(2)</a> - creates a new process</li><li><a href="http://man7.org/linux/man-pages/man2/setns.2.html">setns(2)</a> - allows the calling process to join an existing namespace</li><li><a href="http://man7.org/linux/man-pages/man2/unshare.2.html">unshare(2)</a> - moves the calling process to a new namespace</li></ol><p>unshare() may look familiar from the previous article. This is the system call that gets invoked when running the unshare command. The call we&#39;re interested in this time is clone(), as clone() gets called as part of Go’s exec.Run().</p><p>When calling clone() it&#39;s possible to pass one or more CLONE_* flags. Each namespace has a corresponding CLONE flag - CLONE_NEWNS, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWPID, CLONE_NEWNET, CLONE_NEWUSER and CLONE_NEWCGROUP. The execution context of the cloned process is, in part, defined by the flags passed in.</p><p>Back up to Go land and SysProcAttr, SysProcAttr allows us to set attributes on the *exec.Cmd. By specifying the Cloneflags attribute, we&#39;re telling Go to pass the corresponding CLONE_* flags through to system calls to clone(). And thus we can control which namespaces we&#39;d like our process to be executed in.</p><p>Compile and run the program and you will be dropped into a /bin/sh process that&#39;s running in a new UTS namespace. Note that the program must be run as the root user.</p><p>💁 <em>The following has been tested on Ubuntu 16.04 Xenial with Go 1.7.1</em></p><pre>$ go build<br>$ sudo ./ns-process<br>-[ns-process]- #</pre><p>Great! We’ve been dropped into a new shell that’s supposedly running in a new UTS namespace. Let’s confirm that this is the case.</p><pre>-[ns-process]- # readlink /proc/self/ns/uts<br>uts:[4026532410]<br>-[ns-process]- # exit<br>$ readlink /proc/self/ns/uts<br>uts:[4026531838]</pre><p>The contents of /proc/self/ns/uts include the namespace type (uts) and the inode number of the namespace. The fact that the inode number is different inside the ns-process shell compared to outside it implies that these two processes are indeed running in different UTS namespaces.</p><p>Not bad at all! But, we can do better. At the moment we’re only requesting a single new namespace for the process. Let’s throw in a few more to spice things up a little. This can be achieved by adding additional flags to Cloneflags, as follows.</p><pre># Git repo: <a href="https://github.com/teddyking/ns-process">https://github.com/teddyking/ns-process</a><br># Git tag: 1.1<br># Filename: ns_process.go</pre><pre>...<br>cmd.SysProcAttr = &amp;syscall.SysProcAttr{<br>		Cloneflags: syscall.CLONE_NEWNS |<br>			syscall.CLONE_NEWUTS |<br>			syscall.CLONE_NEWIPC |<br>			syscall.CLONE_NEWPID |<br>			syscall.CLONE_NEWNET |<br>			syscall.CLONE_NEWUSER,<br>	}<br>...</pre><p>Compile and run the program again, and this time you’ll be dropped into a /bin/sh process that&#39;s running in a new Mount, UTS, IPC, PID, Network and User namespace.</p><p>💡 When requesting a new User namespace alongside other namespaces, the User namespace will be created first. User namespaces can be created without root permissions, which means we can now drop the sudo and run our program as a non-root user! I’ll go into more detail about the user namespace in a later article.</p><p>This is all well and good, and at a basic level does allow us to run processes in new namespaces from Go. However, IRL it’s not really all that useful … We’re missing a lot of setup required to fully initialise and configure the namespaces. For example:</p><ul><li>We’ve requested a new Mount namespace (CLONE_NEWNS) but are currently piggybacking off the host&#39;s mounts and rootfs</li><li>We’ve requested a new PID namespace (CLONE_NEWPID) but haven&#39;t mounted a new /proc filesystem</li><li>We’ve requested a new Network namespace (CLONE_NEWNET) but haven&#39;t setup any interfaces inside the namespace</li><li>We’ve requested a new User namespace (CLONE_NEWUSER) but have failed to provide a UID/GID mapping</li></ul><p>And so it appears that we’ve still got plenty of work cut out for us.</p><h4>📺 On the next…</h4><p>We’ve seen how to run a process in a new set of namespaces using Go, but how do we configure and initialise the namespaces so they are ready for use? The answer to this and plenty more coming up, stay tuned…</p><p><strong>Update</strong>: Part 3, “Namespaces in Go - User” has been published and is available <a href="https://medium.com/@teddyking/namespaces-in-go-user-a54ef9476f2a">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3f0fc1ff69a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux Namespaces]]></title>
            <link>https://medium.com/@teddyking/linux-namespaces-850489d3ccf?source=rss-c028e49f8ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/850489d3ccf</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[namespaces]]></category>
            <dc:creator><![CDATA[Ed King]]></dc:creator>
            <pubDate>Sat, 10 Dec 2016 14:37:22 GMT</pubDate>
            <atom:updated>2017-01-10T08:42:08.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Linux namespaces comprise some of the fundamental technologies behind most modern-day container implementations. At a high level, they allow for isolation of global system resources between independent processes. For example, the PID namespace isolates the process ID number space. This means that two processes running on the same host can have the same PID!</p><p>This level of isolation is clearly useful in the world of containers. Without namespaces, a process running in container A <em>could</em>, for example, umount an important filesystem in container B, or change the hostname of container C, or remove a network interface from container D. By namespacing these resources, the process in container A isn’t even aware that the processes in containers B, C and D exist.</p><p>It follows that you can’t interfere with something if it’s not visible to you. And that’s really what namespaces provide - a way to limit what a process can see, to make it appear as though it’s the only process running on a host.</p><p>Note that namespaces <em>do not</em> restrict access to physical resources such as CPU, memory and disk. That access is metered and restricted by a kernel feature called ‘cgroups’.</p><h4>👟 Kicking the tyres</h4><p><em>The following has been tested on an Ubuntu 16.04 Xenial machine</em></p><p>Let’s jump straight in with a practical example of namespaces in action.</p><pre>$ unshare -h<br><br>Usage:  <br> unshare [options] &lt;program&gt; [&lt;argument&gt;...]<br><br>Run a program with some namespaces unshared from the parent.<br><br>Options:  <br> -m, --mount[=&lt;file&gt;]      unshare mounts namespace<br> -u, --uts[=&lt;file&gt;]        unshare UTS namespace (hostname etc)<br>...</pre><p>The unshare command allows you to run a program with some namespaces ‘unshared’ from its parent. Essentially what this means is that unshare will run whatever program you pass it in a new set of namespaces.</p><p>Let’s run through an example using the UTS namespace. The UTS namespace provides isolation of the hostname and domainname system identifiers. This isolation can be tested by running hostname my-new-hostname inside a UTS namespaced /bin/sh process, and confirming that the hostname change is not reflected outside that process.</p><pre>$ sudo su                   # become root user<br>$ hostname                  # check current hostname<br>dev-ubuntu  <br>$ unshare -u /bin/sh        # create a shell in new UTS namespace<br>$ hostname my-new-hostname  # set hostname<br>$ hostname                  # confirm new hostname<br>my-new-hostname  <br>$ exit                      # exit new UTS namespace<br>$ hostname                  # confirm original hostname unchanged<br>dev-ubuntu</pre><p>Breaking this down, we start by running sudo su to become the root user. Root privileges are required to create <em>most</em> namespaces (the exception being the user namespace - more on that in a later article). Then we run hostname to confirm our current hostname (&#39;dev-ubuntu&#39; in my case).</p><p>Now for the exciting part! The unshare -u /bin/sh command drops us into a shell that&#39;s running in a new, separate UTS namespace. We then run hostname my-new-hostname to set the hostname inside the new UTS namespace only. The change can be confirmed by running hostname again.</p><p>Lastly we exit the namespaced shell and run hostname one last time. We can see that the value for the hostname matches the original value, despite having run hostname my-new-hostname in between. This is because that change only took effect inside the new UTS namespace.</p><h4>👑 7 namespaces to rule them all</h4><p>The above example demonstrates the UTS namespace, but the fun doesn’t end there. At the time of writing there are 7 namespaces available:</p><ol><li>Mount - isolate filesystem mount points</li><li>UTS - isolate hostname and domainname</li><li>IPC - isolate interprocess communication (IPC) resources</li><li>PID - isolate the PID number space</li><li>Network - isolate network interfaces</li><li>User - isolate UID/GID number spaces</li><li>Cgroup - isolate cgroup root directory</li></ol><p>Most container implementations make use of the above namespaces in order to provide the highest level of isolation between separate container processes. Although note that the cgroup namespace is slightly more recent than the others and isn’t as widely used.</p><h4>📺 On the next …</h4><p>The unshare command is great, but what happens when we want more fine-grained control over the namespaces in our programs? The answer to this and plenty more coming up, stay tuned…</p><p><strong>Update</strong>: Part 2, “Namespaces in Go - Basics” has been published and is available <a href="https://medium.com/@teddyking/namespaces-in-go-basics-e3f0fc1ff69a">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=850489d3ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>