<?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 Sinha Software Solutions on Medium]]></title>
        <description><![CDATA[Stories by Sinha Software Solutions on Medium]]></description>
        <link>https://medium.com/@sinhasoftwaresolutions?source=rss-c9bf13034fc1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HTZxiUBXiEJNMzXaDUqgOQ.jpeg</url>
            <title>Stories by Sinha Software Solutions on Medium</title>
            <link>https://medium.com/@sinhasoftwaresolutions?source=rss-c9bf13034fc1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:01:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sinhasoftwaresolutions/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[  Broken Window Theory and Tech Debt ]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/broken-window-theory-and-tech-debt-cf5591c05af1?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf5591c05af1</guid>
            <category><![CDATA[sdlc]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[tech-debt]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 16:32:31 GMT</pubDate>
            <atom:updated>2024-01-04T16:32:31.931Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, I try to highlight how the <a href="https://en.wikipedia.org/wiki/Broken_windows_theory">https://en.wikipedia.org/wiki/Broken_windows_theory</a> applies to the software world and how it can lead to restless situations.</p><h3>Say What?</h3><p>Here is a TL;DR of Broken Window Theory:</p><blockquote><em>In </em><a href="https://en.wikipedia.org/wiki/Criminology"><em>criminology</em></a><em>, the </em><strong><em>broken windows theory</em></strong><em> states that visible signs of </em><a href="https://en.wikipedia.org/wiki/Crime"><em>crime</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Antisocial_behavior"><em>antisocial behavior</em></a><em>, and </em><a href="https://en.wikipedia.org/wiki/Civil_disorder"><em>civil disorder</em></a><em> create an </em><a href="https://en.wikipedia.org/wiki/Urban_area"><em>urban environment</em></a><em> that encourages further crime and disorder, including serious crimes.</em><a href="https://en.wikipedia.org/wiki/Broken_windows_theory#cite_note-wilson_kelling-1"><em>[1]</em></a><em>The theory suggests that policing methods that target minor crimes such as </em><a href="https://en.wikipedia.org/wiki/Vandalism"><em>vandalism</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Loitering"><em>loitering</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Public_drinking"><em>public drinking</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Jaywalking"><em>jaywalking</em></a><em>, and </em><a href="https://en.wikipedia.org/wiki/Fare_evasion"><em>fare evasion</em></a><em> help to create an atmosphere of order and lawfulness.</em></blockquote><p>In the field of law, there are two types of definition — positive definition and negative definition. For those who believe in positive thinking let me rephrase the above in plain English</p><blockquote><em>Visible signs of countering minor crimes and working towards reducing it eventually leads to a safe atmosphere where serious crimes are prevented.</em></blockquote><p>You might have seen the <a href="https://starofmysore.com/cleanliness-awareness-through-wall-paintings/">Wall Painting Drives</a> in several cities of India in the last decade where NGOs, City Municipal Corporations, and Citizens come together to counter the menace of Garbage dumping, littering, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ouKTOhuczA0eKqmuPIXTKQ.png" /><figcaption><a href="https://starofmysore.com/cleanliness-awareness-through-wall-paintings/">https://starofmysore.com/cleanliness-awareness-through-wall-paintings/</a></figcaption></figure><p>Why do they do these drives? Because this is a psychological enforcement of keeping public places clean. Painting walls and boundaries with vibrant colors sends a message that this place should be kept clean and that active measures are being taken to ensure hygiene. These counter actions to petty littering eventually enforce cleanliness in the area and eventually city.</p><h3>Remind me again, What’s a Tech Debt?</h3><p>You may know this phenomenon already but for those who want to read more — <a href="https://en.wikipedia.org/wiki/Technical_debt">https://en.wikipedia.org/wiki/Technical_debt</a></p><h3>Debt? Isn’t it related to Finance and Economics? — Explain Tech and Monetary Debt to me!</h3><p>A tech debt definition can be drawn parallel to a monetary debt to a certain extent.</p><ol><li>Both require us to take a loan — In the case of tech debt, the loan is the shortcut or the better-term hack that you employ to solve the problem at hand quickly.</li><li>Both generate interest — In the case of tech debt, the interest is the ‘rework’ that you need to perform.</li><li>Both get compounded — If you don’t pay the debt on time, it will eventually compound to a sum that is bigger than your initial principal.</li></ol><h3>But……, Is it bad?</h3><p>We know that loans and debt are essential to the economy and the finance world and it is not necessarily bad but how does that play out in the tech world?</p><p>It is debatable and can vary from the market standing of a company — For a startup that has to compete with big players, moving fast is the only way. It is either First Mover advantage or Death!</p><p>But for a large company that caters to enterprises moving securely and robust is more important than moving fast. Imagine Apple releasing insecure features to the iPhone or a fintech releasing risky products. We don’t want that, do we?</p><p>Although I have compared tech debt with Monetary debt, IMO <em>tech debt is riskier than monetary debt</em>.</p><h3>You are building a House of Cards</h3><p>Building software with tech debt is like building a house of cards. It might look decent, and you may be able to live in it for some time but as you build more floors the poor choice of building material starts to manifest itself in the form of broken walls and worse a total collapse.</p><p>Have you seen this meme before?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*FGrm_mvkR4DuTIm1j7s3LA.png" /><figcaption><a href="https://www.reddit.com/r/funny/comments/6fp5a4/if_it_looks_stupid_but_works_it_aint_stupid/?rdt=61293">https://www.reddit.com/r/funny/comments/6fp5a4/if_it_looks_stupid_but_works_it_aint_stupid/?rdt=61293</a></figcaption></figure><p><strong>It is stupid! It is stupid! It is stupid! It is stupid! It is stupid! It is stupid! It is stupid! It is stupid! It is stupid!</strong></p><p>Imagine you are building an employee management system, but you do not have anyone experienced in Databases but you have employees experienced in File System Management. What would be a better choice?</p><ol><li>Use .txt files to store employee data; Or</li><li>Hire someone who knows the database</li></ol><p>If your answer is (1) not even <a href="https://onepunchman.fandom.com/wiki/Saitama">Saitama</a> can save you. The answer is obvious, you should get someone who can do the database for you, or you can train your employees in database.</p><p>You might be able to build the software with (1) but it would start failing the moment the number of employees goes beyond a limit.</p><h3>Compounding Effect of Tech Debt</h3><p>Note that the tech debt in the example above has a compounding effect, once you decide to pay the debt it has already grown disproportionally.</p><ol><li>You would need someone who understands Databases to help you migrate</li><li>You need to transfer knowledge of the system to this engineer</li><li>Your team would be overloaded because you will be maintaining both the old version of sw (the one which uses txt files) and the new version</li><li>You would need to revamp your code to support two versions</li><li>You will need to perform thorough testing (again!)</li><li>You would need a pipeline to migrate existing data to the database which may cause downtime</li><li>You would need a rollback mechanism, just in case the new version of the software does not work</li><li>There will be a new on-call load</li></ol><p>Even in this trivial example, you can see the impact of bad decisions and how they impact the software world.</p><h3>Broken Window Theory IRL of Software</h3><p>I want to discuss this section with the help of real examples. You will be able to relate to all these examples as a software engineer.</p><p>There are countless examples but some examples that I have seen often</p><h3>Let us hardcode it for now!</h3><p>Does this sound familiar to you? Now and then we see this hack come up when there is a production issue or a tight deadline. We lie to ourselves that let us hardcode the value now and we will fix it via a config later. But we seldom do that.</p><p>The hardcode mess spirals out of control and you end up doing more hard coding than what you expected.</p><p>Take an example of a case where we publish an SNS topic</p><pre>void publish(final Message message) {<br>  TOPIC_LIST.stream().forEach(<br>    m -&gt; snsPublisher.publish(m.getPriorityObject());<br>  );<br>}</pre><p>Now there is a new requirement that you should not publish this message for customers with free plan type. This requirement has come up in the light of a spam attack.</p><p>Now the first thought that comes to your mind is:</p><pre>void publish(final Message message) {<br>  TOPIC_LIST.stream().forEach(m -&gt; {<br>    if(!FREE.equals(m.getCustomer().planType())) {<br>      snsPublisher.publish(m.getPriorityObject());<br>    }<br>  });<br>}</pre><p>This works but what would happen if the spam attack is attempted with a FREEMIUM plan type?</p><p>You may want to extend above and do something like this</p><pre>List&lt;String&gt; BLOCKED_PLAN_TYPE = List.of(FREE, FREEMIUM);<br>void publish(final Message message) {<br>  TOPIC_LIST.stream().forEach(m -&gt; {<br>    if(!BLOCKED_PLAN_TYPE.contains(m.getCustomer().planType())) {<br>      snsPublisher.publish(m.getPriorityObject());<br>    }<br>  });<br>}</pre><p>This looks better because we have extracted away the plan types in a list. That is true in terms of code structure but it is not a good solution in terms of code design.</p><p><strong><em>Broken Window: </em></strong><em>This creates a slippery slope where any further changes would end up following this code design and it would make your code rigid and your control loose. See the section below to understand the tech debt.</em></p><p><strong>Try answering these questions:</strong></p><ol><li>What would happen if there is a new plan type that the spammer uses? (Code adaptability and finer control)</li><li>What would happen if there are only a handful of accounts (say 2) that are causing spam attacks? Is it justified to block this feature for all free customers? (Fine control)</li><li>What if I want to enable and disable the feature for certain plan types instantly? Would this work? (Feature toggling)</li></ol><p>You might have already realized that this is not a good solution to the problem of spam attacks.</p><p>A good solution would give you control of toggling this feature not only at the customer plant ype but also at the individual customer level.</p><p>Now, consider this solution</p><pre>void publish(final Message message) {<br>  TOPIC_LIST.stream().forEach(m -&gt; {<br>    if(!isBlocked(m.getCustomer())) {<br>      snsPublisher.publish(m.getPriorityObject());<br>    }<br>  });<br>}<br><br>boolean isBlocked(final Customer customer) {<br>  return blockedPlanTypeService.getPlanTypes().contains(customer.planType()) <br>  || customerBlockListService.isBlocked(customer.getId());<br>}</pre><p>As you can see the control of blocking a customer is shifted to the isBlocked(final Customer customer) method. This internally uses services to determine if the customer is blocked or not. The service is likely to get that information from a database or a config file.</p><p><strong><em>Fixed Window</em></strong><em>: In an ideal world changes to config would be independent of code and thus no new deployment needs to be triggered to change effect. This has fixed the broken window and would force any subsequent changes to follow the correct code design</em></p><h3>We should disable the failing flaky tests to unblock folks</h3><p>… and we never worked on the fix after that.</p><p><strong><em>Broken Window: </em></strong><em>The moment you start disabling flaky tests instead of fixing them you open an opportunity for others to follow the same path. Even if a test starts failing due to genuine reasons that need a code fix, engineers might end up ignoring it as there have been “similar flaky tests“ before. This also leads to a catastrophic scenario where the lack of these disabled unit tests leads to frequent regression.</em></p><p>Let us take an example -</p><pre>    private static final int MAX_ENTITY_LIST_SIZE = 10;<br>    private static final int ONE_OBJECT_SIZE = 177;    <br>    @Test<br>    void getSize() {<br>        assertEquals(0, EntityUtil.getSerializedSize(null));<br>        assertEquals(0, EntityUtil.getSerializedSize(createObject(null)));<br>        assertEquals(ONE_OBJECT_SIZE, EntityUtil.getSerializedSize(createEntity(DEFAULT_ENTITY))<br>        );<br>    }</pre><p>This test fails intermittently but works after 2–3 pipeline retries. Imagine that we <strong>disable</strong> this test so that developers are not blocked and worse frustrated due to this.</p><ol><li>What would happen if there is a version upgrade of EntityUtil dependencies? (Backward Compatibility)</li><li>What would happen if there is a bug in the EntityUtil Implementation? (Regression)</li></ol><p>These retrospective questions should convince you why disabling the above test is not a good idea.</p><p>Let us try to fix this Test:</p><pre>private static final int MAX_ENTITY_LIST_SIZE = 10;<br>private static final int ONE_OBJECT_MIN_SIZE = 117;<br>@Test<br>void getSize() {<br>    assertEquals(0, EntityUtil.getSerializedSize(null));<br>    assertEquals(0, EntityUtil.getSerializedSize(createEntity(null)));<br>    final int actualSize = EntityUtil.getSerializedSize(createEntity(DEFAULT_ENTITY));<br>    assertTrue(alertObjectSize &gt; ONE_OBJECT_MIN_SIZE - 1);<br>}</pre><p>The fix above is based on the explanation of how protobuf works. Repeated invocation of protobuf library to serialize does not guarantee the same size. You learn more <a href="https://protobuf.dev/programming-guides/encoding/#implications">here</a>.</p><p><strong><em>Fixed Window: </em></strong><em>Refraining from the practice of disabling test builds a culture in the team to get to the root cause and fix the issue.</em></p><h3>This would work as the customer would first do A and then B</h3><p>No, they won’t. Don’t trust your customers when it comes to how they use your product. Imagine a task management system that your clients use.</p><p>When they start working they put the task in IN_PROGRESS and once done they send a COMPLETED call.</p><p>While the task is in IN_PROGRESS you send a reminder every one hour.</p><p><strong>DB schema</strong></p><pre>CREATE TABLE action_item (<br>    id varchar(100) PRIMARY KEY,<br>    status varchar(100) default &#39;PENDING&#39;<br>);</pre><p><strong>Cron (Every Hour runs inside API server)</strong></p><pre>void sendNotification() {<br>  final List&lt;ActionItem&gt; inProgressItems = actionItemRepository.findByStatus(IN_PROGRESS);<br>  inProgressItems.forEach(<br>    item -&gt; notifier.notify(item.getId());<br>  );<br>}</pre><p><strong>API</strong></p><pre>void updateStatus(final ActionItem existingItem, final String newStatus) {<br>  existingItem.setStatus(newStatus);<br>  actionItemRepository.save();<br>}</pre><p>This is what you expected to happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*zAy9msqR0JqXCtDz-KPfxQ.png" /></figure><p>But this is what really happened. The customer has an automation setup which sends the status update of IN_PROGRESS and COMPLETED almost at the same time.</p><p>This results in wrong order of update. Since there is no check on the existing status, the state goes from COMPLETED → IN_PROGRESS and remains in that state infinitely.</p><p>This results in hourly api call for this customer indefinitely which will increase both cost and load on the system.</p><p><strong><em>Broken Window:</em></strong><em> Assuming orderly update in an event-based system and designing code to work with this assumption.</em></p><p>This broken window would eventually lead subsequent code to be written with the same assumption and will open a pit of risks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*3SINNWETAUm6YyWCRWoDUw.jpeg" /></figure><p>How do we solve this issue? See a solution below</p><pre>void updateStatus(final ActionItem existingItem, final String newStatus) {<br>  if(COMPLETED.equals(existingItem.getStatus())<br>    throw new UnsupportedOperationException(&quot;COMPLETED is a terminal state and it cannot be transitioned to &quot; + newStatus);<br>  }<br>  existingItem.setStatus(newStatus);<br>  actionItemRepository.save();<br>}</pre><p><strong><em>Fixed Window: </em></strong><em>You enforce state checks for every update to an entity. The upper layers of the code and their order should not be considered while implementing lower layers. Remember that the upper layers are specific and the lower layers are generic.</em></p><h3>Moving From Broken Windows to a Fix Windows culture which minimizes Tech Debt</h3><p>I believe that the health of a software system is directly related to the culture of the team. A good culture fosters confidence and support among team members. It helps them develop a sense of ownership. As the team owns more and more they think of long-term investments and eventually grow as engineers.</p><p>The leadership has a crucial role to play here, rewarding short-term achievements and quality sacrifices leads to a house of cards and compounds tech debt</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf5591c05af1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Don’t abuse any*()]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/dont-abuse-any-cb2a94cce9e4?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb2a94cce9e4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 11:20:48 GMT</pubDate>
            <atom:updated>2024-01-04T11:20:48.727Z</atom:updated>
            <content:encoded><![CDATA[<p>Did I mean any(body) or any(one) or any(thing)?</p><p>The answer might be disappointing for some but interesting to engineers. I meant the <a href="https://javadoc.io/doc/org.mockito/mockito-core/2.2.7/org/mockito/ArgumentMatchers.html">ArgumentMatchers</a> that we use in Java unit tests.</p><h3>What the heck is an ArgumentMatcher anyway?</h3><p>An <a href="https://www.baeldung.com/mockito-argument-matchers">ArgumentMatcher</a> is something that does a matching of an argument passed to a method. ArgumentMatchers are used in unit tests so that certain behaviors can be expressed (mocking) when a specific type of argument is passed.</p><p>Nothing fancy about the term or the usage.</p><h3>Talk is cheap, show me the code</h3><p>Let us see an example:</p><pre>Mockito.when(awsSnsAccessor.publishWithName(any())).thenReturn(new PublishResult());</pre><p>When the <em>awsSnsAccessor.publishWithName()</em> method is called with any argument, the return should be a new object of <em>PublishResult</em>.</p><p>This looks benign and a good mocking especially when you read it in the entirety of the test case:</p><pre>final AwsSnsAccessor awsSnsAccessor = Mockito.mock(AwsSnsAccessor.class);<br>final SourceDeleteDataEvent sourceDeleteDataEvent = new SourceDeleteDataEvent(awsSnsAccessor);<br>Mockito.when(awsSnsAccessor.publishWithName(any())).thenReturn(new PublishResult());<br>sourceDeleteDataEvent.publish(data);<br>Mockito.verify(awsSnsAccessor, Mockito.times(1)).publishWithName(any());</pre><p>We want to test the <em>SourceDeleteDataEvent#publish</em> method and want to make sure a message is published once using via <em>awsSnsAccessor</em> object. The verify statements make sure that the accessor was called once and when mocking ensure that an object is returned when <em>publishWithName()</em> is called so that we don’t see <em>NullPointerException</em>.</p><h3>Where is the problem?</h3><p><strong>Context</strong>: When a customer is migrated from region A to region B. We need to delete the customer data in the source i.e. in region A.</p><p>Let us see the implementation of the <em>publish()</em> method first, maybe you will find the issue:</p><pre>@Override<br>    public void publish(final MigrationData data) {<br>        final MigrationDataDeletionEvent dataEvent = new MigrationDataDeletionEvent(<br>                data.getMigrationId(), <br>                data.getCustomerId(),<br>                data.getSourceRealm(), // -----&gt;&gt;&gt;&gt;&gt;&gt;&gt; deletion realm<br>                data.getReportingPlatformOnMigration(),<br>                data.getDeletionTriggerTime()<br>        );<br><br>        DATA_DELETION_TOPICS.forEach(topic -&gt;<br>                publish(data, dataEvent, topic)<br>        );<br>}<br><br>private void publish(MigrationData data, MigrationDataDeletionEvent dataEvent, String topic) {<br>..<br>..<br>}</pre><p>If you have not guessed this yet then here is the big reveal.</p><blockquote><em>What would happen if I set the deletionRealm incorrectly?</em></blockquote><blockquote>data.getTargetRealm()</blockquote><p>You guessed right! A <strong>Sev 0</strong> because you <strong>deleted the customer data</strong> in the region where they are active.</p><p>It is a little far-fetched because generally you would have an integration test in place that is run before deployment to production or you may have run manual tests to confirm everything is working as expected.</p><p>The bit about manual intervention is dangerous in its way but let us not go into that discussion and focus on the issue at hand.</p><h3>Repeat after me</h3><p>→ This issue could have been caught in the unit test if it were exhaustive.</p><p>→ And how could this have been exhaustive?</p><p>→ By not using <em>any()</em> matcher.</p><p>Changing the test to check concrete objects:</p><pre>final PublishWithNameRequest request = new PublishWithNameRequest()<br>                .withTopicName(topic).withMessage(createRequestFromObject(data));<br>Mockito.when(awsSnsAccessor.publishWithName(request)).thenReturn(new PublishResult());<br>Mockito.verify(awsSnsAccessor, Mockito.times(1)).publishWithName(request);</pre><p>Notice how we are matching a concrete object, if the object does not match due to a mismatch in one of its fields, it will fail in the verify step.</p><h3>It doesn’t work that way (always)</h3><p>Indeed, at times creating an expected object is a big task in itself and sometimes impossible to do.</p><p>For example, imagine that we set the deletion time to the current system time.</p><pre>public void publish(final MigrationData data) {<br>        final MigrationDataDeletionEvent dataEvent = new MigrationDataDeletionEvent(<br>                data.getMigrationId(), <br>                data.getCustomerId(),<br>                data.getSourceRealm(),<br>                data.getReportingPlatformOnMigration(),<br>                Instant.EPOCH.toEpochMilli() // -----&gt;&gt;&gt;&gt;&gt;&gt;&gt; current time<br>        );<br><br>        DATA_DELETION_TOPICS.forEach(topic -&gt;<br>                publish(data, dataEvent, topic)<br>        );<br>}</pre><p>Now, how would you create a concrete object? The answer is either — (1) You modify the <em>SourceDeleteDataEvent</em> class to accept a child of the Instant class and use it to get the EOPC and then mock it in your test; or (2) you can use <a href="https://www.baeldung.com/mockito-argumentcaptor">ArgumentCaptors</a>.</p><h3>What the heck is an ArgumentCaptor?</h3><p>An ArgumentCaptor is something that allows us to capture the arguments passed to a method that can be inspected later.</p><p>ArgumentCaptor is perfect for this use case because we cannot build a concrete object which has the right timestamp but we need to verify the other fields of the object anyway.</p><pre>final ArgumentCaptor&lt;PublishWithNameRequest&gt; argumentCaptor = <br>ArgumentCaptor.forClass(PublishWithNameRequest.class);<br><br>final AwsSnsAccessor awsSnsAccessor = Mockito.mock(AwsSnsAccessor.class);<br>final SourceDeleteDataEvent sourceDeleteDataEvent = new SourceDeleteDataEvent(awsSnsAccessor);<br>Mockito.when(awsSnsAccessor.publishWithName(any())).thenReturn(new PublishResult());<br>sourceDeleteDataEvent.publish(data);<br>Mockito.verify(awsSnsAccessor, Mockito.times(1)).publishWithName(argumentCaptor.capture());<br><br>assertEquals(EXPECTED_PAYLOAD_MESSAGE_LOOKER, argumentCaptor.get(0).getMessage());</pre><p>See how we are back to mocking the behavior using <em>any()</em> matcher.</p><p>You must have noticed that we created an <em>argumentCaptor</em> and then used it in the verify method to capture the arguments passed to the <em>publishWithName()</em> method.</p><p>Now it is easier to verify specific fields of the <em>PublishWithNameRequest</em> object which is done subsequently using the <em>assertEquals</em> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*j5eqKJ4Yc4QgidEOmJsMSA.png" /></figure><p>The combination of <em>any()</em> with ArgumentCaptor is a formidable technique that enables you to write exhaustive tests and gives you control to verify individual fields of an object.</p><h3>Conclusion</h3><p>It is going to be an overhead if you start enforcing this as a requirement for every test that you write. You may not need to test all the concrete objects in all the tests.</p><p>Imagine you want to test if sns publish is skipped when a flag is set to true. In this case, you don’t care about the processing done in the method, all you care about is that the publish step is skipped when a flag is set. Assuming that other tests are already present that cover the concrete value matching, this is one of the situations where you can simply use <em>any()</em>. However, it would not harm to enhance it by using the class type.</p><pre>Mockito.when(awsSnsAccessor.publishWithName(PublishWithNameRequest.class)).thenReturn(new PublishResult());</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb2a94cce9e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster Execution: Shift Left, Left and Left]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/faster-execution-shift-left-left-and-left-362a5f0ac630?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/362a5f0ac630</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[execution]]></category>
            <category><![CDATA[project-management]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Sat, 27 May 2023 07:00:52 GMT</pubDate>
            <atom:updated>2023-05-27T07:00:52.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXxyuhOQJKvvOjmiqDveMg.png" /></figure><p>Some exceptions above 😉</p><h3>Why left? What is shifting left?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWrntCRbhE4j3EiUkqgTMA.png" /></figure><h4>Point Zero</h4><p>Point Zero is the <em>beginning,</em> analogous to the big bang or the first cause or the primary move. This is the point where things start, where ideas are conceived, and where the first step of execution is performed.</p><p>In short — <em>the point of origin</em>.</p><p>It is also a representation of time. Point zero is T0, where the project, feature, and program began to exist. Maybe as an idea, maybe as a research effort.</p><p>In Atlassian jargon, you may be used to calling this the <em>Wonder Phase</em></p><h3>Left</h3><p>Imagine you are at point 3 on the <em>Shifting Left 1.0</em> line. This is the point where you have begun developing a feature for <a href="https://github.com/princerachit/kalakaar">Kalaakar</a> Analytics. When you start writing code for infrastructure, you realise that there is a significant limitation on how you can configure your AWS Lambda. You realise that it is not possible to autoscale lambda deployments because it is not supported by the libraries that we have, there are other limitations too that you discover as you start writing more and more code.</p><p>What do you do in this situation?</p><h3>Break the barrier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5bEQ9IM7VI-Kjwxh24E5lQ.png" /></figure><p>You see this risk a bit late but then you decide to break the barrier. Make the call and move forward. Great ! You go to the library code owners and ask them if they can add this feature, they don’t have the bandwidth, so you decide to contribute to that feature. You ship that feature and are now ready to move forward!</p><h3>Take a step back</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZN2toIbUmciN9Bf76dy8WA.png" /></figure><p>In an alternate approach, you observe that this might be risky, as the feature development will take several days to make it production ready. This also might be one of several unanticipated issues that are yet to manifest.</p><p>You decide to take a step back and re-evaluate your design and feasibility. You observe that having a micros service is simpler, battle-tested and faster to develop (sorry, could not control my urge to share the hottest topic in tech <a href="https://thestack.technology/amazon-prime-video-microservices-monolith/">https://thestack.technology/amazon-prime-video-microservices-monolith/</a> ) than having a serverless design. It is not shiny and does not get you appraisals for loosely-coupled architecture from your colleagues, but it works. Maybe, you will be shy when you share this design in your next job interview and fear of getting judged on your skills. But the execution is a skill in itself. Remember, good execution is <em>simple execution</em>.</p><h3>Shifting Left</h3><p>In both of the approaches discussed the intention is to move <em>Right</em> toward the goalpost, but, there is an unwanted move toward the left. We want to minimise left moves in the execution axis.</p><p>How can we avoid these left moves on the execution axis? The answer is — to move the <em>risks</em> to the left. Of course, it is not always possible! Of course, we can’t get stuck in <a href="https://en.wikipedia.org/wiki/Analysis_paralysis">https://en.wikipedia.org/wiki/Analysis_paralysis</a> but we have to make this tradeoff, and it has to be made as early as possible.</p><p>This is counter intuitive to philosophy of <em>move fast, break fast, recover fast</em>. But it is not. The idea of faster execution and faster recovery needs to pivot itself. In order to execute fast we need a solid foundation and a platform that enables us to execute fast. You cannot mass assemble a car without a good assembly line. The better the assembly line is, the faster you ship a car!</p><blockquote><em>Let us focus on solid platform that lets us execute fast; rather than trying to do 100 manual steps fast, let us have one automated pipeline that does that 100 steps for us.</em></blockquote><p>Shift left in automation, risk mitigation, and vulnerability management.</p><h3>Shifting Left as an Engineer</h3><p>Ever been in a Postmortem review and wondered, “<em>this should have been done in the first place”. </em>Why was it not done? Maybe it was a miss, maybe it was deliberately skipped so that we can deliver fast (do you see a contradiction here?).</p><p>Spending reasonable time in design and testing does not slow us down, it gives us the confidence of shipping things fast. Remember the example I gave in preceding sections? If we analyse possible risks, and test out our design and code, there would be fewer issues during release. Imagine discovering a simple use case that fails on Analytics feature one day before the release date. We don’t want that, do we?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgV9bq_4lRyli9tpO_upNA.png" /><figcaption>Graph 1.0</figcaption></figure><p>The Graph 1.0 represents a plane comprised of two axis <em>X — Project lifecycle phase or the time</em> and <em>Y — Delivery Date Impact or Risk</em></p><p>As we move toward the right of the X axis, encountering an issue will block the release of the project. Fixing the issue can be difficult especially if it pertains to Architecture (e.g. lambda vs a server) or Compliance (e.g. BYOK vs Legacy Encryption). The earlier we find and highlight the issue (<strong>Highlight</strong> is the keyword here), the lesser impact we make on the project delivery date. It is easy to make changes in the initial phases than in the later phases — you would be more comfortable in swapping <a href="https://etcd.io/">etcd</a> with <a href="https://learn.microsoft.com/en-us/azure/cosmos-db/introduction">cosmos</a> on day 3 than on day 30.</p><h3>Habits, Tools, and Processes</h3><p>I believe there are 3 aspects to our work as engineers that needs tweaking or even a complete revamp to help us shift left and execute fast.</p><p>Change your habits — Do you raise a big 30-file change PR for review? If yes, then you need to change this habit. Raise small Pull Requests. Reviewing small PRs is easy and fast. Addressing and accommodating review changes is simpler and faster.</p><p>Prioritise PR reviews early in the day. This gives a lot of time for the author to address your comments.</p><p>Call out issues with the code and design. At worst it would be a false flag, at best, you will be delighting a customer, thus, saving reputation and money.</p><p><em>Exceptions </em>— Like any other engineering practice, exceptions exist to this — What if there is cross-timezone collaboration? What if there are zero overlaps in working hours? What if the deadline is tight? In these cases you should work with your reviewer to lay out a PR review plan — maybe have a short meeting to lock the approach and ship a big 20 file change PR with multiple commits which can be reviewed independently. Be careful when you ship a big PR, the only reason to ship such a big PR should be a deadline and blockers. The key to shift left in these cases is early communication.</p><p>Such a situation can also arise when you work on a PR/feature which involves a review from multiple teams or in a situation when you are working on an open-source project. Be aware, involve in the other team’s process to figure out the best way forward.</p><p>Get rid of the “<em>Not my responsibility</em>“ attitude. No, it does not mean you need to own up to every issue out there. You need to work with your colleagues to find the right owner. Can’t decide? Manager to the rescue.</p><p>Upgrade your Tools — Are you still relying on Snyk Scheduled Vuln scanner to scan your projects and raise Jira issues? It is time to move left — You can use Snyk plugin for intellij to scan your projects while you develop or integrate snyk pipeline checks, to never ship a risky dependency ever!</p><p>Are you still using cUrl commands on shell and manually doing indentations? Maybe <a href="https://www.postman.com/">Postman</a> can reduce that effort. It will not only reduce the effort but also make it easier for you to share those command collections with your colleague — DRY.</p><p>Want realtime pair programming feedback and suggestions? <a href="https://hello.atlassian.net/wiki/spaces/DEVPPROSAT/blog/2023/05/08/2571179384/April+Developer+Productivity+Newsletter#AI-Coding-Assistants-are-Here!">Github copilot</a> to the rescue!</p><p>Are you still manually checking for dependency releases? Why not use renovate?</p><p>Modify your Processes — Processes are as good as the results they give us. A process that slows us down with no apparent benefit and no compliance need can be ditched. Yes, there are obvious exceptions to this and we all know them well.</p><p>Automation plays a major role in process change. A good process ideally has a lot of automation. Think about testing code changes in staging. Do you block staging env to test out the changes that you are making? Why not have e2e test? Maybe there are limitations to your project deployment setup and you cannot write e2e test for your feature without manually testing on staging, then, how about writing e2e test to check for regression?</p><p>Why does a PR need confirmation about stage testing and unit testing in the comments? Why not have a Bitbucket task checklist? Allow merging the PR only when all the items of the task list are checked off.</p><p>The list can go on and on ….</p><p>Keep it lean — Leaner is better, Leaner is faster, Leaner is simpler, Leaner is agile, Leaner is iterable. Oftentimes, a lot of amazing features and processes slow us down. Maybe that automated e2e test per PR is not required when there is a change in the documentation folder. Maybe you can get rid of 5 reviewers per PR and just do away with 2. The idea is to reduce complexity. If there is a complexity that is visible, that is probably a sign of friction. If the complexity is hidden (or as we devs like to call it <em>abstracted</em> away), most of the time we will be happy to continue with the process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=362a5f0ac630" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I scored 99% in CKA first attempt[Not for beginners]]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/how-i-scored-99-in-cka-first-attempt-not-for-beginners-d57288f5148f?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d57288f5148f</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cka]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[exam]]></category>
            <category><![CDATA[cncf]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Mon, 30 Dec 2019 08:55:44 GMT</pubDate>
            <atom:updated>2019-12-30T08:55:44.777Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xq95ESImDdNbUmZyPP1rGw.png" /><figcaption>Score Card</figcaption></figure><h3>Background</h3><p>I have been working on <a href="https://github.com/kubernetes/kubernetes"><strong>Kubernetes</strong></a> for a long time now. It all started back in December 2017 when I was asked to deploy and test one of the services on Kubernetes. It was tough! Not because Kubernetes is tough but because I was a noob just out of college who thought writing java code is the coolest thing to do as engineer. That mindset changed in two years though.</p><p>I have worked on <a href="https://github.com/openebs/openebs/"><strong>OpenEBS</strong></a> project in past which is Kubernetes native storage engine. I learnt a lot while developing features for the project. It involved not only Kubernetes API usage but also extensive use of the cli <a href="https://github.com/kubernetes/kubectl"><strong>kubectl</strong></a>.</p><p>When I switched job I started working on a more challenging project which was on cloud migration(fun fact: as of today my employer is still hiring more engineers for that profile. Be sure to checkout my <a href="https://www.linkedin.com/in/prince-rachit-sinha-573828113/">LinkedIn</a> and connect if you want a referral). This made me understand the power and use case of Kubernetes not just with a Kubernetes Vendor’s perspective but also Kubernetes User’s perspective. I learnt a lot in this project and still learning. I spend a huge chunk of time in design discussion and debugging.</p><p>A number of my friends started taking <a href="https://www.cncf.io/certification/cka/">CKA</a> and they were pushing me to take it. It started with <a href="https://medium.com/u/91bf8d33db91">Ashutosh Kumar</a> aka Baba clearing the exam and then recently <a href="https://www.linkedin.com/in/srivastavaakash/">Akash Srivastava</a> aka Vladmir. Three weeks back I talked to Vladmir about preparing for exam. He convinced me that it will take some 6–7 days. To be on safer side I took 10 days and booked the slot. The results came out today and I cracked it with a score of 99%. So how did I do it?</p><h3>Preparation Time</h3><p>I purchased the <a href="https://training.linuxfoundation.org/training/kubernetes-fundamentals/">official CNCF course</a> few months back but was not going through it regularly. Occasionally I will open it up and go through lab exercises. The course is really great though. It has everything you need to know about running Kubernetes and managing it. The exercises are also very good. So I spent like <strong>a month</strong> or so in going through the course.</p><h4>Marathon Preparation</h4><p>I spent 9 days to prepare and here is how I spent the time:</p><p><strong>Day 1–2</strong>: Cluster Setup using kubeadm and revising components of kubernetes</p><p><strong>Day 3–4</strong>: Learning deployment objects like pod, deployment, daemonset etc.</p><p><strong>Day 4–5</strong>: Deploying applications using above objects and in combination, utilising the features of these object.</p><p><strong>Day 5–6</strong>: Services and other resources like secrets,volumes,resourcequota, limitranges etc.</p><p><strong>Day 7–8</strong>: Close loop with all the knowledge accumulated so far. Use various objects in conjunction like Daemonset with taint toleration and rolling update etc.</p><p><strong>Day 8–9</strong>: Revise everything again.</p><p><strong>Day 10</strong>: Take exam.</p><p>I referred to the official CNCF course to decide the order of objects and concepts I should go through.</p><h3>Preparation Resources</h3><ol><li>O<a href="https://training.linuxfoundation.org/training/kubernetes-fundamentals/">fficial CNCF course</a></li><li><a href="https://kubernetes.io/docs">Kubernetes docs and api references</a>: Must do the Tasks and Concepts section. You can skip some tasks like federation and some debugging sections (which I skipped too)</li><li>Stackoverflow for QnA</li><li>Slack #cka-exam-prep <a href="http://slack.k8s.io/">http://slack.k8s.io/</a> for more material</li><li>Random blogs on Kubernetes</li></ol><h3>Exam Tips</h3><h4>Must learn hacks of kubectl</h4><ol><li>kubectl explain</li><li>kubectl — dry-run and other flags</li><li>kubectl create/replace/update/delete/run etc</li></ol><h4>Use Kubernetes docs</h4><ol><li>You are free to open any subdomains of <a href="https://kubernetes.io/docs/">https://kubernetes.io/docs/</a> and github kubernetes docs repo.</li><li>Make use of the search bar in the docs site</li><li>Download the YAMLs and edit them</li></ol><h4>Learn to use wget/curl</h4><ol><li>The exam environment only allows you to copy 2 lines at a time</li><li>Instead of typing the YAMLs you can open examples in the docs site and copy the url. Then use wget/curl to download the YAML.</li></ol><h4>Learn VIM shortcuts</h4><p>I use vim to edit files quickly. Nano is another option but the shortcuts of vi are more rich. Copy/Paste/Delete/Multiple line selection and edit are the shortcuts that you should be aware of. It will save a lot of time.</p><h4>Enable auto completion</h4><p>Enable auto completion of all the clis that you would be using:</p><pre>source &lt;(kubectl completion bash)<br>source &lt;(etcdctl completion bash)<br>source &lt;(kubeadm completion bash)</pre><p>This would help you in saving time and getting an insight of available flags. If you don’t do this then you will endup opening man page or help page of the clis.</p><h4>Store your YAMLs</h4><p>I found it very useful to store the YAMLs that I generated to solve problems. I marked them with question num like <em>1-pod.yaml</em>, <em>6-deploy-svc-secret.yaml </em>.The benefit of doing this was that you can reuse the yamls by copying them to new file and you can keep track of the progress you made. It is very helpful when you try to verify.</p><h4>Use Notepad</h4><p>The exam env comes with a notepad where you can take notes. I used it to keep track of problems that I skipped initially. I also stored some commands of creating secrets and exposing a deployment etc. in the notepad.</p><h4>Do what you know first</h4><p>The most advised strategy in any exam is not to get stuck in one question. Just skip it. There are 24 questions that are needed to be solved. First do what you are comfortable with. Just make a note of skipped question and revisit it later.</p><h3>Conclusion</h3><p>If you have been working on Kubernetes for long time then preparation could be done in 10 days. It is good to learn hacks like wget/vim shortcuts to save time.</p><p>If you like this blog then show your appreciation by clapping and sharing it. Feel free to post your questions here. You can also connect to me on LinkedIn (please mention through blog in the request).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMOFCv-dCbOXZdnxfRx-Gg.png" /><figcaption>CKA certificate</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d57288f5148f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Testing Latency Sensitive Java Apps on Kubernetes [Part I]]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/load-testing-latency-sensitive-java-apps-on-kubernetes-part-i-6f56f93e801?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f56f93e801</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 05:50:49 GMT</pubDate>
            <atom:updated>2019-12-24T05:50:49.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*apnXgWAMVl1hSFr_PtUZqQ.png" /></figure><p>I am the guy who is supposed to help services running on data center to move to kubernetes. With a small team it is often difficult to migrate a critical service. However, along with challenges it brought learning. With no connection to load testing I was asked to help the service owners in their load test. Let me share the ordeals of load testing on cloud.</p><h4>Old is not gold, it is a piece of shit!</h4><p>A number of services which have been running on Java 7 were moved to Java 8 few years back. The transition was interesting and challenging for the teams and brought several features and practices enhancing the developed experience. But then, it became outdated. Services on Java8 were not interested in updating to new patches unless it was a security patch.</p><p>So we started with deploying our first demo service written in Java 8 on kubernetes. We dockerized it pretty much in a straight forward way by copying the fat jar.</p><p>It crashed. It had to. Nothing works at first attempt. Not in software at least. The reason was baffling to us. Because kubelet was complaining that it is OOM. Say what? A demo app running out of memory? It was printing hello world for tfs. We started digging into the root cause and we could see that the framework was requesting correct memory. It was trying to get the available memory and then using 60% of it in the JVM heap. The code was right there and it had been working smoothly for few years, what could possibly be wrong in a working code. We started looking into app logs and what we found was that the JVM size being allocated/used is some ~12G.</p><p>Soon we realized that it was the EC2 host memory that is being read in the container and not the container’s allotted limit. <em>This was due to a bug in Java8 which was fixed later.</em><strong><em> </em></strong>Sorry, I can’t find the bug link. You should try googling it.</p><p>We overrided the dynamic calculation with a static value and it worked. Later we upgraded to the latest Java8 and the issue was resolved.</p><h4>On-prem resources ≠ Cloud resources</h4><p>I tried translating the on prem huge box config to small pod config. For me the calculation was easy. If a box on prem has 45gigs of memory and 12 CPUs then on cloud I will have (4.5gigs , 1.2 CPU) x 10 pods.</p><p>Trust me, it was a stupid calculation because the CPUs on prem are different than on the cloud. You have to account for the cores and the vCPUs. Even then the calculation would be incorrect. You should subtract the resources used by supporting services like filebeat, monitord etc when you move to the cloud. These services are added as sidecar and have their own dedicated resources.</p><h4>Less threads is NOT always a good idea</h4><p>I managed to get a working configuration for the functional testing and it was a success. 3 pods were able to handle some 10k rpm. The next step was to check if autoscaling works. It did not. Not because we misconfigured our load test client, but because the pod was never hitting the CPU target of 50%.</p><p>We had some 100 threads running per pod. And they would block because of their DB and server dependencies. When this happens the CPU utilization is relatively low i.e. 45%. Thus, the HPA would never kicking. Instead we will see our pods getting killed due to liveness probe failure.</p><p>The liveness check would be often dropped by the server as the queue was full and processing was slow.</p><p>We incremented the thread count to 200 and voila! it worked. We ran few more experiments and concluded that 260 was most performing thread count.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f56f93e801" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating docker images the right way]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/creating-docker-images-the-right-way-a3d5ba57ce2a?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3d5ba57ce2a</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Sun, 09 Jun 2019 19:18:02 GMT</pubDate>
            <atom:updated>2019-06-09T19:18:02.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-eIk543nLf_1Yw6VWuUGHg.png" /></figure><p>There are literally hundreds of blog post out there which talk about creating small size docker images. And yes, there are many blogs as well as excellent documentation around best practices of creating a docker image.</p><p>This blog post is a summary of the most important yet the most basic practice that you can adapt to get some great results.</p><h4>Choosing the right base image</h4><p>This is perhaps the most talked about topics in the container world. The answer is simple: The smallest which has all the tools you want and stripped of the tools that you don’t want.</p><p>It is natural to select the smallest size base image like <a href="https://docs.docker.com/samples/library/alpine/">alpine</a> as your base image but this comes with a cost. A bad choice of the base image would mean a lack of support, bugs, maintenance etc.</p><p>You basically have a choice:</p><ol><li>Use a base image which has all the tools you want</li><li>Create your own base image to be used across projects</li></ol><p>A number of times you would want to use approach 2. For an organization which is large and running thousands of containers in production, even 100MB of extra space per container is expensive and slow down container deployments.</p><h4>Installing the runtime dependencies</h4><p>There is a difference between project build dependencies and project runtime dependencies. The build dependencies are heavy whereas the runtime dependencies are small and cheap.</p><h4>Create different images for project build and project runtime</h4><p>Your project, if building inside a container, would require a plethora of tools and dependencies which can range from make, git, rub gems, tar, jdk, g++ to docker runtime . But, do you actually require these tools for the container which runs in production? No! It is wasteful. So use a different container when building your project.</p><h4>Install generic tools at the lower layer of your image</h4><p>It is obvious that you want to have the generic tools like git, jdk etc at a lower level of the project build image. These dependencies are not updated regularly, thus your image push and pull (or even a build, if using cache) would be faster. Another important thing to keep in mind is to have the version of your dependencies locked while installing.</p><p>i.e instead of doing this:</p><pre>apt-get install -y apt-transport-https</pre><p>do this:</p><pre>apt-get install -y apt-transport-https=1.4.9</pre><p>Well, this comes with a headache of keeping yourself updated with the security patches of these dependencies. If there is a crucial bug fix then you have to manually update the version in the Dockerfile.</p><h4>Strip it when you don’t need it</h4><p>Many times we miss the fact that when you install a runtime dependency you might be installing stuff that you don’t actually require. For example, I was creating a docker base image to be used by the java services. Upon doing a little research, I realized that some of the standard java images available out there are doing something really cool. They are stripping unwanted dependencies. To run your java project you probably only need <strong>jre and not the jdk</strong>. You can even get rid of unwanted jars which are shipped with jre.</p><p>e.g. after installing Java you can remove unwanted stuff with the following command:</p><pre>RUN cd ${JAVA_HOME} &amp;&amp; \<br>    rm -rf &quot;bin/&quot; &quot;lib/&quot; &quot;src.zip&quot; &quot;javafx-src.zip&quot; &quot;man/&quot; \<br>    &quot;jre/plugin&quot; \<br>    &quot;jre/bin/javaws&quot; \<br>    &quot;jre/bin/jjs&quot; \<br>    &quot;jre/bin/orbd&quot; \<br>    &quot;jre/bin/pack200&quot; \<br>    &quot;jre/bin/policytool&quot; \<br>    &quot;jre/bin/rmid&quot; \<br>    &quot;jre/bin/rmiregistry&quot; \<br>    &quot;jre/bin/servertool&quot; \<br>    &quot;jre/bin/tnameserv&quot; \<br>    &quot;jre/bin/unpack200&quot; \<br>    &quot;jre/lib/&quot;*javafx* \<br>    &quot;jre/lib/plugin.jar&quot; \<br>    &quot;jre/lib/ext/jfxrt.jar&quot; \<br>    &quot;jre/lib/javaws.jar&quot; \<br>    &quot;jre/lib/desktop&quot; \<br>    &quot;jre/lib/&quot;deploy* \<br>    &quot;jre/lib/&quot;*javafx* \<br>    &quot;jre/lib/&quot;*jfx* \<br>    &quot;jre/lib/amd64/libdecora_sse.so&quot; \<br>    &quot;jre/lib/amd64/&quot;libprism_*.so \<br>    &quot;jre/lib/amd64/libfxplugins.so&quot; \<br>    &quot;jre/lib/amd64/libglass.so&quot; \<br>    &quot;jre/lib/amd64/libgstreamer-lite.so&quot; \<br>    &quot;jre/lib/amd64/&quot;libjavafx*.so \<br>    &quot;jre/lib/amd64/&quot;libjfx*.so \<br>    &quot;jre/lib/ext/nashorn.jar&quot; \<br>    &quot;jre/lib/jfr.jar&quot; \<br>    &quot;jre/lib/jfr&quot; \<br>    &quot;jre/lib/oblique-fonts&quot; \<br>    &quot;jre/THIRDPARTYLICENSEREADME-JAVAFX.txt&quot; \<br>    &quot;jre/THIRDPARTYLICENSEREADME.txt&quot; \<br>    &quot;jre/README&quot; \<br>    &quot;jre/Welcome.html&quot; \<br>    &quot;jre/lib/security/README.txt&quot;</pre><p>Obviously, you would do this in the same layer where you are installing java.</p><h4>Can you make it smaller?</h4><p>Yes, there is this trick, well not exactly a trick but a best practice that you can follow. <strong>Use </strong><a href="https://docs.docker.com/develop/develop-images/multistage-build/"><strong>multi-stage builds</strong></a><strong>.</strong></p><p>With what I have done above I can have another stage in my Dockerfile which can simply consume dependencies/artifacts created in the previous stage.</p><pre>FROM ubuntu:latest as BASE</pre><pre>..<br># install java<br>..<br># remove jdk<br>..<br># do some more stuff<br>..</pre><pre># Now create another image which uses artefacts from previous stage</pre><pre>FROM debian:stretch-slim</pre><pre>ENV JAVA_HOME /usr/java/default</pre><pre>RUN mkdir -p $JAVA_HOME &amp;&amp; cd $JAVA_HOME</pre><pre>COPY --from=BASE $JAVA_HOME/ $JAVA_HOME/</pre><p>You can imagine that with this approach our image is going to be extremely lightweight.</p><h4>But what if I need tools to debug?</h4><p>This is a genuine requirement. There are two ways to solve this problem.</p><ol><li>Use a different base image which has all the tools</li><li>Install tools ad-hoc</li></ol><p>Both approaches have their own pros and cons. As we would really want our image to be as small as possible, it is safe to ignore approach 1 for now.</p><p>But how do we install tools in the container? Should we just run our classic apt-get install commands?</p><p>There is a better way to solve this problem. You would often know a set of tools that you require to debug your container. E.g. netstat, ss, telnet etc.</p><p>The trick is to create a tools installation script and ship it with your base image.</p><pre>#!/bin/bash</pre><pre>apt-get install -y net-tools \<br>apt-transport-https \<br>curl</pre><p>So, whenever you want to debug your container you can simply exec inside it and run</p><pre>$ bash ./install-debug-essentials.sh</pre><p>and you have all the required tools that you need.</p><h4>The End</h4><ul><li>Claps appreciated</li><li>Shares appreciated</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3d5ba57ce2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validating Kubernetes Deployment YAMLs]]></title>
            <link>https://medium.com/schkn/validating-kubernetes-deployment-yamls-d46a16a7e664?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d46a16a7e664</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Fri, 07 Jun 2019 12:00:25 GMT</pubDate>
            <atom:updated>2019-06-15T15:25:58.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*wttZ04DixIDEvU0pH1RYTQ.png" /></figure><h3>It doesn’t need an Introduction</h3><p>One of the challenges working with K8s is pre-deployment validation of your descriptor YAMLs. A slight misalignment of the — env values and the server returns an ugly error which makes you wonder if your life is worth living.</p><p>It is more annoying when you see this error while deploying through an automated tool/system.</p><p>Yes, CI/CD! Not good, right?</p><p>I was bestowed upon with this opportunity recently. Like every other engineer I started with an internet search How to validate Kubernetes YAMLs and the results were not really welcoming. I thought there would be a multitude of tools and systems offering this but to my dismay, there was only a handful of them, some of them created by the same person <a href="https://github.com/garethr/">Gareth</a>.</p><h3>Well, what to test?</h3><p>With more research and introspection I realized that there were primarily 2 things that need to be validated:<br>1. <strong>The schema</strong>: So the server does not complain about invalid kind or invalid array while it was expecting a map <br>2. <strong>The state</strong>: So that when you deploy your workload it does not land in a dangling state. e.g. The service name is incorrect and the dependent services are calling non-existent URLs.</p><h3>Prince, cut the crap and tell me where should I test?</h3><p>Now there are several stages of the application life cycle where you want to have these two checks. Validating YAMLs while developing application logic might not make sense but having a fail-fast mechanism would result in less error prone deployments.</p><p>Possible stages where you can think of integrating these checks are:<br>1. <strong>Development and local test</strong>: Developers laptop<br>2. <strong>Continuous Integration</strong>: Full-fledged CI system where you have a dedicated Validate or Test stage<br>4. <strong>Pre Deployment</strong>: The deployment tool validates the YAMLs before deploying<br>5. <strong>Post Deployment</strong>: Some tool which pulls the created object and performs validation on them</p><p>I would assume that your project uses containers extensively and your tests are also run inside a container (If that is not too much to ask for).</p><p>There are two ways you can validate your schema, you either use kubectland use --validate with --dry-run or you utilize some tool which does not require a K8s server as a dependency.</p><h3>Validating the schema</h3><p>I will talk about the latter here.</p><p><a href="https://kubeval.instrumenta.dev/"><strong>kubeval</strong></a> is a tool which uses OpenAPI spec to validate your config. It has a <a href="https://github.com/instrumenta/kubernetes-json-schema">modified</a> (or cleaned up) version of Kubernetes <a href="https://github.com/kubernetes/kubernetes/blob/master/api/openapi-spec/README.md">OpenAPI spec</a> which is suitable to build a tool around.</p><p>Before we proceed shoutout to <a href="https://github.com/instrumenta/">Instrumenta</a> for the awesome work!</p><p>kubevalalso allows you to use your own schema for validation (I have never tried it though and there is a <a href="https://github.com/instrumenta/kubeval/issues/94">bug</a> which restricts it to an extent).</p><p>Let us see a quick example of how kubevalworks. I have a deployment file which looks like:</p><pre>apiVersion: apps/v1<br>kind: Deploy<br>metadata:<br>  creationTimestamp: null<br>  labels:<br>    run: nginx<br>  name: nginx<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      run: nginx<br>  template:<br>    metadata:<br>      labels:<br>        run: nginx<br>    spec:<br>      containers:<br>      - image: nginx<br>        name: nginx</pre><p>For some unfortunate reason, I have declared the kind as Deploy which should have been Deployment. Now I can run the following command to validate my YAML:</p><pre>bash-5.0$ kubeval deploy.yaml<br>1 error occurred:<br> * Problem loading schema from the network at <a href="https://kubernetesjsonschema.dev/master-standalone/deploy-apps-v1.json">https://kubernetesjsonschema.dev/master-standalone/deploy-apps-v1.json</a>: Could not read schema from HTTP, response status is 404 Not Found</pre><p>You can see that it errors out saying that the schema does not have any kind Deploy. After fixing the kind:</p><pre>bash-5.0$ kubeval deploy.yaml<br>The document deploy.yaml contains a valid Deployment</pre><p>I modified the replicas to accept an array whereas it should accept an integer:</p><pre>..<br>spec:<br>  replicas: [1]<br>  selector:<br>..</pre><p>kubeval reports the error:</p><pre>bash-5.0$ kubeval deploy.yaml<br>The document deploy.yaml contains an invalid Deployment<br>---&gt; spec.replicas: Invalid type. Expected: integer, given: array</pre><p>Useful, isn’t it?</p><p>However, if you introduce an unknown field in the manifest the above command would fail (notice the field non-metadata):</p><pre>bash-5.0$ cat deploy.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>non-metadata:<br>  creationTimestamp: null<br>  labels:<br>    run: nginx<br>  name: nginx<br>..<br>..</pre><pre>bash-5.0$ kubeval deploy.yaml<br>The document deploy.yaml contains a valid Deployment</pre><p>To make sure it catches these errors use the flag --strict</p><pre>bash-5.0$ cat deploy.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>non-metadata:<br>  creationTimestamp: null<br>  labels:<br>    run: nginx<br>  name: nginx<br>..<br>..</pre><pre>bash-5.0$ kubeval deploy.yaml --strict<br>The document deploy.yaml contains an invalid Deployment<br>---&gt; non-metadata: Additional property non-metadata is not allowed</pre><h3>Hey, what about validating the state?</h3><p>There are two tools both created by a gentleman if you haven’t guessed yet: <a href="https://github.com/garethr">Gareth</a></p><ol><li><a href="https://github.com/garethr/kubetest">kubetest</a> : It’s a nice tool but I could not successfully use it due to <a href="https://github.com/garethr/kubetest/issues/9">this bug</a>.</li><li><a href="https://github.com/instrumenta/conftest/">conftest</a> : This tool is gold. Why? because it uses Rego for queries. Rego is the same query language that <a href="https://www.openpolicyagent.org/docs/latest/get-started">Open Policy Agent</a> uses. As there are several enterprises already using OPA there is better support and documentation.</li></ol><p>Let me know if you are interested in examples of kubetest, I will create another post for it.</p><p>Let us see how you can use conftest with an example. But wait, some intro first. conftest accepts a set of policies which are a collection of rules. A rule can either evaluate to true or false.</p><p>By default, the policies are assumed to be in the ./policy directory. Obviously, you can override the location using --policy flag. Why would you even think that the support to override the location would be missing?! Dumb you.</p><p>I won’t go into many details but see here is a sample:</p><pre>.<br>├── deploy.yaml<br>└── policy<br>    └── base.rego</pre><p>The content of base.rego :</p><pre>package main</pre><pre>deny[msg] {<br>  not input.kind = &quot;Deployment&quot;<br>  msg = &quot;not a deployment&quot;<br>}</pre><p>I have defined onedeny rule which checks the input.kind value. If</p><pre>not input.kind = “Deployment&quot;</pre><p>evaluates to true then the msg would be returned. Basically what the rule says is that if the input kind is not deployment then succeed. Here, success will cause the deny rule to pass, which means error. You might want to read the above lines a few times to make sense. BTW this is the input we are using:</p><pre>apiVersion: apps/v1<br>kind: Deploy<br>metadata:<br>..<br>..</pre><p>Here is the result:</p><pre>bash-5.0$ conftest test deploy.yaml<br>deploy.yaml<br>   not a deployment<br>bash-5.0$ echo $?<br>1</pre><p>Now let us correct the deploy.yaml kind:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>..<br>..</pre><p>and here is the magic:</p><pre>bash-5.0$ conftest test deploy.yaml<br>deploy.yaml<br>bash-5.0$ echo $?<br>0</pre><h3>How do I integrate it into the pipeline?</h3><p>Well, containers! Run your test in containers and have these tools available in them. You would be good to go with a few lines of code in your Jenkinsfile or some test script.</p><h3>Really important stuff!</h3><ol><li>Clap for the story</li><li>Follow me on medium</li><li>Send me a LinkedIn invite with message “from medium blog”</li><li>And yeah you can follow me on github too: <a href="https://github.com/princerachit">https://github.com/princerachit</a></li></ol><p><a href="http://devconnected.com/about">About - devconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d46a16a7e664" width="1" height="1" alt=""><hr><p><a href="https://medium.com/schkn/validating-kubernetes-deployment-yamls-d46a16a7e664">Validating Kubernetes Deployment YAMLs</a> was originally published in <a href="https://medium.com/schkn">devconnected — DevOps, Sysadmins &amp; Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monolith to Microservices: Why Kubernetes on Cloud?[Business Need]]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/monolith-to-microservices-why-kubernetes-on-cloud-business-need-52bd7fbbadba?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/52bd7fbbadba</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 11:08:17 GMT</pubDate>
            <atom:updated>2019-03-20T11:08:17.737Z</atom:updated>
            <content:encoded><![CDATA[<h4>Saving money</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5O4cIVSqi37Avv3Q42yOcw.png" /></figure><h3>Overview</h3><p>The software industry or in fact any industry is governed by only one rule: <em>profit</em>. To make a business profitable you can do two things:</p><ol><li>Make more money by selling more</li><li>Spend Less on every sell</li></ol><p>While the first gives you growth, the second gives you margin.</p><h3>How and why Kubernetes</h3><p>There are hundreds of reasons why one should move to cloud and use kubernetes. Most of the blogs you find online would talk about only the technical problems k8s solves. However, I believe Kubernetes is gaining momentum not because the problems it solves at the technical front but the scale of cost cutting it provides at the business front.</p><h3>Explaining need by example</h3><p>Let us take a hypothetical use case which a VP or folks from senior management can understand.</p><p>TradeStok Ltd. is an investment consultancy firm which provides a platform for individuals to make an investment in various schemes like Mutual Funds, Fixed Deposit etc. It also provides TradeStok coins which are similar to a cryptocurrency(not really) that users can buy and sell in real time.</p><p>TradeStok maintains its own datacenters and manages its own servers. The trend of the user accessing the platform and making investment is well analysed. Every 1st week of the month the traffic to the server increases by 10x. During festivals like Christmas and Diwali when the country’s workforce receives bonuses the load on the server increases to 25x. During holiday seasons the load on TradeStok coins server increases to 200x.</p><p>Since TradeStok does not want to lose a customer they have decided to scale their servers to handle the peak load. While they made a good profit during holidays, the overall business started plummeting after January. They came up with a plan of buying/leasing servers before holidays and reselling them afterwards. This strategy has itself produced 2 big challenges:</p><ol><li>The cost of servers devaluates to 70% after use</li><li>Finding buyers is very difficult</li></ol><p>Some other challenges they face are:</p><ol><li>Expenses in the Audit Process</li><li>Security check</li><li>Cost of maintaining a support team</li><li>Transportation</li><li>Complying with Regulations</li></ol><p>and many others.</p><p>They are burning more % of the money on maintenance of their servers than they used to do when their business was 10 times smaller.</p><p>Although the revenue is increasing the profit % is decreasing every day. As a result, the management is forced to look at cost-cutting options.</p><p>Bam! Here comes the need for kubernetes on cloud. All(Okay I go carried away, let us say most) of the problems listed in preceding sections can be solved by using kubernetes on cloud. How? Let us investigate two of them.</p><h4>Challenge 1: Scaling servers</h4><p>With K8s you can spin up multiple server instances in seconds. This can be done dynamically by setting the auto scaling configuration against the average load on a server. However, this still does not solve the problem of maintaining the underlying infrastructure. If TradeStok starts using cloud infrastructure let us say AWS then the burden of maintaining the infrastructure with huge investments is mitigated. Platforms such as AWS or Google cloud provide node auto-scaling feature i.e. more machines are added to existing infrastructure as the load increases.</p><p>Therefore, the challenges pertaining to scaling up servers, scaling them down, maintaining them during the idle period, finding buyers is all solved.</p><p>How would this look in numbers? Let us see. Assume that the company spends $500k per month for an infra which can support the peak load. During non-peak seasons the infra required costs only $50k per month. Assuming that the peak season time duration is anywhere 10–30 days, let’s say one month. The actual infra cost should be $50k x 11 + $500k x 1 = ~$1m but the company is spending ~$6m in one year.</p><p>Even if the cost of cloud infra is 2 times the effective infra cost would be:</p><p>$50k x 2 x 11 + $500k x 2 x 1 =~$2m. So, the company would save $4m on infra maintenance.(Shocked? You better be!)</p><h4>Challenge 2: Security and Audit</h4><p>Since the company has deferred the maintenance of hardware infrastructure to the vendor, the headache of conforming to infrastructure security and regulatory compliance would be taken care of by the vendor. Not only that but the regulations which force companies to upgrade the hardware(to avoid any hardware-level security issues) are no more problems of TradeStok.</p><p>Now the company has to spend its resources only on the software and business audits. A company of this size would usually spend several thousand dollars on an audit. So using k8s on cloud would save the company a big piece of gold.</p><h3>Summary</h3><p>Any big company which needs to scale its infra on demand is better off using k8s on cloud.</p><h3>What’s is next</h3><p>In the next story, I will talk about the technical need of k8s on cloud. Post that I will start writing about the challenges of migration. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52bd7fbbadba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monolith to Microservices: About Me]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/monolith-to-microservices-about-me-f807a4c4f9df?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f807a4c4f9df</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 12:01:10 GMT</pubDate>
            <atom:updated>2019-03-18T12:01:10.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5O4cIVSqi37Avv3Q42yOcw.png" /></figure><p>This is the first of the series of stories I would be writing describing the technical challenges and experience during migration of a system from on-prem data centre to cloud. But first, let us talk about me(the narcissist).</p><p>I began my career some 19 months back in a startup which builds storage monitoring and management platform for kubernetes. I was involved in solving the difficult challenge of storage management and visualization for kubernetes clusters. Although I worked on building tools for kubernetes I was not aware of the impact these tools make or in fact how cloud(in particular kubernetes) solves the real problem. The use cases I saw were always a surprise to me. My team would develop a feature with certain assumptions and great design only to learn later that the use case of a potential customer is diametrically opposite to our design. Whereas the solution would solve the problem, the way it solved it, required a lot of privileges and flexibility on the customer side, which is safe to say, never works.</p><p>I am not talking about customers building their infra on the cloud from the beginning. I am talking about companies who have been in the industry for a long time and recently started migrating their infra to cloud. There are stringent challenges with these companies. They cannot just adopt the cloud infra in one go. They have to comply with all the existing laws and regulations while migrating to the cloud. Use cases are sometimes very specific to a user, what User A needs, User B doesn’t want it at all.</p><p>Then I decided to make a move to understand how these big system work and what they need exactly. So from building for kubernetes I switched to using kubernetes to solve the problem as I landed a job in my current company.<br>I work in a team which is responsible to migrate existing monolith apps to kubernetes in a microservice architecture. To be honest, things are already set to motion when I joined, at least on the platform side. However, the actual migration was not started for core applications, so I got a chance to learn the early challenges of cloud migration.</p><p>In the next story I will start with the need for cloud infrastructure and problems it solves. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f807a4c4f9df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[cStor volume snapshot and clone: A technical overview]]></title>
            <link>https://sinhasoftwaresolutions.medium.com/cstor-volume-snapshot-and-clone-a-technical-overview-3edd84ae0678?source=rss-c9bf13034fc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3edd84ae0678</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[openebs]]></category>
            <category><![CDATA[snapshot]]></category>
            <category><![CDATA[cstor]]></category>
            <dc:creator><![CDATA[Sinha Software Solutions]]></dc:creator>
            <pubDate>Sat, 05 Jan 2019 18:12:39 GMT</pubDate>
            <atom:updated>2019-01-05T18:12:39.284Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prerequisite</h3><p>Read this blog if you want to know <a href="https://medium.com/@princerachit/cstor-volume-a-techincal-overview-1759c6ac0a0b">technicalities of a cstor volume</a>. If you want to try out snapshot and clones along with the blog then follow <a href="https://docs.openebs.io/docs/next/installation.html">installation setups</a> and provision <a href="https://docs.openebs.io/docs/next/deploycstor.html">cstor volume.</a> Also checkout video demo of snapshot, link at the bottom.</p><h3>The Key Terms: Jargons</h3><p>Refer to the blog link in prerequisite to learn about other jargons.</p><ol><li><a href="https://searchdatabackup.techtarget.com/definition/storage-snapshot"><em>Snapshot</em></a>: A storage snapshot is a set of reference markers for data at a particular point in time. A snapshot acts like a detailed table of contents, providing the user with accessible copies of data that they can roll back to.</li><li><em>VolumeSnapshot</em>: A snapshot request object in kubernetes. When this object is created then the snapshot controller would act on the information and try to create a <em>VolumeSnapshotData</em>.</li><li><em>VolumeSnapshotData: </em>It is a kubernetes object that represents an actual volume snapshot. It contains information about the snapshot e.g. the snapshot name mapped by the actual storage vendor, creation time etc.</li></ol><p>You can relate these objects with the following relation:</p><p>PersistentVolumeClaim:PersistentVolume::VolumeSnapshot:VolumeSnapshotData</p><h3>The Whats: Introduction</h3><p>The upcoming release 0.8 would be bundled with a stable snapshot and clone support for cstor volumes.</p><p>Assuming that a cstor volume is already created it is possible to take snapshot of it by creating a VolumeSnapshot object. Snapshotting would be successful only when the cstor volume is in healthy state. i.e. if <strong>.status.phase </strong>∉ <strong>{Healthy}</strong> then snapshotting of the volume would fail.</p><p>You can always check if it is possible to take snapshot by inspecting the cstor volume object. Run the below command:</p><blockquote>kubectl describe cstorvolume &lt;cstor volume name&gt; -n openebs</blockquote><pre>prince@prince:~/go/src/github.com/princerachit/dump/demo-09-11-18$ kubectl describe cstorvolume -n openebs pvc-9a3d6a39-f486-11e8-8689-42010a80017d<br>...<br>...<br>...<br>Status:<br>  Phase:  Healthy<br>  Replica Statuses:<br>    Checkpointed IO Seq:  0<br>...<br>...<br>...</pre><p>Once a snapshot has been created we can clone the snapshot into actual volume which could be mounted to a workload.</p><h3>The User Stuff: Snapshot Creation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*DTVMf1-JwGyB8MnT" /><figcaption>Relation between CRs as viewed in MayaOnline topology view.</figcaption></figure><p>Let us try to take snapshot of the our volume. It must be noted that openebs DOES NOT support application level snapshots for now.</p><p>The pvc which I used to create cstor volume is <strong>openebs-pvc.</strong> This would be referenced in the volumesnapshot manifest.</p><pre>apiVersion: volumesnapshot.external-storage.k8s.io/v1<br>kind: VolumeSnapshot<br>metadata:<br>  name: snapshot-demo<br>  namespace: default<br>spec:<br>  persistentVolumeClaimName: openebs-pvc</pre><p>Things are quite clear from the manifest itself. Let us see what happens when we apply this yaml.</p><pre>prince@prince:~/go/src/github.com/princerachit/dump/demo-09-11-18$ kubectl apply -f snapshot.yaml <br>volumesnapshot.volumesnapshot.external-storage.k8s.io/snapshot-demo created</pre><p>If the snapshot was successful we would expect an object of <strong>VolumeSnapshotData</strong> to be created which would have a reference to this object.</p><pre>prince@prince:~/go/src/github.com/princerachit/dump/gke_util$ kubectl get volumesnapshotdata<br>NAME                                                       CREATED AT<br>k8s-volume-snapshot-33a7b5c5-f487-11e8-a0ac-0a580a3c0910   1m</pre><p>So our snapshot seems to be created. Let us see what exact information these two objects have in them.</p><pre>prince@prince:~/go/src/github.com/princerachit/dump/gke_util$ kubectl describe volumesnapshot snapshot-demo<br>Name:         snapshot-demo<br>Namespace:    default<br>Labels:       SnapshotMetadata-PVName=pvc-9a3d6a39-f486-11e8-8689-42010a80017d<br>              SnapshotMetadata-Timestamp=1543572214871829268<br>Annotations:  kubectl.kubernetes.io/last-applied-configuration:<br>                {&quot;apiVersion&quot;:&quot;volumesnapshot.external-storage.k8s.io/v1&quot;,&quot;kind&quot;:&quot;VolumeSnapshot&quot;,&quot;metadata&quot;:{&quot;annotations&quot;:{},&quot;name&quot;:&quot;snapshot-demo&quot;,&quot;nam...<br>API Version:  volumesnapshot.external-storage.k8s.io/v1<br>Kind:         VolumeSnapshot<br>Metadata:<br>  Cluster Name:        <br>  Creation Timestamp:  2018-11-30T10:03:34Z<br>  Generation:          1<br>  Resource Version:    14151955<br>  Self Link:           /apis/volumesnapshot.external-storage.k8s.io/v1/namespaces/default/volumesnapshots/snapshot-demo<br>  UID:                 32fb7599-f487-11e8-8689-42010a80017d<br>Spec:<br>  Persistent Volume Claim Name:  openebs-pvc<br>  Snapshot Data Name:            k8s-volume-snapshot-33a7b5c5-f487-11e8-a0ac-0a580a3c0910<br>Status:<br>  Conditions:<br>    Last Transition Time:  2018-11-30T10:03:35Z<br>    Message:               Snapshot created successfully<br>    Reason:                <br>    Status:                True<br>    Type:                  Ready<br>  Creation Timestamp:      &lt;nil&gt;<br>Events:                    &lt;none&gt;</pre><p>The .status.conditions.status phase conveys the information that the snapshot was created. More information about actual snapshot is visible by:</p><pre>prince@prince:~/go/src/github.com/princerachit/dump/gke_util$ kubectl describe volumesnapshotdata k8s-volume-snapshot-33a7b5c5-f487-11e8-a0ac-0a580a3c0910 <br>Name:         k8s-volume-snapshot-33a7b5c5-f487-11e8-a0ac-0a580a3c0910<br>Namespace:    <br>Labels:       &lt;none&gt;<br>Annotations:  &lt;none&gt;<br>API Version:  volumesnapshot.external-storage.k8s.io/v1<br>Kind:         VolumeSnapshotData<br>Metadata:<br>  Cluster Name:        <br>  Creation Timestamp:  2018-11-30T10:03:35Z<br>  Generation:          1<br>  Resource Version:    14151954<br>  Self Link:           /apis/volumesnapshot.external-storage.k8s.io/v1/volumesnapshotdatas/k8s-volume-snapshot-33a7b5c5-f487-11e8-a0ac-0a580a3c0910<br>  UID:                 33a81571-f487-11e8-8689-42010a80017d<br>Spec:<br>  Openebs Volume:<br>    Snapshot Id:  pvc-9a3d6a39-f486-11e8-8689-42010a80017d_snapshot-demo_1543572214878429520<br>  Persistent Volume Ref:<br>    Kind:  PersistentVolume<br>    Name:  pvc-9a3d6a39-f486-11e8-8689-42010a80017d<br>  Volume Snapshot Ref:<br>    Kind:  VolumeSnapshot<br>    Name:  default/snapshot-demo-32fb7599-f487-11e8-8689-42010a80017d<br>Status:<br>  Conditions:<br>    Last Transition Time:  2018-11-30T10:03:35Z<br>    Message:               Snapshot created successfully<br>    Reason:                <br>    Status:                True<br>    Type:                  Ready<br>  Creation Timestamp:      &lt;nil&gt;<br>Events:                    &lt;none&gt;</pre><p>You can see that there are some important info present here like the Persistent volume name, the ID of the snapshot internally being used by openebs, reference to volumesnapshot and the status of the snapshot.</p><p>Wasn’t that quick? Yes! that is the advantage of openebs. cStor snapshots are fast because they use Copy-On-Write(<a href="https://www.grendelman.net/wp/fast-frequent-incremental-zfs-backups-with-zrep/">Read more here</a>). Inshort when we take snapshots we are not actually copying the volume anywhere, instead cStor internally leverages the zfs to save/record indexes. Thus, both actual volume and snapshot would refer to the same block of data unless one of them updates it.</p><h3>The Interesting Stuff: Snapshot Technicality</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2axwsKn5CW4z0bV8zfq4AQ.png" /></figure><p>Refer to diagram above the explanation is following:</p><ol><li>User registers a request to create volumesnapshot to kube apiserver, this request is then saved to the etcd db.</li><li>The snapshot controller watches for volumesnapshot object, as soon as the snapshot controller realizes that one of the volumesnapshot object does not have corresponding volumesnapshotdata object, it tries to reconcile.</li><li>It sends a create snapshot request to m-apiserver with CASSnapshot payload. This payload contains snapshot name, pv name, namespace of the pvc, and the cas type which is cStor here.</li><li>The m-apiserver receives this post request at the /latest/snapshots/ endpoint.</li><li>It then triggers the cas engine which in turn runs the required runtasks to create a cstor volume snapshot.</li><li>The run task sends a create request to the target deployment’s cstorvolume mgmt container.</li><li>This request is forwarded to all the cstor-pool containers which in turn take snapshot of the volumes.</li></ol><p>The pods topology explain things in a better way. (A screenshot from Mayaonline.io topology view)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*nWCsbKmxhH5zevXb" /></figure><h3>The User Stuff: Clone Creation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PLg6DjREctVYSgBTzhqiw.png" /></figure><p>To create a clone out of a snapshot is very simple. All you need to do is create a pvc manifest that refers to the volumesnapshot object.</p><p>e.g.</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: demo-snap-vol-claim<br>  namespace: default<br>  annotations:<br>    snapshot.alpha.kubernetes.io/snapshot: snapshot-demo<br>spec:<br>  storageClassName: openebs-snapshot-promoter<br>  accessModes: [ &quot;ReadWriteOnce&quot; ]<br>  resources:<br>    requests:<br>      storage: 5G</pre><p>You can see that the annotation <strong>snapshot.alpha.kubernetes.io/snapshot </strong>refers to the volumesnapshot object snapshot-demo. This tells the snapshot provisioner which snapshot has to be used to clone the volume.</p><p>By default all the clone pvcs would use <strong>openebs-snapshot-promoter</strong> storage class.</p><p>Let us see what happens when we apply this yaml.</p><pre>prince@prince:~/go/src/github.com/princerachit/dump/demo-09-11-18$ kubectl apply -f snapshot_claim.yaml <br>persistentvolumeclaim/demo-snap-vol-claim created</pre><p>Let us inspect the pv for this pvc.</p><pre>Name:            pvc-4041fd14-f487-11e8-8689-42010a80017d<br>Labels:          openebs.io/cas-type=cstor<br>                 openebs.io/storageclass=openebs-cstor-default-0.7.0<br>Annotations:     pv.kubernetes.io/provisioned-by: volumesnapshot.external-storage.k8s.io/snapshot-promoter<br>                 snapshotProvisionerIdentity: volumesnapshot.external-storage.k8s.io/snapshot-promoter<br>Finalizers:      [kubernetes.io/pv-protection]<br>StorageClass:    openebs-snapshot-promoter<br>Status:          Bound<br>Claim:           default/demo-snap-vol-claim<br>Reclaim Policy:  Delete<br>Access Modes:    RWO<br>Capacity:        5G<br>Node Affinity:   &lt;none&gt;<br>Message:         <br>Source:<br>    Type:               ISCSI (an ISCSI Disk resource that is attached to a kubelet&#39;s host machine and then exposed to the pod)<br>    TargetPortal:       10.63.240.55:3260<br>    IQN:                iqn.2016-09.com.openebs.cstor:pvc-4041fd14-f487-11e8-8689-42010a80017d<br>    Lun:                0<br>    ISCSIInterface      default<br>    FSType:             ext4<br>    ReadOnly:           false<br>    Portals:            []<br>    DiscoveryCHAPAuth:  false<br>    SessionCHAPAuth:    false<br>    SecretRef:          &lt;nil&gt;<br>    InitiatorName:      &lt;none&gt;<br>Events:                 &lt;none&gt;</pre><p>You can see that in the annotation <strong>pv.kubernetes.io/provisioned-by: volumesnapshot.external-storage.k8s.io/snapshot-promoter</strong> rather than regular <strong>openebs.io/provisioner-iscsi. </strong>Thus, this is a cloned volume.</p><p>From the topology view we can see that both the actual volume as well as the cloned volume is on the same set of pools.</p><h3>The Interesting Stuff: Clone Technicality</h3><p>The volume clone is similar to dynamic volume provisioning. The only difference is the fact that the clone volume is provisioned through snapshot provisioner instead of volume provisioner. The flow of control is same. The actual creation of the volume at openebs layer differs as the snapshots are used as a source of volume instead of empty volume creation.</p><h3>Usecase of snapshot/clone</h3><p>CI/CD is part of the eco-system that enables applications to be tested through various pipelines (CI) and deployed into production automatically (CD) at the end of successful CI. When one of the stages of pipeline fails, developers would like to reproduce the state of the stateful application for further debugging. DevOps admins need a solution where preserving the state of the application at each stage of the pipeline is very easy and seamlessly integrated into the CI/CD platforms such as Jenkins using the API.</p><p>A devops admin can use the snapshot feature of openebs to preserve the state of a stage. Later this can be promoted to a clone volume and inspected. (<a href="https://docs.openebs.io/docs/next/cicd.html">Read more here</a>)</p><h3>Future Enhancements</h3><p>As kubernetes is moving towards CSI compliant storage spec openebs v1.0+ is expected to adapt CSI compliant snapshotting.</p><h3>Link to important resources</h3><ol><li><a href="https://github.com/openebs/openebs/pull/1316/files">Snapshot proposal</a></li><li><a href="https://docs.openebs.io/docs/next/snapshots.html">Snapshot documentation</a></li><li><a href="https://www.youtube.com/watch?v=i8E9CtNzmak">Snapshot video demo weekly contributors meet</a></li><li><a href="https://mayaonline.io/">MayaOnline for visualization and monitoring of resources</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3edd84ae0678" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>