<?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 Ido Ozeri on Medium]]></title>
        <description><![CDATA[Stories by Ido Ozeri on Medium]]></description>
        <link>https://medium.com/@imunscarred?source=rss-a10cb189901------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Ido Ozeri on Medium</title>
            <link>https://medium.com/@imunscarred?source=rss-a10cb189901------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:40:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imunscarred/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[Exploring the Power of Pulumi Dynamic Providers — a Practical Example in Python]]></title>
            <link>https://medium.com/@imunscarred/exploring-the-power-of-pulumi-dynamic-providers-a-practical-example-in-python-aac002db2c78?source=rss-a10cb189901------2</link>
            <guid isPermaLink="false">https://medium.com/p/aac002db2c78</guid>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[pulumi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Ido Ozeri]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 11:03:02 GMT</pubDate>
            <atom:updated>2024-10-14T11:03:02.779Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring the Power of Pulumi Dynamic Providers — a Practical Example in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGNK7p10LlrwOojE_A3BOw.png" /></figure><p>In the ever-evolving landscape of Infrastructure as Code (IaC), Pulumi has emerged as a powerful tool, allowing developers to define cloud infrastructure using familiar programming languages. While Pulumi’s standard providers cover a wide range of cloud services, there are times when you need to manage resources that don’t have built-in support. This is where Pulumi’s dynamic providers come into play, offering a flexible solution for custom resource management.</p><p>Recently, I encountered such a scenario when I needed to create and manage GitHub runner groups programmatically. GitHub’s API doesn’t have native support in Pulumi, but thanks to the dynamic provider feature, I was able to seamlessly integrate this functionality into my infrastructure code. This article will walk you through my experience, demonstrating how to leverage dynamic providers to interact with GitHub’s API and manage runner groups effectively (or any other service provider for that matter).</p><h3>Understanding Dynamic Providers</h3><p>Before we dive into the implementation, let’s briefly explore what dynamic providers are and why they’re useful. In Pulumi, a dynamic provider is a resource that implements custom create, read, update, and delete (CRUD) operations. This allows you to manage resources that aren’t covered by existing providers or to implement custom logic for resource management.</p><p>More on that in the <a href="https://www.pulumi.com/docs/iac/concepts/resources/dynamic-providers/">official Pulumi documentation</a>.</p><h3>Clients Implementation</h3><p>At the base of the implementation, we have the Github client that’s responsible for constructing the base API call to the Github API. <br>Notice how we fetch some configuration from Pulumi config, and the API token from an environment variable.</p><p>base_client.py:</p><pre>import os<br>import requests<br>from pulumi import Config<br>from typing import Dict, Tuple<br><br>class BaseGitHubClient:<br>    def __init__(self, stack_config: Config) -&gt; None:<br>        self.github_server_url = stack_config.require(&quot;github_server_url&quot;)<br>        self.org_name = stack_config.require(&quot;org_name&quot;)<br>        self.github_token_env_var = &quot;GH_PERSONAL_ACCESS_TOKEN&quot;<br>        <br>        token = os.getenv(self.github_token_env_var)<br>        if not token:<br>            raise Exception(f&quot;{self.github_token_env_var} environment variable is not set&quot;)<br><br>        self.headers = {<br>            &quot;Authorization&quot;: f&quot;token {token}&quot;,<br>            &quot;Accept&quot;: &quot;application/vnd.github.v3+json&quot;<br>        }<br>        <br>        self._validate_token()<br><br>    def _validate_token(self) -&gt; None:<br>        url = f&quot;{self.github_server_url}/user&quot;<br>        response = requests.get(url, headers=self.headers)<br>        if response.status_code != 200:<br>            raise Exception(f&quot;Invalid GitHub token, api response: {response.text}&quot;)<br><br>    def get_api_url_and_headers(self) -&gt; Tuple[str, Dict[str, str]]:<br>        return self.github_server_url + f&#39;/orgs/{self.org_name}&#39;, self.headers</pre><p>Now that we have a base client, we can create a dedicated client for our use case: Github Runner Groups.</p><p>clients.py:</p><pre>import requests<br>import json<br>from typing import Dict, Any, List<br>from requests.exceptions import HTTPError<br><br>from .base_client import BaseGitHubClient<br><br>class RunnerGroupClient():<br>    def __init__(self, client: BaseGitHubClient) -&gt; None:<br>        self.github_api_url, self.headers = client.get_api_url_and_headers()<br><br>    def _get_api_path(self) -&gt; str:<br>        return f&quot;{self.github_api_url}/actions/runner-groups&quot;<br><br>    def create_runner_group(self, name: str, *args, **kwargs) -&gt; int:<br>        data = {<br>            &quot;name&quot;: name,<br>            **kwargs<br>        }<br>        try:<br>            response = requests.post(self._get_api_path(), headers=self.headers, data=json.dumps(data))<br>            response.raise_for_status()<br>            return response.json()[&quot;id&quot;]<br>        except HTTPError as e:<br>            raise Exception(f&quot;Failed to create runner group &#39;{name}&#39;: {e.response.status_code}, {e.response.json()}&quot;)<br><br>    def get_runner_group(self, group_id: str) -&gt; Dict[str, Any]:<br>        url = self._get_api_path() + f&quot;/{group_id}&quot;<br>        try:<br>            response = requests.get(url, headers=self.headers)<br>            response.raise_for_status()<br>            return response.json()<br>        except HTTPError as e:<br>            raise Exception(f&quot;Failed to get runner group with ID &#39;{group_id}&#39;: {e.response.status_code}, {e.response.json()}&quot;)<br><br>    def update_runner_group(self, group_id: str, **kwargs) -&gt; None:<br>        url = self._get_api_path() + f&quot;/{group_id}&quot;<br>        try:<br>            response = requests.patch(url, headers=self.headers, data=json.dumps(kwargs))<br>            response.raise_for_status()<br>        except HTTPError as e:<br>            raise Exception(f&quot;Failed to update runner group with ID &#39;{group_id}&#39;: {e.response.status_code}, {e.response.json()}&quot;)<br><br>    def delete_runner_group(self, group_id: str) -&gt; None:<br>        url = self._get_api_path() + f&quot;/{group_id}&quot;<br>        try:<br>            response = requests.delete(url, headers=self.headers)<br>            response.raise_for_status()<br>        except HTTPError as e:<br>            raise Exception(f&quot;Failed to delete runner group with ID &#39;{group_id}&#39;: {e.response.status_code}, {e.response.json()}&quot;)</pre><p>The RunnerGroupClient class implements the required methods to effectively manage Runner Groups. These are just the API calls we’ll be making to the Github API in that context, it has almost nothing to do with Pulumi (except the use of Pulumi config), and can work as a standalone code. Next, we’ll see how they integrate with the Pulumi Dynamic Provider.</p><h3>Dynamic Provider Implementation</h3><p>Now we’re getting to the interesting stuff. We have our clients that interact with the Github API, so let’s integrate them into a Pulumi Dynamic Provider.</p><p>providers.py:</p><pre>from pulumi.dynamic import (<br>    ResourceProvider, <br>    CreateResult, <br>    UpdateResult, <br>    DiffResult, <br>    ReadResult<br>)<br>from typing import Dict, Any<br><br>from .clients import RunnerGroupClient<br><br>class RunnerGroupProvider(ResourceProvider):<br>    def __init__(self, github_client: RunnerGroupClient):<br>        self.client = github_client<br><br>    def create(self, props: Dict[str, Any]) -&gt; CreateResult:<br>        group_id = self.client.create_runner_group(**props)<br>        return CreateResult(id_=str(group_id), outs=props)<br><br>    def read(self, id_: str, props: Dict[str, Any]) -&gt; ReadResult:<br>        group = self.client.get_runner_group(id_)<br>        return ReadResult(id_, outs=group)<br><br>    def update(self, id_: str, olds: Dict[str, Any], news: Dict[str, Any]) -&gt; UpdateResult:<br>        changes = {key: value for key, value in news.items() if olds.get(key) != value}<br><br>        if changes:<br>            self.client.update_runner_group(id_, **changes)<br><br>        return UpdateResult(outs=news)<br><br>    def delete(self, id_: str, props: Dict[str, Any]) -&gt; None:<br>        self.client.delete_runner_group(id_)<br><br>    def diff(self, id_: str, olds: Dict[str, Any], news: Dict[str, Any]) -&gt; DiffResult:<br>        group = self.client.get_runner_group(id_)<br>        diffs = []<br>        changes = False<br><br>        for key in news:<br>            if key in group and group[key] != news[key]:<br>                diffs.append(key)<br>                changes = True<br><br>        stables = [key for key in news if key not in diffs]<br><br>        return DiffResult(<br>            changes=changes,<br>            replaces=[],<br>            stables=stables,<br>            delete_before_replace=False<br>        )</pre><p>As you can see, our dynamic provider inherits from ResourceProvider that’s part of the pulumi.dynamic built-in package. Here we’ve implemented CRUD operations, and in each operation called the corresponding client method.</p><p>So far we’ve created the clients and the providers. Now it’s time to create the custom resource and define the configuration properties it might have.</p><h3>Dynamic Resource Implementation</h3><p>Here we’re creating a RunnerGroup resource that will eventually be called from our __main__.py Pulumi program.</p><pre>from pulumi.dynamic import Resource<br>from pulumi import ResourceOptions<br>from typing import Optional, Dict, Any<br><br>from .providers import RunnerGroupProvider<br>from .clients import RunnerGroupClient<br><br>class RunnerGroup(Resource):<br>    def __init__(self,<br>                 name: str,<br>                 github_client: RunnerGroupClient,<br>                 visibility: str,<br>                 allows_public_repositories: Optional[bool] = False,<br>                 restricted_to_workflows: Optional[bool] = True,<br>                 opts: Optional[ResourceOptions] = None<br>                 ):<br>        <br>        props = {<br>            &quot;name&quot;: name,<br>            &quot;visibility&quot;: visibility,<br>            &quot;allows_public_repositories&quot;: allows_public_repositories,<br>            &quot;restricted_to_workflows&quot;: restricted_to_workflows<br>        }<br><br>        provider = RunnerGroupProvider(github_client=github_client)<br><br>        super().__init__(provider, f&quot;RunnerGroup:{name}&quot;, props, opts)</pre><p>In this example I’ve only included <em>some </em>of the properties a Runner Group on Github supports.</p><p>In the __init__ method, we’re collecting all these properties to a dictionary called props. This dictionary is then passed to the super().__init__() call, which is how we provide these properties to the underlying Pulumi dynamic Resource class.</p><p>The RunnerGroupProvider we’re creating (with github_client as an argument) will use these props in its CRUD methods to interact with the GitHub API and manage the runner group resource.</p><p>At this stage, we’re done writing the underlying code for the dynamic provider. Let’s use it to create resources!</p><h3>Main Program Implementation</h3><p>Now it’s finally time to see everything in action and create our Github Runner Groups via Pulumi. Here’s the implementation of our __main__.py file:</p><pre>#!/usr/bin/env python3<br><br>from pulumi import Config, export<br>from modules.resources import RunnerGroup<br>from modules.clients import BaseGitHubClient<br>from modules.clients import RunnerGroupClient<br><br>#######################<br># Pulumi Stack Config #<br>#######################<br><br>stack_config = Config()<br><br>######################<br># Initialize Clients #<br>######################<br><br>base_github_client = BaseGitHubClient(stack_config=stack_config)<br>runner_group_client = RunnerGroupClient(client=base_github_client)<br><br>#################<br># Runner Groups #<br>#################<br><br>dev_runner_group = RunnerGroup(<br>    name=&quot;dev-runner-group&quot;,<br>    github_client=runner_group_client,<br>    visibility=&quot;selected&quot;,<br>    allows_public_repositories=True<br>)<br><br>prod_runner_group = RunnerGroup(<br>    name=&quot;prod-runner-group&quot;,<br>    github_client=runner_group_client,<br>    visibility=&quot;selected&quot;<br>)<br><br>##################<br># Output Control #<br>##################<br><br>export(&quot;dev_runner_group_id&quot;, dev_runner_group.id)<br>export(&quot;prod_runner_group_id&quot;, prod_runner_group.id)</pre><p>In this simple program we’re creating 2 runner groups and exporting their ID. The suggested Pulumi plan looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Sx-p2YydIDEqSZJ2LSg5A.png" /></figure><p>Once approved, Pulumi was able to create the resources and output their generated IDs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWW0omwE4cUHEO3rFCw5Sg.png" /></figure><p>Now let’s modify our code and see how Pulumi handles the update operation. For the dev group, let’s modify the allows_public_repositories to False and see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TTQKYq2JMLBrhS-wMX_Pg.png" /></figure><p>As you can see, Pulumi recognized this change and suggested to update the runner group in question.</p><h3>Limitations</h3><p>One thing I will point out is that although dynamic providers are a very convenient way of talking directly to the APIs, there are a couple of downsides:</p><ol><li>Any secrets specified in them are not encrypted in the state.</li><li>Because the code is serialized and pushed into the state, if the resource or the state gets messed up it can cause big issues and it’s not easy to back out or refresh to get updates from (in our case) GitHub and you basically have to destroy the stack and then start again with a fresh update.</li></ol><p>If these drawbacks are a blocker for you, you might want to try Pulumi’s Golang framework for building “native” providers <a href="https://github.com/pulumi/pulumi-go-provider">in this link</a>.</p><h3>Conclusion</h3><p>This article demonstrated why Pulumi, in my opinion, is the best tool for IAC, mainly (but not limited to) the freedom it provides. No more manual processes that lack provider support, create one yourself!</p><p>-Ido Ozeri</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aac002db2c78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Repairing MongoDB When WiredTiger.wt file is Corrupted]]></title>
            <link>https://medium.com/swlh/repairing-mongodb-when-wiredtiger-wt-file-is-corrupted-9405978751b5?source=rss-a10cb189901------2</link>
            <guid isPermaLink="false">https://medium.com/p/9405978751b5</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[restoration]]></category>
            <dc:creator><![CDATA[Ido Ozeri]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 14:38:21 GMT</pubDate>
            <atom:updated>2022-01-24T23:59:21.620Z</atom:updated>
            <content:encoded><![CDATA[<h3>Repairing MongoDB When WiredTiger.wt File is Corrupted</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8AVI1CDjVoh7Lf2Kxg8hg.jpeg" /></figure><h3>Preface</h3><p>In this article I’m going to cover the necessary procedure in order to salvage and repair your MongoDB database when the “WiredTiger.wt” file is corrupted. I’ll walk you through the recovery journey that we had for a few days and how we overcame it.</p><p>All the internet references on how to remedy such a disaster suggest that whenever the aforementioned file is missing/corrupted <strong>and you have no backups </strong>— you can pretty much kiss your data goodbye and start mourning.</p><p>Also, all possible solutions to MongoDB-related data corruption refer to a broken/corrupted collection or table, not one of the ‘WiredTiger’ files.<br>In this case you can use the ‘wt’ command-line utility that might be able to restore your corrupted collections.</p><p>But here we are specifically addressing a situation in which <strong>your collections exist</strong>, but the metadata file (“WiredTiger.wt”) is missing/corrupted.<br>When that happens, even the folks at Atlas Support would tell you that you’re screwed since this file is crucial to MongoDB collections, as stated by this answer from StackOverflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*RbIn5aEWIex8Q_wr8dqMqg.png" /><figcaption>Source: <a href="https://tinyurl.com/3r49ytk2">https://tinyurl.com/3r49ytk2</a></figcaption></figure><p>One thing is agreed upon everyone: the file cannot be re-created/restored by conventional tools that are at your disposal. No matter how hard you try.<br>And we did. Believe you me.</p><p>However, restoring this file <strong>is not the only method to recover your data</strong>.</p><p>If your data is critical to you and you still wish to be able to access it again, then go ahead and make some coffee, stick around and read through. It will be long and tedious, but I guarantee it’ll worth your while. It happened to our team and now I’m here writing about it for all the poor bastards that might get into the same predicament.</p><h3>Our Problem</h3><p>We’re running MongoDB version 3.2.7 on a standalone instance hosted at AWS and perform disk snapshot backups, twice-a-day. At the very same day that we planned to migrate the server into a ReplicaSet in Kubernetes — the server had an unknown issue and apparently didn’t shut-down gracefully. As a result, the ‘WiredTiger.wt” file size was suspiciously round at 4096 bytes and MongoDB failed to start with the following error:</p><pre>[1617558227:741955][14734:0x7f921ad91740], file:WiredTiger.wt, connection: WiredTiger.wt read error: failed to read 4096 bytes at offset 73728: WT_ERROR: non-specific WiredTiger error</pre><p>Unfortunately, all the backups that we had contained the same file size and were rendered useless at that point. The root cause is still unbeknownst to me (perhaps the data existed only in-memory and was never dumped into the file?)</p><p>We scorched the Internet looking for potential solutions, even reached out to Atlas Support with a lucrative offer to help us out — but to no avail. Everything seemed lost.</p><p>I called an old friend of mine whom I knew had a DBA consulting company back in the day called <a href="https://il.linkedin.com/company/brillix">Brillix</a>. He answered right away and referred me to their co-founder and CEO to try and solve the problem. That CEO is a super nice, highly skilled, hardcore MongoDB expert named <a href="https://www.linkedin.com/in/alonspiegel/">Alon Spiegel</a>.</p><p>Alon called me as soon as he had heard of our problem. He sounded very skeptical over our chances to recover the data since the 3.2.x version of MongoDB is notorious for potential data corruption (they improved significantly in later versions), but did suggest that if he were next to a computer (he was celebrating his son’s birthday) he’d probably try and create a new empty database and try to replace new collection files with the old ones that we had in an effort to “manipulate” MongoDB into reading the data inside those collections. “Not sure it’ll work, but I’d give it a try”, were his exact words.</p><p>However intrigued by the idea — we couldn’t keep him much longer on the line due to obvious family obligations and we didn’t quite understand what he was suggesting as the idea was lacking specifics.</p><p>Little did he know that his ‘far-fetched’ idea would be the precursor to the final solution. We have to give credit where credit is due (Thanks Alon!).</p><p>After more than 24 hours of trying to crack this, trying different things, shooting in the dark and basically almost losing any hope — our super talented and tenacious Head of R&amp;D, <a href="https://www.linkedin.com/in/eliran-yasharel-63075289">Eliran Yasharel</a> had a successful restoration of one collection (out of a total of almost 50).</p><h3>The Solution</h3><p>We deployed a MongoDB server version 4.0.5 since we knew the repairing capabilities of later versions were much superior to our 3.2.7 version. We also attached the disk that contained our precious data into the instance running the new MongoDB server.</p><p>From this point on, I’ll write in an <em>instructional fashion</em>:</p><p>Once deployed, create a new empty directory that will be used as the ‘dbpath’ of the new server. Directory paths are as follows:</p><ul><li>New Database collection files are stored in: <em>/data/new-db</em></li><li>Old Database collection files exist in: <em>/data/old-db</em></li></ul><p>Start the database application in the foreground by issuing:</p><pre>mongod --dbpath /data/new-db</pre><p>Once the server is up and running, connect to it via the ‘mongo’ command-line utility and create a new database, I called it ‘Recovery’ (but it’s best to name it after the original database). Then, insert some arbitrary document data into a new collection called ‘newDummyCollection1’, which represents the first collection that you’re going to recover:</p><pre>use Recovery<br>db.newDummyCollection1.insert({arbitrary: “value”})</pre><p>Which should result in this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*3L-EL8bSjkx6tlY_tHFmOg.png" /><figcaption>use Recovery ;</figcaption></figure><p>It’s important to note that you <strong>MUST </strong>put some document/data inside a collection in order to be able to manipulate MongoDB later on.</p><p>The next step is to determine the location on the disk in which the new collection you’ve just created has been saved to. This is done by running:</p><pre>db.newDummyCollection1.stats()</pre><p>This would yield a long JSON output, out of which you should search for the ‘uri’ object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*SM_gWyg2_nxP3MA3sJkWAA.png" /></figure><p>In this case, the full filename and location on the disk would be:</p><pre><strong>/data/new-db/collection-7-709196944276175444.wt</strong></pre><p>Confirm the file exists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WL8QI2e3DLL8XKzPrXsV5g.png" /></figure><p>Good. At this point, <strong>we stop the database and exit the mongo shell!</strong></p><p>Now comes the manipulation part: select a collection you wish to restore, in this case I’m now restoring collection file named “collection-13–8474722577232649897.wt”, so let’s copy this collection file and override the <strong>new collection file</strong> from the previous screenshot:</p><pre>cp /data/old-db/<strong>collection-13–8474722577232649897.wt</strong> \<br>/data/new-db/<strong>collection-7-709196944276175444.wt</strong></pre><p>Once the file has been copied successfully, run the ‘repair’ operation:</p><pre>mongod --dbpath /data/new-db --repair</pre><p>Now you’ll see that it repairs the collection and salvages the data:</p><pre>2021-04-06T13:57:35.813+0000 E STORAGE  [initandlisten] WiredTiger error (0) [1617717455:813361][787:0x7f6a10b78a40], file:collection-7-709196944276175444.wt, WT_SESSION.verify: __verify_filefrag_chk, 474: file ranges never verified: 1 Raw: [1617717455:813361][787:0x7f6a10b78a40], file:collection-7-709196944276175444.wt, WT_SESSION.verify: __verify_filefrag_chk, 474: file ranges never verified: 1<br>2021-04-06T13:57:35.813+0000 I STORAGE  [initandlisten] Verify failed on uri table:<strong>collection-7-709196944276175444</strong>. Running a <strong>salvage</strong> operation.<br>2021-04-06T13:57:35.819+0000 I INDEX    [initandlisten] build index on: Recovery.newDummyCollection1 properties: { v: 2, key: { _id: 1 }, name: &quot;_id_&quot;, ns: &quot;<strong>Recovery.newDummyCollection1</strong>&quot; }</pre><p>Start the database again:</p><pre>mongod --dbpath /data/new-db</pre><p>Verify that the data has been restored:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*fzPih1yZQsEwfMmE0beKtA.png" /></figure><p>Viola! A few steps ago we only had one arbitrary document that we inserted into that collection, now MongoDB has erased that document and was able to replace it with the data from our old collection by repairing it.</p><p>Repeat this operation for each and every collection that you have by incrementing the ‘newDummyCollection’ number for each collection.</p><p><strong>However</strong>, don’t pop your champagnes just yet, you still have one laborious task in order to complete the restoration process. Since the original table/collection names were stored inside ‘WiredTiger.wt’ file and are now lost, you’ll have to manually browse through each collection and determine which kind of data it holds. Then, you’ll have to rename the collection to match the original table name (otherwise your application would err, it does not know what ‘newDummyCollectionX’ represents..)</p><p>After reviewing the data inside the collection we recovered, we concluded that it was originally named ‘transactions’, so we rename it:</p><pre>db.newDummyCollection1.renameCollection(&quot;transactions&quot;)</pre><p>Once you recovered all the collections and renamed them properly, you probably want to import this data back into mongo 3.2.7 (remember, the restoration process was done on version 4.0.5).<br>You’d be very much surprised to hear that the ‘mongodump’ command of version 4.0.5 <strong>is working beautifully</strong> with the ‘mongorestore’ command of version 3.2.7!</p><p>This means that we were able to repair the data on mongo version 4.0.5, dump it using ‘mongodump’ version 4.0.5, copy the dump to a brand new and empty MongoDB version 3.2.7 and restore it using version 3.2.7 of ‘mongorestore’!</p><p><strong>One word on indexing</strong></p><p>You’ll still need to re-build your database indexes. In our case we save them in version control and ran a script that re-built them in minutes, so if you don’t have them saved somewhere — I’m leaving it for you to figure out.</p><h3>A Final Word on Backups</h3><p>After such an ordeal, the experts at <a href="https://www.linkedin.com/company/brillix">Brillix</a> suggested that from their experience, a disk snapshot backup is not ideal as the only means of MongoDB backup. They recommend using the native MongoDB backup tools (i.e. ‘mongodump’) and use the disk snapshot backup as a secondary backup method but certainly not as primary. Although running ‘mongodump’ on a large database with lots of collections might put some strain on the underlying hardware — it’s worth the cost of resources as the data reliability increases ten folds.</p><p>I hope someone out there finds this article useful. If so, please feel free to comment and share! Thanks to everyone involved in solving this incident.</p><p>-Ido Ozeri</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9405978751b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/repairing-mongodb-when-wiredtiger-wt-file-is-corrupted-9405978751b5">Repairing MongoDB When WiredTiger.wt file is Corrupted</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Own Custom Metrics API for Kubernetes Horizontal Pod Autoscaler]]></title>
            <link>https://medium.com/swlh/building-your-own-custom-metrics-api-for-kubernetes-horizontal-pod-autoscaler-277473dea2c1?source=rss-a10cb189901------2</link>
            <guid isPermaLink="false">https://medium.com/p/277473dea2c1</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[hpa]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ido Ozeri]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 14:19:37 GMT</pubDate>
            <atom:updated>2020-09-09T09:13:49.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nU1sRmFqlX820E5jZNLYLA.jpeg" /></figure><h3>Preface</h3><p>Kubernetes is a lot of fun, has lots of features and usually supports most of one’s whims as a container orchestration tool in a straight-forward fashion.</p><p>However, one request from my direct manager had made me sweat during my attempts to achieve it: auto-scale pods according to a complicated logic criteria.</p><p>Trying to tackle the task, my online research yielded partial solutions, and I ran through so many brick walls trying to crack this one, that I had to write an article about it in order to avoid future confusion regarding this matter for all poor souls who might try to scale-up their micro-services on a criteria that’s not CPU/Mem.</p><h3>The Challenge</h3><p>It all started when we needed to scale one of our deployments according to the number of pending messages in a certain queue of RabbitMQ.<br>That is a cool, not overly complicated task that can be achieved by utilizing Prometheus, Rabbitmq-exporter, and Prometheus-adapter together (hereinafter referred to as “the trio”).</p><p>With much enthusiasm and anticipation, I jumped right into the implementation only to later discover that one of my manager’s magic light-bulbs had switched on in his brain. It happens quite often, fortunately for him, and less fortunately for me as this usually means stretching the capabilities of the technology at hand with advanced and not-often-supported demands.</p><p>He came up with a better, more accurate scaling criteria for our deployment. In a nutshell: measures how long a message has been waiting in queue “A” using the message’s timestamp, and then performs some logic to determine the final value of the metric, which is always returned as a positive integer.</p><p>Well, that’s nice and all, but as far as my knowledge extends, the trio mentioned above is not able to perform the advanced logic my manager desired. After all it relies solely on metrics that RabbitMQ exposes, so I was left to figure out a solution.</p><p>The experience from trying to implement the trio has helped me gain a better view on how the Horizontal Pod Autoscaler works and reads data from sources.</p><p>As per the <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/#support-for-metrics-apis">documentation</a>, HPA works mainly against 3 APIs:</p><ul><li>Metrics</li><li>Custom Metrics</li><li>External Metrics</li></ul><p>My plan was to somehow harness the ‘custom metrics’ API and have it work against an internal application metrics API of our own, with the intention that the HPA would be able to read data from the internal API and scale accordingly.</p><p>This API could, in the future, be extended and serve as an application-metric for other deployments that need scaling based on internal application metrics or any kind of metrics for that matter.</p><p>This in essence involves the following tasks:</p><ol><li>Writing the code for our internal API</li><li>Creating a Kubernetes deployment and service for our internal API</li><li>Creating a Custom Metrics APIService in Kubernetes</li><li>Creating the HPA resource</li></ol><p>And with that in mind, let’s get to work.</p><p><strong>Please note</strong> that for the sake of demonstration, I used the ‘custom-metrics’ namespace in all yaml definitions. However, it’s an arbitrary selection so feel free to deploy it anywhere you want.</p><h3>Writing the Internal API Metrics Server</h3><p>Since web development isn’t a Devops specialty, I turned to the pros and asked my talented colleague <a href="https://www.linkedin.com/in/naama-yochai-27627917a/">Naama Yochai</a> to help out with getting this part of the equation done. She’s the one in the team in charge of the deployment that we’re trying to scale, so she also had high-stakes in this project.</p><p>Our basic requirement was a fast and simple web application, so we used JavaScript and the Express web-server, nothing fancy.</p><p>For the sake of POC we only need to return some mock integer value and Naama would later on write the code performing the advanced logic behind the scaling criteria.</p><p>However, we had no idea how to return the results in a way that the HPA would understand. What’s the expected output when querying our API?<br>We knew it was probably JSON, but had no idea of the structure nor the path on the web-server that HPA would search for when looking for that scale metric. Will it hit ‘/’ by default?</p><p>To better understand how APIs in Kubernetes work, we needed to take a look at the ‘metrics’ API (implemented by ‘metrics-server’) that was already deployed in our cluster. This API gives you CPU/Mem metrics for pods and worker nodes.</p><p>When we described the service, we noticed the ‘Self Link’ value in the metadata of the service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AR1f0CFOJ0ZqqNETieZLEw.png" /></figure><p>This gave us a hint as to the path in which APIs are expected to work in Kubernetes.</p><p>Once the root path was discovered, we created a small Docker container running NodeJS and ended up having a simple HTTP server running in port 6443.</p><p>However, we soon found the first chink in the armor: the Kubernetes API works exclusively with HTTPS web-servers (namely port 443) and cannot use insecure HTTP.</p><p>A couple of code tweaks later, and viola! The server was working in a secure protocol and listening on the same port.</p><p>Here’s the Dockerfile we used:</p><pre>FROM ubuntu:18.04</pre><pre># Install some debugging/editor tools</pre><pre>RUN apt-get update --fix-missing &amp;&amp; \<br> apt-get install -y \<br> build-essential \<br> net-tools \<br> iputils-ping \<br> vim \<br> curl \<br> nginx \<br> wget -y</pre><pre>RUN curl -sL <a href="https://deb.nodesource.com/setup_10.x">https://deb.nodesource.com/setup_10.x</a> | bash -<br>RUN apt-get install nodejs -y</pre><pre>WORKDIR /metric-exporter</pre><pre>COPY . /metric-exporter</pre><pre>RUN npm install</pre><pre>EXPOSE 6443<br>ENTRYPOINT [“/usr/bin/node”]<br>CMD [“./index.js”]</pre><h3>Creating a Kubernetes Deployment &amp; Service</h3><p>Now that the basic code outline for the internal API was ready, we proceeded with creating a deployment.</p><p>The metrics-exporter.yaml deployment file is fairly simple and looks like this:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: metrics-exporter<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: metrics-exporter<br>  template:<br>    metadata:<br>      labels:<br>        app: metrics-exporter<br>    spec:<br>      containers:<br>      - image: our-company/metrics-exporter<br>        name: metrics-exporter<br>        ports:<br>        - containerPort: 6443</pre><p>Once the pod was up and running, it needed to be backed-up by a corresponding service, so we applied the following metrics-exporter-service.yaml file:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: metrics-exporter<br>spec:<br>  ports:<br>  - port: 443<br>    protocol: TCP<br>    targetPort: 6443 <br>  selector:<br>    app: metrics-exporter</pre><p>Notice that the service is configured to run on port 443, but the container port is the aforementioned 6443 port.</p><p>Let’s test the internal API from within the pod. Since there’s no certificate to our web-server, we used the ‘-k’ switch:</p><p>curl -k <a href="https://localhost:6443/apis/custom.metrics.k8s.io/v1beta1/">https://localhost:6443/apis/custom.metrics.k8s.io/v1beta1/</a></p><p>And received the following output:</p><p>{“status”:”healthy”}</p><p>This would serve later on as a “Liveness probe” that the web-server is healthy and accepting requests.</p><p>So up until this point we had a working web-server on port 6443 that hopefully the APIService we were going to create would be able to communicate with. We had yet to figure out the path to retrieve metrics from, but more on that later.</p><h3>Creating the Custom Metrics APIService</h3><p>When applied, the below resource definition creates and registers the ‘<em>v1beta1.custom.metrics.k8s.io</em>’ APIService. Note that it has no namespace affinity and thus a global resource.</p><pre>apiVersion: apiregistration.k8s.io/v1beta1<br>kind: APIService<br>metadata:<br>  name: v1beta1.custom.metrics.k8s.io<br>spec:<br>  insecureSkipTLSVerify: true<br>  group: custom.metrics.k8s.io<br>  groupPriorityMinimum: 1000<br>  versionPriority: 5<br>  service:<br>    name: metrics-exporter<br>    namespace: custom-metrics<br>  version: v1beta1</pre><p>The most interesting bit in this APIService resource definition is the ‘service’ stanza. It basically registers a new APIService object that will bind the new API path to the Kubernetes service that’s implementing it, in our case it is the ‘metrics-exporter’ service in the ‘custom-metrics’ namespace.</p><p>This APIService would connect to our internal API Kubrenetes service in an attempt to retrieve our custom application metrics.</p><p>The chain of information looks like this:</p><p><em>APIService → Metrics-Exporter Kubernetes-Service → Metrics-Exporter Pod</em></p><p>If you’re using <a href="https://kubernetes.io/docs/reference/access-authn-authz/authorization/">RBAC</a> in your cluster, you’ll also need to create <em>ServiceAccount</em>, <em>ClusterRole</em> and <em>ClusterRoleBindings</em> for the custom metrics API. I’ve added all yaml definitions for the above in <a href="https://gist.github.com/Ido-Ozeri/c1af0d6413f828c941819c92ac3183ae">here</a>.<br>Without these you’ll get “Unauthorized” error messages since the API would fail to interact with Kubernetes resources.</p><p>Now, let’s examine the newly-created APIService:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*oTs34KfGzn1IeTCakOIUXQ.png" /><figcaption>kubectl get apiservices v1beta1.custom.metrics.k8s.io</figcaption></figure><p>We can see that it’s available, let’s describe it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CUcwxetqTe-sEfJv2oyHw.png" /></figure><p>It reports back that “all checks passed”, which bodes well for now. It would not have passed if we omitted the “Insecure Skip TLS Verify: true” line (again, there’s no signed certificate for our web-server), or if the deployment/service underneath it were not in place.</p><p>We’re almost done!</p><h3>Creating the HPA resource</h3><p>Now the last missing part of the puzzle is what I described earlier in this article and what consumed a lot of my time: the path from which the APIService would retrieve the metrics of our deployment. So far, our internal API returns a health check status in JSON format, which is merely enough to satisfy the APIService’s sanity checks.</p><p>We created the below HPA resource and started experimenting:</p><pre>apiVersion: autoscaling/v2beta1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: binder-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: binder <br>  minReplicas: 1<br>  maxReplicas: 30<br>  metrics:<br>  - type: Object<br>    object:<br>      target:<br>        kind: Service<br>        name: metrics-exporter<br>      metricName: seconds<br>      targetValue: 100</pre><p>Note that the deployment we’re asking to scale is called “binder”, it’s one of our prominent micro-services that gets a lot of requests.</p><p>When describing the HPA resource we created, we get the following error that the HPA cannot get the value of a metric named “seconds” and as a result nothing would be scaled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVk55-jLLzf08tcMztltdg.png" /></figure><p>At this stage we’re still ignorant and baffled as to the format that needs to be adhered to in regards to API calls done by Kubernetes.</p><p>Since we use a managed Kubernetes cluster (EKS) on AWS, we turned to their premium support for help with troubleshooting (as we don’t have the master logs and can’t see what’s really going on under the hood). After several back-and-forth correspondences and failed attempts to help with the matter, the support engineer sent me off with:</p><p>“<em>Custom metrics API implementation or implementing any Kubernetes configurations falls outside of the scope of support for us Premium Support Engineers and is done on a best-effort basis”</em></p><p>So much for best effort :-/</p><p>With little new debug information we received from AWS, we carried on doing our own experimentation and research.</p><p>After lots of reading on how APIs interact in Kubernetes and hours of trial and error, we had managed to crack this one! We finally understood what the proper way of interacting with the API was, and where the APIService was expecting to find the “seconds” metric.</p><p>It appears that the path convention is as follows:</p><pre>/apis/custom.metrics.k8s.io/v1beta1/namespaces/&lt;NAMESPACE&gt;/services/&lt;NAME_OF_CUSTOM_METRICS_SERVICE&gt;/&lt;METRIC_NAME&gt;’</pre><p>In our case, the full path was:</p><pre>/apis/custom.metrics.k8s.io/v1beta1/namespaces/custom-metrics/services/metrics-exporter/seconds</pre><p>And could be verified via:</p><pre>kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1/namespaces/custom-metrics/services/metrics-exporter/seconds</pre><p>However, that was not enough! We knew the path, but what was the expected output format when hitting that path?</p><p>We were naive at first to think that a simple {“seconds”:”10”} would do. Needless to say it wasn’t that simple, so again we used the ‘metrics’ API as a reference and deduced the supported JSON output format.<br><br>When piping it all into ‘jq’ for better readability, we get the following JSON output that originates from our internal API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*dEATK43XQzkPMWf-5NOq8w.png" /><figcaption>kubectl get — raw /apis/custom.metrics.k8s.io/v1beta1/namespaces/custom-metrics/services/metrics-exporter/seconds | jq</figcaption></figure><p>This, ladies and gentlemen, is the proper way of satisfying the APIService metric values. Your internal API code must output its metrics in the above way, or else no metric values would be processed by the HPA.</p><p>Now the HPA is happy and can retrieve the current value of the ‘seconds’ metric:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Nye5RnX7NeyqKgXWjINAg.png" /><figcaption>kubectl -n custom-metrics describe hpa binder-hpa</figcaption></figure><h3>Conclusion</h3><p>Once again we’re witnessing the sheer brilliance and dynamics of Kubernetes, as it offers its users a way to scale pods based on whatever criteria they desire. This internal ‘metrics-server’ of ours is now being further developed to support any kind of deployment in our cluster in terms of custom metrics auto-scaling.</p><p>Hope you enjoyed reading and please feel free to ask questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=277473dea2c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/building-your-own-custom-metrics-api-for-kubernetes-horizontal-pod-autoscaler-277473dea2c1">Building Your Own Custom Metrics API for Kubernetes Horizontal Pod Autoscaler</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>