<?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 Satish Thakur on Medium]]></title>
        <description><![CDATA[Stories by Satish Thakur on Medium]]></description>
        <link>https://medium.com/@satish.manit?source=rss-1835642ee3cb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IkVrxNC_bHzMM9C-</url>
            <title>Stories by Satish Thakur on Medium</title>
            <link>https://medium.com/@satish.manit?source=rss-1835642ee3cb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:05:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satish.manit/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[Debug Story — How File Ownership got Changed]]></title>
            <link>https://medium.com/@satish.manit/debug-story-how-file-ownership-got-changed-246e36737bc8?source=rss-1835642ee3cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/246e36737bc8</guid>
            <category><![CDATA[sftp]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[ebs-volume]]></category>
            <category><![CDATA[inode]]></category>
            <dc:creator><![CDATA[Satish Thakur]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 12:37:40 GMT</pubDate>
            <atom:updated>2020-09-11T12:37:40.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>Debug Story — How File Ownership got Changed</h3><p>Few years back(around 2015) I had worked on a project where we automated the SFTP account creation for our clients. The problem statement was :</p><ol><li>We needed an automated way to have a dedicated SFTP account for our new client as part of client on-boarding.</li><li>The SFTP server should be Highly Available given it was being used to get/push data for the client on daily basis.</li></ol><p>As our infrastructure was on AWS, so we came up with the following high level design:</p><p>Every client would be provisioned a separate <a href="https://aws.amazon.com/ebs/?ebs-whats-new.sort-by=item.additionalFields.postDateTime&amp;ebs-whats-new.sort-order=desc">EBS</a> (storage configurable ) and the SFTP account would be created with <a href="https://en.wikipedia.org/wiki/Chroot">chroot</a> to that specific EBS. This was before <a href="https://aws.amazon.com/about-aws/whats-new/2016/06/amazon-elastic-file-system-efs-is-now-generally-available/">EFS</a> was launched in 2016.For example for client-1 we would create a new EBS lets call it EBS1, mount it to the SFTP server as /client-1 with chroot to /client-1. The account was configured to only allow SFTP (no ssh access). Also there was provision for both password based (as some legacy clients were not able to use key based authentication) as well as key based authentication (though key based authentication was preferred).</p><p>The architecture of the so called <em>managed SFTP Server</em> looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*t5NnbEaoOWldZSL4lGFQeg.png" /><figcaption>High Level Architecture</figcaption></figure><p>Apart from orchestrating creation of SFTP account the application also did:</p><ol><li>Automated backups (last N) of EBS volumes.</li><li>Long term retention of EBS data in S3 (periodic sync of EBS to S3 buckets).</li><li>Periodic purging of data in EBS based on policies.</li><li>File audit (number of file and size uploaded by users) using <a href="https://en.wikipedia.org/wiki/Inotify">iNotify</a>. Having these audit and metrics helped us debug another production issue and avoid outage (may be for another post).</li></ol><p>Taking this application to production allowed us one-click creation of SFTP account for any new client.</p><blockquote>Please note that the architecture and design choices were made 5 years back. There might be better ways to solve the problem today. The post is not about designing SFTP server but about one particular issue we found in production.</blockquote><p>The application used to save all the metadata related to a client account in DynamoDb (which would be used in HA part in next section) the simplified view of data stored:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCb6qBEyX6_hE7YyZ1ySMg.png" /><figcaption>Sample Data in Dynamodb</figcaption></figure><h4>Fault Tolerance</h4><p>For the HA part the server/EC2 machine was part of <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html">ASG</a> with min/max as 1. So in case of machine termination a new machine would spun up and the SFTP application used to get deployed to the new EC2 machine via AWS <a href="https://aws.amazon.com/codedeploy/">CodeDeploy</a>. Elastic IP was attached to the EC2 machine (SFTP server) and as part of bootstrap same IP was attached to the new server (this made sure endpoint is not changed for our clients).</p><p>The application on bootstrap scans the DynamoDb table to find what all accounts and EBS the server managed and recreated the user accounts as well as attached all the EBS. This made sure in case of any issues if the machine goes down, we get the new machine up and data/accounts everything is restored.</p><h4>Access denied to Client</h4><p>The managed SFTP server went live and helped us in smooth on-boarding of clients. Everything worked well until one day we got multiple escalations from different clients who were not able to access their files.</p><p>As we started looking in to the issue, we checked the basic things like all the EBS being mounted to the server etc which looked fine.</p><p>On further debug we found that old EC2 machine had degraded and ASG had terminated the degraded EC2 machine (expected behaviour). The fault tolerance had kicked in :</p><ol><li>New EC2 machine had come up.</li><li>The application was deployed to the machine and went through the bootstrap process. All the accounts were created and EBS were also mounted to the new server.</li><li>Only thing which was not correct was file ownership. Somehow file ownership had been changed. Client 1 files were owned by client 2, client 2 files were owned by client N and so on. SFTP connection as well as authentication was working fine but any get/put operations were failing.</li></ol><p>To unblock the clients we changed the ownership of files to right users manually.</p><h4>Why ownership changed?</h4><p>After mitigation we started deep diving into the issue as why the ownership changed and how to prevent it happening next time server goes down.</p><p>Here is the summary of what we found as root cause of the issue:</p><p>When we create users in Linux, every new user is assigned UID which is unique integer such as 1004. The data is stored in /etc/passwd file which was the root volume of EC2 machine in our case.</p><p>When we create files in Linux filesystem (we used <a href="https://en.wikipedia.org/wiki/Ext4">ext4</a>) the metadata about file is stored in something called inode. The inode stores data about file ownership as well. But it stores UID of the user and not the name of the user.</p><blockquote>Files are usually accessed by filename, they actually are not associated to any such name. Instead a file is referenced by inode (shorthand for information node) which is assigned an integer unique to the filesystem. This value is called the inode number, often abbreviated as i-number or ino. An inode stores metadata associated with a file, such as its modification timestamp, owner, type, length, and the location of the file’s data.</blockquote><p>In our case every EBS (which is a different filesystem)has its own inode space where it stores data about file ownership.</p><p>When the EC2 machine went down and new one came up, we created the users once again reading from DynamoDb. Now the user creation is not guaranteed to be in same order as was done on original server. Hence the user1 which previously used to have UID as 1002 might get UID of 1003 and hence the ownership of files on EBS got changed.</p><h4>How did we fix it?</h4><p>There are multiple ways to fix the issue depending upon the use case (few listed in summary). In this case user creation was dynamic and having a fixed AMI would not have helped us. We solved the issue by changing the file ownership of all the files in EBS on bootstrap (since all files on a given EBS were owned by same client).</p><h4>Summary</h4><p>The model where data is stored on EBS volume is used in various persistence solutions such as running mySql or mongo on EC2 where data is stored on EBS.</p><p>The same issue could happen if due to EC2 machine failure the EBS is now attached to a different instance and suddenly mysql user does not have permission to read the files.</p><p>There are multiple ways to solve the problem and the exact solution would depend on the use case.</p><ol><li>By having baked in AMI which has all the users created and using the same AMI to spin up EC2 machine where EBS would be attached.</li><li>By automating user creation via ansible or similar tools and hardcoding the UID for the users so that same user always has same UID across machines.</li><li>Changing the file permissions on the new machine on bootstrap.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=246e36737bc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error Handling with Optional in Java]]></title>
            <link>https://medium.com/@satish.manit/error-handling-with-optional-in-java-bb6db8f2cedc?source=rss-1835642ee3cb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb6db8f2cedc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[optionals]]></category>
            <dc:creator><![CDATA[Satish Thakur]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 04:28:43 GMT</pubDate>
            <atom:updated>2020-09-01T04:28:43.649Z</atom:updated>
            <content:encoded><![CDATA[<p>Prior to Java 8 there were typically two ways to handle errors. Either by throwing exceptions or by returning null from a method. There are drawbacks in both the approaches:</p><p>Throwing exceptions should be reserved for truly exceptional conditions and furthermore exceptions make the caller code boilerplate (in case of checked exceptions). Returning null does not have the above problem but makes the calling code verbose and error prone, as we need to do null check everywhere.</p><p>There is alternative to exceptions or returning null which is to use Optional. The primary benefit of exceptions: they allow us to consolidate and centralise the error handling logic, rather than being forced to distribute this logic throughout our codebase. We would see how we do not loose that benefit with Optional.</p><p>The technique used in Optional for error handing is similar to the old one (in C or even go), returning error codes to handle exceptions. But instead of error code we return a generic type called Optional which indicates presence or absence of a value. We would use the <a href="https://en.wikipedia.org/wiki/Higher-order_function">higher-order functions</a> to encapsulate common patterns of handing errors and propagate errors (central way to handle and propagate errors).</p><p>Optional type is present in Scala as well (called Option) which is very similar to Optional in java (except few details). We will go over that in another post.</p><h4>What is Optional?</h4><p>Optional&lt;T&gt; is the generic immutable container which can hold either a single non-null T or nothing at all (empty).</p><p>A method that conceptually returns T but under certain circumstances is unable to do so can return Optional&lt;T&gt; rather than throwing exception or returning null. In Java to create instance of Optional the class provide factory method.</p><pre>//Create Optional&lt;T&gt; from a non-null value T<br>Optional&lt;String&gt; name = Optional.of(&quot;john&quot;);<br>//Create Optional&lt;T&gt; indicating error condition<br>Optional&lt;String&gt; name = Optional.empty();</pre><h4>Optional Data Type</h4><p>Let’s take an example of a function which calculates mean. Without Optional the implementation would be:</p><pre>private Double mean1(Collection&lt;Double&gt; numbers){<br>    if(numbers.isEmpty()){<br>        throw new ArithmeticException(&quot;mean of empty collection&quot;);<br>    }<br>    return numbers.stream()<br>            .mapToDouble(Double::doubleValue)<br>            .sum()/numbers.size();<br>}</pre><p>As we see mean is a partial function which means the function does not have output for all the inputs.</p><blockquote>Partial Function is a function which is not defined for all the possible inputs.</blockquote><p>Now the same function can be defined using Optionals:</p><pre>private Optional&lt;Double&gt; mean(Collection&lt;Double&gt; numbers) {<br>    if (numbers.isEmpty()) {<br>        return Optional.<em>empty</em>();<br>    }<br>    return Optional.<em>of</em>(<br>            numbers.stream()<br>                    .mapToDouble(Double::doubleValue)<br>                    .sum() / numbers.size());<br>}</pre><p>Now the function mean is a total function. It has a well-defined value for every possible input value.</p><h4>Functions on Optionals</h4><p>There are few methods (and high order functions) defined in Optional class which we would also use for error handling are explained here:</p><ol><li>Map function. The signature of map functions is:</li></ol><pre>//Given a Optional&lt;T&gt; and a transforming function from T to U<br>Optional&lt;U&gt; map(Function&lt;? super T, ? extends U&gt; mapper)</pre><p>If the Optional has a value (not empty) the apply the mapper function and if the produced value is non-null return Optional wrapping the value or else return empty.</p><p>Simple example:</p><pre>//if mean produces a value then double it or return empty<br>Optional&lt;Double&gt; result = mean(numbers).map(n -&gt; n * 2);</pre><p>2. FlatMap function. The signature of flatMap function is:</p><pre>Optional&lt;U&gt; flatMap(Function&lt;? super T, Optional&lt;U&gt;&gt; mapper)</pre><p>FlatMap is similar to map, the only difference being now our mapper itself produces Optional. So if the Optional has a value (non empty) then apply the mapper function and return the result.</p><p><strong>Example:</strong></p><p>Following example shows how flatMap is used in calculating <a href="https://en.wikipedia.org/wiki/Variance">variance</a>. Thing to note here is variances is Optional and function mean also produces Optional. Hence we have to use flatMap to get the mean of the variances list.</p><pre>private double elemVariance(double elem, double mean){<br>    return Math.<em>pow</em>(elem - mean, 2);<br>}<br><br>private Optional&lt;Double&gt; variance(Collection&lt;Double&gt; numbers){<br>    Optional&lt;List&lt;Double&gt;&gt; variances = mean(numbers)<br>            .map(m -&gt; numbers.stream()<br>                    .map(n -&gt; elemVariance(n, m))<br>                    .collect(Collectors.<em>toList</em>()));<br>    <br>     return  variances.flatMap(this::mean);<br>}</pre><p>3. orElse. The signature are:</p><pre>public T orElse(T other)</pre><p>This is self explanatory. If the Optional has value then return the value or else return other. This is very similar to getOrdefault operation.</p><p><strong>Example:</strong></p><pre>Double num = mean(numbers).orElse(0.0);</pre><p>4. orElseGet. Signatures:</p><pre>T orElseGet(Supplier&lt;? extends T&gt; other)</pre><p>Similar to orGet but very subtle and important difference. The computation of other is lazy. Other is only calculated if the Optional is empty. We will see the importance of this difference in one of the examples.</p><p><strong>Example:</strong></p><pre>Double num = mean(numbers).orElseGet(() -&gt; service.getDefault())</pre><h4>Intuition on when to use map vs flatMap</h4><p>As we have seen exceptions let us consolidate the error handing and propagation to a central place. With Optionals we would use high order functions map, flatMap along with orElse/orElseGet etc to achieve the same.</p><p>Let’s start with map. Map function can be used to transform the result inside of Optional if it exists. We can think of it as proceeding with a computation on the assumption that error has not happened. It is also a way to defer the error handling to later code.</p><pre>//John&#39;s dept if John is an employee else Empty<br>lookupByName(&quot;john&quot;).map(e -&gt; e.getDepartment());</pre><p>Note that we do not have to explicitly check the result of lookupByName(“john”). We simply continue with the computation. If the lookupByName returns Empty this would abort rest of the computation and map will not get getDepartment at all (would simply return Empty).</p><p>Now coming to flatMap which is similar to map except the function we provide for computation itself can fail.</p><pre>//Not all employees have managers!!<br>lookupByName(&quot;john&quot;).flatMap(e -&gt; e.getManager());</pre><p>The above code can have error both in lookupByName (unknown employee) or employee is known but has no manager.</p><h4>Usage Scenerios</h4><p>Let’s assume we have a function to return office location to a given address. We have a AddressService which can give us pincode given the address. We have another service lets call locationService, which given the pincode can give us office location. Note that both the calls can fail (address may not have pincode, or a given pincode has no office location). Below is one of the implementation where error handling is done using exception.</p><pre>public interface AddressService{<br>    PinCode getPincode(Address address);<br>}<br><br>public interface LocationService{<br>    OfficeLocation getOfficeLocation(PinCode pincode);<br>    OfficeLocation getDefaultLocation();<br>}<br><br><br>public OfficeLocation getOfficeLocation(Address address){<br><br>    PinCode pc = null;<br>    try {<br>         pc = addressService.getPincode(address);<br>    }catch(Exception ex){<br>        return locationService.getDefaultLocation();<br>    }<br>    <br>    OfficeLocation loc = null;<br>    <br>    try{<br>        loc = locationService.getOfficeLocation(pc);<br>    }catch (Exception ex){<br>        return locationService.getDefaultLocation();<br>    }<br>    return loc;<br>}</pre><p>Now lets look at how we can implement the same using Optionals:</p><pre>public interface AddressService{<br>    Optional&lt;PinCode&gt; getPincode(Address address);<br>}<br><br>public interface LocationService{<br>    Optional&lt;OfficeLocation&gt; getOfficeLocation(PinCode pincode);<br>    OfficeLocation getDefaultLocation();<br>}<br><br><br>public OfficeLocation getOfficeLocation(Address address){<br>    return addressService.getPincode(address)<br>            .flatMap(locationService::getOfficeLocation)<br>            .orElseGet(() -&gt; locationService.getDefaultLocation());<br>}</pre><p>Important point above is to use orElseGet (lazy). If we use orElse we would end up making call to getDefaultLocation even the cases where both getPinCode and getOfficeLocation have produced values.</p><h4>Summary</h4><p>In case of partial functions, Optionals let us handle the error cases in more idiomatic way (also making the function total function). The high order functions like map, flatMap, orElseGet along with other functions like orElseThrow, orElse makes the Optionals <a href="https://en.wikipedia.org/wiki/Function_composition_(computer_science)#:~:text=In%20computer%20science%2C%20function%20composition,to%20build%20more%20complicated%20ones.&amp;text=The%20ability%20to%20easily%20compose,built%20by%20composing%20whole%20programs.">composable</a> and allow us to centralise the error handling as well as error propagation (as we have seen with deferred error handing both in map and flatMap).</p><p>So next time your are tempted to use Null or exception to communicate errors, see if Optionals is the right choice for the use-case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb6db8f2cedc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>