<?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 Pratyush Singh on Medium]]></title>
        <description><![CDATA[Stories by Pratyush Singh on Medium]]></description>
        <link>https://medium.com/@singhpratyush?source=rss-4747a35cc359------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sszuZAu9iFpIfmNi1A8MHA.jpeg</url>
            <title>Stories by Pratyush Singh on Medium</title>
            <link>https://medium.com/@singhpratyush?source=rss-4747a35cc359------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:31:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@singhpratyush/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[Docker containers for pipenv]]></title>
            <link>https://medium.com/analytics-vidhya/docker-containers-for-pipenv-3be128f1444?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/3be128f1444</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Mon, 09 Mar 2020 13:07:29 GMT</pubDate>
            <atom:updated>2022-05-02T09:53:32.494Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick note on writing Dockerfile for python projects that use pipenv for dependency management</h4><h4>What is pipenv?</h4><p>Pipenv helps us to maintain a deterministic set of external dependencies in Python projects. This is important because as our code gets installed on different machines at different times, there is a possibility that different versions of the package get installed. Further, this can make your code to crash because the APIs or behavior of your dependencies would have changed.</p><h4>Dockerfile with pipenv dependencies in requirements.txt</h4><p>Since Docker provides a well-defined environment for our code to run, anything possible with pipenv should be achievable by Docker.</p><p>To get proper dependencies installed in the container, we can store dependencies directly in requirements.txt and later install it directly from there. This not only creates a much smaller image (because we no longer have pipenv in the container) but also reduces the time taken to build the image by omitting pipenv install (we know <a href="https://github.com/pypa/pipenv/issues/2284">pipenv install is slow</a>).</p><pre>FROM python:3.6-alpine<br>...</pre><pre>RUN apk update &amp;&amp; \<br>    apk add --no-cache python3-dev &amp;&amp; \<br>    pip3 install pipenv &amp;&amp; \<br>    pipenv lock -r &gt; requirements.txt &amp;&amp; \<br>    pip3 uninstall --yes pipenv &amp;&amp; \<br>    pip3 install -r requirements.txt &amp;&amp; \<br>    apk del python3-dev &amp;&amp; \<br>    ...</pre><h4>Testing containers and dev dependencies</h4><p>In the image we created earlier, we didn’t have dev dependencies installed. Though this would make the container size small, we will not longer be able to run tests inside the container.</p><p>This problem can be solved by having a separate requirements file for dev dependencies and install it whenever needed —</p><pre>FROM python:3.6-alpine<br>...</pre><pre>RUN apk update &amp;&amp; \<br>    apk add --no-cache python3-dev &amp;&amp; \<br>    pip3 install pipenv &amp;&amp; \<br>    pipenv lock -r &gt; requirements.txt &amp;&amp; \<br>    <strong>pipenv lock --dev -r &gt; dev-requirements.txt</strong> &amp;&amp; \<br>    pip3 uninstall --yes pipenv &amp;&amp; \<br>    pip3 install -r requirements.txt &amp;&amp; \<br>    apk del python3-dev &amp;&amp; \<br>    ...</pre><p>To run tests on this image, we can have the following setup in our CI environment —</p><pre>test_docker:<br>  image: &lt;<em>the-above-image-name</em>&gt;<br>  before_script:<br>    - apk add python3-dev<br>  script:<br>    - pip3 install -r /src/dev-requirements.txt<br>    - python manage.py test</pre><p>The above snippet uses <a href="https://about.gitlab.com/">Gitlab</a> <a href="https://en.wikipedia.org/wiki/Continuous_integration">CI</a> and <a href="https://www.djangoproject.com/">Django</a> as an example, but the idea can be extended to any possible combination.</p><h4>Limitations</h4><p>I have been using this setup in <a href="https://gosocial.io/">GoSocial</a> and haven’t faced any limitations. However, one pain point of stripping pipenv from the project is losing the ability to run <a href="https://pipenv-fork.readthedocs.io/en/latest/advanced.html#custom-script-shortcuts">custom scripts defined in Pipfile</a>. This results in situations where we need to enter long and complex commands in a shell, significantly increasing the scope for human error. Though in most of the scenarios, this will be a rare event as we have these scripts pre-written (like Procfiles, CI config, etc.).</p><p>pipenv is an awesome tool for setting up a well-defined environment for running our Python code. But when we have tools like Docker at our disposal, we can omit pipenv to run a faster, yet consistent version of our application across machines. This not only results in a smaller-sized container but also improves the build time for it, which everyone loves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3be128f1444" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/docker-containers-for-pipenv-3be128f1444">Docker containers for pipenv</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1Ramp’s Alpha Web App is Open-Source on GitHub]]></title>
            <link>https://medium.com/hapramp/hapramps-alpha-web-app-is-open-source-on-github-b999b174f220?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/b999b174f220</guid>
            <category><![CDATA[announcements]]></category>
            <category><![CDATA[press-release]]></category>
            <category><![CDATA[product-updates]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Mon, 09 Jul 2018 11:19:28 GMT</pubDate>
            <atom:updated>2020-03-12T06:24:40.147Z</atom:updated>
            <content:encoded><![CDATA[<h4>1Ramp is a Steem-Blockchain based social media for the creative communities. It rewards cryptocurrency to the users for sharing valuable work on the platform.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93f3Bpwd9gZfy8xFl0mZrw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/_yBEyYR8wps?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Goran Ivos</a> on <a href="https://unsplash.com/search/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The Blockchain-based Projects advocate for decentralization. One part of decentralization is to open-source the code and invite the developers to suggest ideas, improve, and build a better platform.</p><p>HapRamp’s Alpha Web App is open-source and it can be accessed on our GitHub organization: <a href="https://github.com/hapramp">HapRamp-GitHub</a>.</p><p>Link to the GitHub Repository: <a href="https://github.com/hapramp/alpha-web">1Ramp Alpha Web App</a>.</p><h4>Technology</h4><p>The web app uses <a href="https://reactjs.org/">React</a> as the base UI library. Bootstrapped with <a href="https://github.com/facebook/create-react-app">Create React App</a>, it uses many other popular JS libraries such as <a href="https://redux.js.org/">redux</a>, <a href="https://reacttraining.com/react-router/">react-router</a>, <a href="https://lodash.com/">lodash</a>, etc.</p><p>For the full list of dependencies see the <a href="https://github.com/hapramp/alpha-web/blob/master/package.json">package.json</a>file.</p><h4>Connect with us on Discord: <a href="https://discord.gg/PkgCv8j">https://discord.gg/PkgCv8j</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tevG7QMXEdmuTILXInZakw.png" /><figcaption>Start the conversation on Discord.</figcaption></figure><p><a href="https://discord.gg/PkgCv8j"><strong>Invite link!</strong></a></p><p>We are pretty active on the Discord. If you have any queries, suggestions, or you want to get an early access to the platform and help us with feedback — do join our Discord server.</p><h4>Want to contribute?</h4><p>You can contribute to the HapRamp project in many ways. The easiest being <a href="https://github.com/hapramp/alpha-web/issues/new">opening an issue</a> for reporting a bug or making a feature request. You can also create pull requests to improve the app.</p><p><em>This blog was originally published on </em><a href="https://alpha.1ramp.io/"><em>alpha.1ramp.io</em></a><em>: </em><a href="https://alpha.1ramp.io/@singhpratyush/open-sourcing-hapramp-alpha-web-app-and-adding-travis-ci"><em>Open sourcing 1Ramp Alpha web app and adding Travis CI</em></a><em>.</em></p><p><em>For more information, please visit: </em><a href="https://1ramp.io/"><em>1Ramp.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b999b174f220" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hapramp/hapramps-alpha-web-app-is-open-source-on-github-b999b174f220">1Ramp’s Alpha Web App is Open-Source on GitHub</a> was originally published in <a href="https://medium.com/hapramp">Hapramp Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Taste of Media Streaming with Flask]]></title>
            <link>https://codeburst.io/the-taste-of-media-streaming-with-flask-cdce35908a50?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdce35908a50</guid>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Mon, 29 Jan 2018 16:46:28 GMT</pubDate>
            <atom:updated>2021-07-17T12:34:23.774Z</atom:updated>
            <content:encoded><![CDATA[<h4>A journey from hardly serving an 8 min song to instantly streaming 5 hour jukeboxes in AnyAudio</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*LUOeruyHbP5I-syqgozJHg.png" /><figcaption>Photo by <a href="https://unsplash.com/photos/oI3Vb4Q_Nl0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austin Neill</a> on <a href="https://unsplash.com/search/photos/streaming?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a> (Edited)</figcaption></figure><p><strong>AnyAudio</strong> is a hobby project which I started with my friends in the 2nd year of my engineering. As of now, it consists of an <a href="https://api.anyaudio.in/">API server</a> (which also serves media 😅), a <a href="https://web.anyaudio.in/">React-based PWA</a> (at least that’s what I am trying to make it), and an <a href="https://github.com/anyaudio/anyaudio-android-app">Android app</a>. There is a <a href="https://github.com/anyaudio">Github organization</a> dedicated to the different components of the project.</p><p>In this blog post, I will discuss the path our streaming API went through to become good enough for daily use.</p><h3>But where do you get ’em media from?</h3><blockquote>“Where can you find every single version of every song you have ever listened?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*YhPb6jw0W9a0BotLChloOw.png" /><figcaption>Courtesy of <a href="https://www.youtube.com/">YouTube</a></figcaption></figure><p>Simple, <a href="https://www.youtube.com/">YouTube</a>!</p><p>YouTube hosts every song that ever existed and will continue to do so. Not just that, it also has various formats and bit-rates for audio that it hosts. Not to mention the accuracy of search results that it presents.</p><p>Keeping these things in mind, we decided to use YouTube as the source of data for everything — search results, playlists, media, autocomplete and what not.</p><p>Most of the part was scraped from YouTube but to fetch the audio URL of a video, we used <a href="https://rg3.github.io/youtube-dl/">youtube-dl</a> (a command-line tool to download videos from YouTube and <a href="https://rg3.github.io/youtube-dl/supportedsites.html">many other websites</a>).</p><h3>Flow of Requests for Streaming</h3><p>In order to stream an audio, a client needs to follow the following flow of requests —</p><ol><li>Get the details for the audio it wants to play. <br>As of now, there are two ways to do this — using search and from predefined playlists.</li><li>Once the client has details of the audio, it requests the stream_url from the server (when needed).</li><li>The server then responds with a URL where the client can make the request in order to get the actual audio.<br>This is the URL it can embed in the &lt;audio../&gt; tag or <a href="https://github.com/google/ExoPlayer">ExoPlayer</a> source to directly play the song. It is again served by the AnyAudio server.</li><li>The server acts as a middleman and redirects the data from YouTube to the client.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4Xo9pANvr6QNUHHcC6Fng.jpeg" /><figcaption>The flow of requests for streaming in AnyAudio</figcaption></figure><p>The first thing that may come to your mind is that <strong>“Why does the client need to make an extra request to fetch the actual stream URL?”</strong></p><p>This is because finding out the actual media URL is a time-consuming process. youtube-dl takes a fair amount of time to get the resource location of a YouTube video. Fetching it in advance for every media in search results or playlists will be a pain in the UX. So, we decided to generate it on demand from the client.</p><p>This is how we got the stream API <em>working</em>. But in order to make it usable, we had to make a lot of improvements.</p><h3>Bruh, do you even seek?</h3><p>The API provided a final URL in the stream API. But when using this URL as a source, the resulting player was not seekable. This behavior was not acceptable for a media-playing website.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FuprwwjptZW4Za%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FuprwwjptZW4Za%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FuprwwjptZW4Za%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="324" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe62b4b2a89b7bf3b4ac21e94b44796/href">https://medium.com/media/8fe62b4b2a89b7bf3b4ac21e94b44796/href</a></iframe><p>After looking up a solution on the Internet (like this <a href="https://stackoverflow.com/questions/35751736/seeking-in-html5-video-with-chrome">StackOverflow question</a>), I found out that <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206">partial content</a> support was necessary for creating media elements that are seekable.</p><p>In order for clients to know that partial content is supported by the server, the server needs to add the following header to the response —</p><pre>&quot;Accept-Ranges&quot;: &quot;bytes&quot;</pre><p>This implies that the server is capable of serving partial content, specified as a range of bytes.</p><p>To add this header to responses, one can use the following decoration —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b9116a6fd14f4af7f1eb30979b0107d/href">https://medium.com/media/0b9116a6fd14f4af7f1eb30979b0107d/href</a></iframe><p>After this, the clients would know that the server supports partial content. And they will start sending a request header mentioning the byte range for which they want the data. It looks something like this —</p><pre>Range: bytes=0-1023</pre><p>So we now had to serve only this part of the media file when asked. In flask, this can be easily done as follows —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d955db6ee8739fe8267795dc139bcbaf/href">https://medium.com/media/d955db6ee8739fe8267795dc139bcbaf/href</a></iframe><p>After this, the seekbar was functional and the user could go to any position on any playing audio.</p><h3>The problem with long songs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeoeucAOAiqayDcCL8X6tg.png" /><figcaption><a href="https://www.youtube.com/watch?v=GIbYxVynGpA">A really long YouTube video</a></figcaption></figure><p>Streaming audio on AnyAudio was now a better experience than before. But there is a problem here. For every media request made to the server, the first thing done is fetching the media from YouTube servers (see line 1 in the code above). And after this, a fixed part of the media is sent as a response to the client.</p><p>The lengthy songs present on YouTube, such as jukeboxes and music compilations, have a large file size just for the audio. And considering the fact that there is a backend request made by the media player for every seek, listening to long audio would take forever.</p><p>The solution to this is quite simple — ask just for what you need.</p><h3>Ask just for what you need</h3><p>Earlier, every request of media made to the server resulted in downloading the whole audio from YouTube before serving any. This problem was solved by —</p><ol><li>Limiting the size of media served by the server with each stream request.</li><li>Requesting partial content from YouTube.</li></ol><p>The limit of file size helps to restrict the amount of data that will be requested from YouTube and as a result, we will have much more deterministic stream time than before. Here is a piece of code that explains the process —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96ad40a0fb0e6366f0bae74d25631216/href">https://medium.com/media/96ad40a0fb0e6366f0bae74d25631216/href</a></iframe><p>By putting the Range header with the request made to YouTube, the amount of data that the server needs to download before serving it to the client becomes less.</p><h3>One more step forward — Connecting Streams</h3><p>With this change, streaming was a lot better than before. But this was still not the optimal performance that one expects from a media streaming service.</p><p>The client doesn’t get a response from the server unless the server has downloaded the partial data from YouTube and the response has been prepared and sent. This can be improved by streaming the content from YouTube directly to the user. In simple words, by connecting the data stream from YouTube to the connection where the client is expecting a reply.</p><p>To enable streaming in <a href="https://github.com/requests/requests">requests</a>, we can simply add the stream=True parameter while making the request. Combining this with <a href="http://flask.pocoo.org/docs/0.12/patterns/streaming/">Flask’s streaming abilities</a>, we can instantly start serving data to the client without waiting for some requests to complete. Here is a rough sample of how this would work —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d943140f8f5ef12a93e11c2459f9a5cb/href">https://medium.com/media/d943140f8f5ef12a93e11c2459f9a5cb/href</a></iframe><p>This resulted in a Time to First Byte (TTFB) value of around 400ms on a dual-core server with average client speed. Though this is nowhere compared to the requests made to YouTube from the same client (around 15ms), it is an achievement for a hobby project with a cheap server.</p><h3>What are we planning next?</h3><p>As of now, it is very difficult to invest time in AnyAudio. But we are really looking forward to introducing API v3 to the server which allows more straightforward requests and playlist support. This would mean that users would be able to listen to complete YouTube playlists on the web app.</p><p>We are also planning to improve the suggestions made on the web app. As of now, it is just related to the current song that is being played. But instead, it can be a lot better by taking into account the reader’s listening habits, search queries, how often the songs bump into the suggestion for the user and so on.</p><p>Integrating this would require the users to create an account on the platform, which we do not wish to include as we just want the platform to be as hassle-free as possible. So for this, we are planning just to use the browser’s local storage. Additional features would include saving songs and listening to them whenever the user wants. Offline listening is also something that we are looking to integrate once it turns out to be a good PWA.</p><h3>Parting words</h3><p>I have learned a lot from this project and hope to learn a lot more. We would love it if you drop by and star our <a href="https://github.com/anyaudio/">GitHub repositories</a>. And if you are a developer and love to fix some dirty code and introduce awesome test cases, feel free to get in touch with us at our <a href="https://gitter.im/Any-Audio/">Gitter channel</a>.</p><figure><a href="https://web.anyaudio.in/"><img alt="" src="https://cdn-images-1.medium.com/max/150/1*8uYQhr1nQqhXwZnnc2DW5Q.png" /></a></figure><h4>So, visit <a href="https://web.anyaudio.in/">AnyAudio</a> now to listen to your favorite songs.</h4><p>Please let us know your views and stay tuned for more.</p><h3>❗Update</h3><p>The development/maintenance of AnyAudio has been stopped indefinitely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdce35908a50" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/the-taste-of-media-streaming-with-flask-cdce35908a50">The Taste of Media Streaming with Flask</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Posting Key in Steem based DApps]]></title>
            <link>https://medium.com/hapramp/handling-posting-key-in-steem-based-dapps-a03c7ab0310a?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/a03c7ab0310a</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[decentralization]]></category>
            <category><![CDATA[steem]]></category>
            <category><![CDATA[product-updates]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Wed, 24 Jan 2018 18:39:06 GMT</pubDate>
            <atom:updated>2018-05-06T07:47:06.399Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to’s and best practices about private posting key for your next DApp.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPUgcQsiZiSJCxRzHHM-9w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/FXFz-sW0uwo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/search/photos/cryptography?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The <a href="https://steem.io/">Steem</a> blockchain has rewarded more than <strong>$22 million</strong> to its users since June 2016. And with its <a href="https://developers.steem.io/">API</a> being released for public usage, we’ve seen many applications built on the top of it like <a href="https://busy.org/">Busy</a>, <a href="https://dsound.audio/">DSound</a>, <a href="https://d.tube/">DTube</a>, <a href="https://steepshot.io/">Steepshot</a>, etc.</p><p>These platforms provide users with a different interface to do different things; like publishing music, sharing photos and videos, blogging, etc. And since there are a lot of use cases where users can get rewarded for the content they create, there is a fair chance that you will come across the next cool thing and decide to work on it.</p><p>In such cases, you would like to provide your users with a functionality to vote, comment, create a post in your platform’s style and so on. But before you can do any of this, you would require user’s authorization.</p><p>In Steem, there are two ways to do this —</p><ul><li>Using <a href="https://steemconnect.com/">Steem Connect</a>.</li><li>Using the private posting key (more <a href="https://steemit.com/steemit-guides/@pfunk/a-user-s-guide-to-the-different-steem-keys-or-passwords">here</a>).</li></ul><p>In this post, I will be discussing only the posting key method and the practices that developers should follow while using it.</p><h3>Installing Dependencies</h3><p>The Steem API is available in Javascript and can be easily installed using npm —</p><pre>npm i --save steem</pre><p>or using yarn —</p><pre>yarn add steem</pre><p>after this, we are all set to go.</p><h3>Logging Users In</h3><p>The easiest way to log users in is by asking their <strong>username</strong> and <strong>private posting key</strong>.</p><p>After getting this data, here is the flow for verifying the credentials —</p><ol><li>Get the username and request user details from Steem API.</li><li>Extract the public posting key from the response to the previous step.</li><li>Use the Steem API to validate private key using the public key.</li><li>If success, set the cookies or localstorage or whatever you want, otherwise display some error message.</li></ol><p>Here is an example —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bf3692ba113614e81e05b8cb2b2db53/href">https://medium.com/media/7bf3692ba113614e81e05b8cb2b2db53/href</a></iframe><p>And once we are sure that the posting key provided by the user is correct, we can use it to comment, vote and create new posts. These actions are available in the steem.broadcast module.</p><h3>(Not) Storing the Posting Key</h3><p>The private key of the user can be used for the most powerful action on the Steem blockchain — content creation and curation.</p><p>So, the developers should NEVER store the posting key with themselves by making a POST request to their own back-end server (or something similar).</p><p>This would take away the power from users and introduce the <strong>trust</strong> element again in the blockchain, which is the USP of this technology.</p><p>If someone holds the posting keys of all the users on a platform, it is possible that they can use these keys to upvote some articles without the authorization of the user and ruin the complete motivation behind Steem.</p><p>Users should also take a deep look inside the platform before submitting their posting key to them, there are many <a href="https://en.wikipedia.org/wiki/Phishing">phishing</a> websites out there.</p><blockquote><em>We are currently working on the </em><a href="http://hapramp.com/"><em>HapRamp</em></a><em> platform. It is a social media for people who consider themselves a part of communities like music, dance, art, dramatics and so on.</em></blockquote><blockquote><em>Our app is currently in private beta phase and we will be making the first public release soon.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a03c7ab0310a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hapramp/handling-posting-key-in-steem-based-dapps-a03c7ab0310a">Handling Posting Key in Steem based DApps</a> was originally published in <a href="https://medium.com/hapramp">Hapramp Studio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Tweet Streaming Feature in World Mood Tracker loklak App]]></title>
            <link>https://singhpratyush.medium.com/adding-tweet-streaming-feature-in-world-mood-tracker-loklak-app-807afb15ecad?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/807afb15ecad</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[twitter]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Fri, 01 Sep 2017 15:23:23 GMT</pubDate>
            <atom:updated>2018-05-10T07:25:46.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*3v5e8XGmQice8dYqifpFuw.png" /></figure><p>The World Mood Tracker was added to <a href="https://apps.loklak.org/">loklak apps</a> with the feature to display aggregated data from the emotion classifier of <a href="https://api.loklak.org/">loklak server</a>. The next step in the app was adding the feature to display the stream of Tweets from a country as they are discovered by loklak. With the addition of stream servlet in loklak, it was possible to utilise it in this app.</p><p>In this blog post, I will be discussing the steps taken while adding to introduce this feature in World Mood Tracker app.</p><h3>Props for WorldMap component</h3><p>The WorldMap component holds the view for the map displayed in the app. This is where API calls to classifier endpoint are made and results are displayed on the map. In order to display tweets on clicking a country, we need to define react props so that methods from higher level components can be called.</p><p>In order to enable props, we need to change the constructor for the component –</p><pre><strong>export</strong> <strong>default</strong> <strong>class</strong> WorldMap <strong>extends</strong> React.Component {<br>    constructor(props) {<br>        <strong>super</strong>(props);<br>        ...<br>    }<br>    ...<br>}</pre><p>We can now pass the method from parent component to enable streaming and other components can close the stream by using props in them –</p><pre><strong>export</strong> <strong>default</strong> <strong>class</strong> WorldMoodTracker <strong>extends</strong> React.Component {<br>    ...<br>    showStream(countryName, countryCode) {<br>        /* Do something to enable streaming component */<br>        ...<br>    }<br> <br>    render() {<br>        <strong>return</strong> (<br>             ...<br>                &lt;WorldMap showStream={<strong>this</strong>.showStream}/&gt;<br>             ...<br>        )<br>    }<br>}</pre><h3>Defining Actions on Clicking Country Map</h3><p>As mentioned in an <a href="https://blog.fossasia.org/adding-react-based-world-mood-tracker-to-loklak-apps/">earlier blog post</a>, World Mood Tracker uses <a href="https://github.com/markmarkoh/datamaps/blob/master/README.md#getting-started">Datamaps</a> to visualize data on a map. In order to trigger a piece of code on clicking a country, we can use the “done” method of the Datamaps instance. This is where we use the props passed earlier –</p><pre>done: <strong>function</strong>(datamap) {<br>    datamap.svg.selectAll(&#39;.datamaps-subunit&#39;).on(&#39;click&#39;, <strong>function</strong> (geography) {<br>        props.showStream(geography.properties.name, reverseCountryCode(geography.id));<br>    })<br>}</pre><p>The name and ID for the country will be used to display name and make API call to stream endpoint respectively.</p><h3>The StreamOverlay Component</h3><p>The StreamOverlay components hold all the utilities to display the stream of Tweets from loklak. This component is used from its parent components whose state holds info about displaying this component –</p><pre><strong>export</strong> <strong>default</strong> <strong>class</strong> WorldMoodTracker <strong>extends</strong> React.Component {<br>    ...<br>    getStreamOverlay() {<br>        <strong>if</strong> (<strong>this</strong>.state.enabled) {<br>            <strong>return</strong> (&lt;StreamOverlay<br>                show={true} channel={<strong>this</strong>.state.channel}<br>                country={<strong>this</strong>.state.country} onClose={<strong>this</strong>.onOverlayClose}/&gt;);<br>        }<br>    }<br><br>    render() {<br>        <strong>return</strong> (<br>            ...<br>                {<strong>this</strong>.getStreamOverlay()}<br>            ...<br>        )<br>    }<br>}</pre><p>The corresponding props passed are used to render the component and connect to the stream from loklak server.</p><h3>Creating Overlay Modal</h3><p>On clicking the map, an overlay is shown. To display this overlay, <a href="https://github.com/react-bootstrap/react-overlay">react-overlays</a> is used. The Modal component offered by the packages provides a very simple interface to define the design and interface of the component, including style, onclose hook, etc.</p><pre><strong>import</strong> {Modal} from &#39;react-overlays&#39;;<br><br>&lt;Modal aria-labelledby=&#39;modal-label&#39;<br>    style={modalStyle}<br>    backdropStyle={backdropStyle}<br>    show={true}<br>    onHide={<strong>this</strong>.close}&gt;<br>    &lt;div style={dialogStyle()}&gt;<br>        ...<br>    &lt;/div&gt;<br>&lt;/Modal&gt;</pre><p>It must be noted that modalStyle and backdropStyle are React style objects.</p><h3>Dialog Style</h3><p>The dialog style is defined to provide some space at the top, clicking where, the overlay is closed. To do this, vertical height units are used –</p><pre><strong>const</strong> dialogStyle = <strong>function</strong> () {<br>    <strong>return</strong> {<br>        position: &#39;absolute&#39;,<br>        width: &#39;100%&#39;,<br>        top: &#39;5vh&#39;,<br>        height: &#39;95vh&#39;,<br>        padding: 20<br>        ...<br>    };<br>};</pre><h3>Connecting to loklak Tweet Stream</h3><p>loklak sends Server Sent Events to clients connected to it. To utilise this stream, we can use the natively supported EventSource object. Event stream is started with the render method of the StreamOverlay component –</p><pre>render () {<br>    <strong>this</strong>.startEventSource(<strong>this</strong>.props.channel);<br>    ...<br>}</pre><p>This channel is used to connect to twitter/country/&lt;country-ID&gt; channel on the stream and then this can be passed to EventStream constructor. On receiving a message, a list of Tweets is appended and later rendered in the view –</p><pre>startEventSource(country) {<br>    <strong>let</strong> channel = &#39;twitter%2Fcountry%2F&#39; + country;<br>    <strong>if</strong> (<strong>this</strong>.eventSource) {<br>        <strong>return</strong>;<br>    }<br>    <strong>this</strong>.eventSource = <strong>new</strong> EventSource(host + &#39;/api/stream.json?channel=&#39; + channel);<br>    <strong>this</strong>.eventSource.onmessage = (event) =&gt; {<br>        <strong>let</strong> json = JSON.<strong>parse</strong>(event.data);<br>        <strong>this</strong>.state.tweets.push(json);<br>        <strong>if</strong> (<strong>this</strong>.state.tweets.<strong>length</strong> &gt; 250) {<br>            <strong>this</strong>.state.tweets.shift();<br>        }<br>        <strong>this</strong>.setState(<strong>this</strong>.state);<br>    };<br>}</pre><p>The size of the list is restricted to 250 here, so when a newer Tweet comes in, the oldest one is chopped off. And thanks to fast DOM actions in React, the rendering doesn’t take much time.</p><h3>Rendering Tweets</h3><p>The Tweets are displayed as simple cards on which user can click to open it on Twitter in a new tab. It contains basic information about the Tweet — screen name and Tweet text. Images are not rendered as it would make no sense to load them when Tweets are coming at a high rate.</p><pre><strong>function</strong> getTweetHtml(json) {<br>    <strong>return</strong> (<br>        &lt;div style={{padding: &#39;5px&#39;, borderRadius: &#39;3px&#39;, border: &#39;1px solid black&#39;, margin: &#39;10px&#39;}}&gt;<br>            &lt;a href={json.<strong>link</strong>} target=&quot;_blank&quot;&gt;<br>            &lt;div style={{marginBottom: &#39;5px&#39;}}&gt;<br>                &lt;b&gt;@{json[&#39;screen_name&#39;]}&lt;/b&gt;<br>            &lt;/div&gt;<br>            &lt;div style={{overflowX: &#39;hidden&#39;}}&gt;{json[&#39;text&#39;]}&lt;/div&gt;<br>            &lt;/a&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>They are rendered using a simple map in the render method of StreamOverlay component –</p><pre>&lt;div className={styles.container} style={{&#39;height&#39;: &#39;100%&#39;, &#39;overflowY&#39;: &#39;auto&#39;,<br>    &#39;overflowX&#39;: &#39;hidden&#39;, maxWidth: &#39;100%&#39;}}&gt;<br>    {<strong>this</strong>.state.tweets.reverse().map(getTweetHtml)}<br>&lt;/div&gt;</pre><h3>Closing Overlay</h3><p>With the previous setup in place, we can now see Tweets from the loklak backend as they arrive. But the problem is that we will still be connected to the stream when we click-close the modal. Also, we would need to close the overlay from the parent component in order to stop rendering it.</p><p>We can use the onclose method for the Modal here –</p><pre>close() {<br>    <strong>if</strong> (<strong>this</strong>.eventSource) {<br>        <strong>this</strong>.eventSource.close();<br>        <strong>this</strong>.eventSource = null;<br>    }<br>    <strong>this</strong>.props.onClose();<br>}</pre><p>Here, props.onClose() disables rendering of StreamOverlay in the parent component.</p><h3>Conclusion</h3><p>In this blog post, I explained how the flow of props are used in the World Mood Tracker app to turn on and off the streaming in the overlay defined using react-overlays. This feature shows a basic setup for using the newly introduced stream API in loklak.</p><p>The motivation of such application was taken from <a href="https://github.com/mroth/emojitracker">emojitracker by mroth</a> as mentioned in <a href="https://github.com/fossasia/labs.fossasia.org/issues/136">fossasia/labs.fossasia.org#136</a>. The changes were proposed in <a href="https://github.com/fossasia/apps.loklak.org/pull/315">fossasia/apps.loklak.org#315</a> by <a href="https://github.com/singhpratyush">@singhpratyush</a> (me).</p><p>The app can be accessed live at <a href="https://singhpratyush.github.io/world-mood-tracker/index.html">https://singhpratyush.github.io/world-mood-tracker/index.html</a>.</p><h3>Resources</h3><ul><li>DataMaps documentation — <a href="https://github.com/markmarkoh/datamaps/blob/master/README.md#getting-started">https://github.com/markmarkoh/datamaps/blob/master/README.md#getting-started</a>.</li><li>React-overlays documentation and examples — <a href="https://react-bootstrap.github.io/react-overlays/">https://react-bootstrap.github.io/react-overlays/</a>.</li><li>How I Built Emojitracker by Matthew Rothenberg — <a href="https://medium.com/@mroth/how-i-built-emojitracker-179cfd8238ac">https://medium.com/@mroth/how-i-built-emojitracker-179cfd8238ac</a>.</li><li>Props in ReactJS — <a href="https://facebook.github.io/react/docs/components-and-props.html">https://facebook.github.io/react/docs/components-and-props.html</a>.</li><li>Channels available in loklak server for streaming — <a href="https://github.com/loklak/loklak_server/blob/development/docs/misc/StreamChannels.md">https://github.com/loklak/loklak_server/blob/development/docs/misc/StreamChannels.md</a>.</li></ul><p><em>Originally published at </em><a href="https://blog.fossasia.org/adding-tweet-streaming-feature-in-world-mood-tracker-loklak-app/"><em>blog.fossasia.org</em></a><em> on September 1, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=807afb15ecad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Stream Servlet in loklak Server]]></title>
            <link>https://singhpratyush.medium.com/introducing-stream-servlet-in-loklak-server-ead6676112b9?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/ead6676112b9</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Sat, 26 Aug 2017 14:42:38 GMT</pubDate>
            <atom:updated>2018-05-10T07:26:10.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*Iwd0sW4Br8j38Fsk." /></figure><p>A major part of my GSoC proposal was adding stream API to <a href="http://loklak.org/">loklak</a> server. In a <a href="https://blog.fossasia.org/using-mosquitto-as-a-message-broker-for-mqtt-in-loklak-server/">previous blog post</a>, I discussed the addition of <a href="https://mosquitto.org/">Mosquitto</a> as a message broker for MQTT streaming. After testing this service for a few days and some minor improvements, I was in a position to expose the stream to outside users using a simple API.</p><p>In this blog post, I will be discussing the addition of /api/stream.json endpoint to loklak server.</p><h3>HTTP Server-Sent Events</h3><blockquote><a href="https://en.wikipedia.org/wiki/Server-sent_events"><em>Server-sent events</em></a><em> (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection. The Server-Sent Events </em><a href="https://developer.mozilla.org/en/docs/Web/API/EventSource"><em>EventSource API</em></a><em> is standardized as part of HTML5 by the </em><a href="https://www.w3.org/"><em>W3C</em></a><em>.</em></blockquote><p>– <a href="https://en.wikipedia.org/wiki/Server-sent_events">Wikipedia</a></p><p>This API is supported by all major browsers except Microsoft Edge. For loklak, the plan was to use this event system to send messages, as they arrive, to the connected users. Apart from browser support, EventSource API can also be used with many other technologies too.</p><h3>Jetty Eventsource Plugin</h3><p>For Java, we can use Jetty’s <a href="https://github.com/jetty-project/jetty-eventsource-servlet/wiki">EventSource</a> plugin to send events to clients. It is similar to other Jetty servlets when it comes to processing the arguments, handling requests, etc. But it provides a simple interface to send events as they occur to connected users.</p><h3>Adding Dependency</h3><p>To use this plugin, we can add the following line to Gradle dependencies –</p><pre>compile group: &#39;org.eclipse.jetty&#39;, name: &#39;jetty-eventsource-servlet&#39;, version: &#39;1.0.0&#39;</pre><h3>The Event Source</h3><p>An EventSource is the object which is required for EventSourceServlet to send events. All the logics for emitting events needs to be defined in the related class. To link a servlet with an EventSource, we need to override the newEventSource method –</p><pre>public class StreamServlet extends EventSourceServlet {<br>    @Override<br>    protected EventSource newEventSource(HttpServletRequest request) {<br>        String channel = request.getParameter(&quot;channel&quot;);<br>        if (channel == null) {<br>            return null;<br>        }<br>        if (channel.isEmpty()) {<br>            return null;<br>        }<br>        return new MqttEventSource(channel);<br>    }<br>}</pre><p>If no channel is provided, the EventSource object will be null and the request will be rejected. Here, the MqttEventSource would be used to handle the stream of Tweets as they arrive from the Mosquitto message broker.</p><h3>Cross Site Requests</h3><p>Since the requests to this endpoint can’t be of JSONP type, it is necessary to allow cross site requests on this endpoint. This can be done by overriding the doGet method of the servlet –</p><pre>@Override<br>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br>    response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);<br>    super.doGet(request, response);<br>}</pre><h3>Adding MQTT Subscriber</h3><p>When a request for events arrives, the constructor to MqttEventSource is called. At this stage, we need to connect to the stream from Mosquitto for the channel. To achieve this, we can set the class as MqttCallback using appropriate client configurations –</p><pre>public class MqttEventSource implements MqttCallback {<br>    ...<br>    MqttEventSource(String channel) {<br>        this.channel = channel;<br>    }<br>    ...<br>    this.mqttClient = new MqttClient(address, &quot;loklak_server_subscriber&quot;);<br>    this.mqttClient.connect();<br>    this.mqttClient.setCallback(this);<br>    this.mqttClient.subscribe(this.channel);<br>    ...<br>}</pre><p>By setting the callback to this, we can override the messageArrived method to handle the arrival of a new message on the channel. Just to mention, the client library used here is <a href="https://www.eclipse.org/paho/">Eclipse Paho</a>.</p><h3>Connecting MQTT Stream to SSE Stream</h3><p>Now that we have subscribed to the channel we wish to send events from, we can use the Emitter to send events from our EventSource by implementing it –</p><pre>public class MqttEventSource implements EventSource, MqttCallback {<br>    private Emitter emitter;<br><br><br>    @Override<br>    public void onOpen(Emitter emitter) throws IOException {<br>        this.emitter = emitter;<br>        ...<br>    }<br><br>    @Override<br>    public void messageArrived(String topic, MqttMessage message) throws Exception {<br>        this.emitter.data(message.toString());<br>    }<br>}</pre><h3>Closing Stream on Disconnecting from User</h3><p>When a client disconnects from the stream, it doesn’t makes sense to stay connected to the server. We can use the onClose method to disconnect the subscriber from the MQTT broker –</p><pre>@Override<br>public void onClose() {<br>    try {<br>        this.mqttClient.close();<br>        this.mqttClient.disconnect();<br>    } catch (MqttException e) {<br>        // Log some warning <br>    }<br>}</pre><h3>Conclusion</h3><p>In this blog post, I discussed connecting the MQTT stream to SSE stream using Jetty’s EventSource plugin. Once in place, this event system would save us from making too many requests to collect and visualize data. The possibilities of applications of such feature are huge.</p><p>This feature can be seen in action at the <a href="https://github.com/fossasia/apps.loklak.org/tree/master/WorldMoodTracker">World Mood Tracker</a> app.</p><p>The changes were introduced in pull request <a href="https://github.com/loklak/loklak_server/pull/1474">loklak/loklak_server#1474</a> by <a href="https://github.com/singhpratyush">@singhpratyush</a> (me).</p><h3>Resources</h3><ul><li>Using Mosquitto as a Message Broker for MQTT in loklak Server — <a href="https://blog.fossasia.org/using-mosquitto-as-a-message-broker-for-mqtt-in-loklak-server/">https://blog.fossasia.org/using-mosquitto-as-a-message-broker-for-mqtt-in-loklak-server/</a>.</li><li>Using server-sent events — Mozilla Developers Network — <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events</a>.</li><li>Server-Sent Events W3C Specifications — <a href="https://www.w3.org/TR/2009/WD-eventsource-20090423/">https://www.w3.org/TR/2009/WD-eventsource-20090423/</a>.</li><li>More about Eclipse Paho Java Client — <a href="https://www.eclipse.org/paho/clients/java/">http://www.eclipse.org/paho/clients/java/</a>.</li><li>Event Source Example by marschall — <a href="https://github.com/marschall/event-source-sample">https://github.com/marschall/event-source-sample</a>.</li></ul><p><em>Originally published at </em><a href="https://blog.fossasia.org/introducing-stream-servlet-in-loklak-server/"><em>blog.fossasia.org</em></a><em> on August 26, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ead6676112b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimising Docker Images]]></title>
            <link>https://singhpratyush.medium.com/optimising-docker-images-7d40ada95517?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d40ada95517</guid>
            <category><![CDATA[google-summer-of-code]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Tue, 15 Aug 2017 11:21:58 GMT</pubDate>
            <atom:updated>2018-05-08T10:33:08.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/659/0*eTgPDDWtPqXjeh08." /></figure><p>The <a href="http://api.loklak.org/">loklak server</a> was in a process of moving to Kubernetes. In order to do so, we needed to have different Docker images that suit these deployments. In this blog post, I will be discussing the process through which I optimised the size of Docker image for these deployments.</p><h3>Initial Image</h3><p>The image that I started with used Ubuntu as base. It installed all the components needed and then modified the configurations as required –</p><pre>FROM ubuntu:latest<br><br># Env Vars<br>ENV LANG=en_US.UTF-8<br>ENV JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8<br>ENV DEBIAN_FRONTEND noninteractive<br><br>WORKDIR /loklak_server<br><br>RUN apt-get update<br>RUN apt-get upgrade -y<br>RUN apt-get install -y git openjdk-8-jdk<br>RUN git clone https://github.com/loklak/loklak_server.git /loklak_server<br>RUN git checkout development<br>RUN ./gradlew build -x test -x checkstyleTest -x checkstyleMain -x jacocoTestReport<br>RUN sed -i.bak &#39;s/^\(port.http=\).*/\180/&#39; conf/config.properties<br>... # More configurations<br>RUN echo &quot;while true; do sleep 10;done&quot; &gt;&gt; bin/start.sh<br><br># Start<br>CMD [&quot;bin/start.sh&quot;, &quot;-Idn&quot;]</pre><p>The size of images built using this Dockerfile was quite huge –</p><pre>REPOSITORY        TAG      IMAGE ID          CREATED          SIZE<br><br>loklak_server   latest  a92f506b360d   About a minute ago   1.114 GB<br><br>ubuntu          latest  ccc7a11d65b1      3 days ago        120.1 MB</pre><p>But since this size is not acceptable, we needed to reduce it.</p><h3>Moving to Apline</h3><p><a href="https://alpinelinux.org/">Alpine Linux</a> is an extremely lightweight Linux distro, built mainly for the container environment. Its size is so tiny that it hardly puts any impact on the overall size of images. So, I replaced Ubuntu with Alpine –</p><pre>FROM alpine:latest<br><br>...<br>RUN apk update<br>RUN apk add git openjdk8 bash<br>...</pre><p>And now we had much smaller images –</p><pre>REPOSITORY        TAG      IMAGE ID          CREATED          SIZE</pre><pre>loklak_server   latest  54b507ee9187    17 seconds ago      668.8 MB<br><br>alpine          latest  7328f6f8b418    6 weeks ago         3.966 MB</pre><p>As we can see that due to no caching and small size of Alpine, the image size is reduced to almost half the original.</p><h3>Reducing Content Size</h3><p>There are many things in a project which are no longer needed while running the project, like the .git folder (which is huge in case of loklak) –</p><pre>$ du -sh loklak_server/.git<br>236M loklak_server/.git</pre><p>We can remove such files from the Docker image and save a lot of space –</p><pre>rm -rf .[^.] .??*</pre><h3>Optimizing Number of Layers</h3><p>The number of layers also affect the size of the image. More the number of layers, more will be the size of image. In the Dockerfile, we can club together the RUN commands for lower number of images.</p><pre>RUN apk update &amp;&amp; apk add openjdk8 git bash &amp;&amp; \<br>  git clone https://github.com/loklak/loklak_server.git /loklak_server &amp;&amp; \<br>  ...</pre><p>After this, the effective size is again reduced by a major factor –</p><pre>REPOSITORY        TAG      IMAGE ID          CREATED          SIZE<br>loklak_server   latest   54b507ee9187   17 seconds ago      422.3 MB<br><br>alpine          latest   7328f6f8b418     6 weeks ago       3.966 MB</pre><h3>Conclusion</h3><p>In this blog post, I discussed the process of optimising the size of Dockerfile for Kubernetes deployments of loklak server. The size was reduced to 426 MB from 1.234 GB and this provided much faster push/pull time for Docker images, and therefore, faster updates for Kubernetes deployments.</p><h3>Resources</h3><ul><li>Docker Tutorial Series : Writing a Dockerfile — <a href="https://rominirani.com/docker-tutorial-series-writing-a-dockerfile-ce5746617cd">https://rominirani.com/docker-tutorial-series-writing-a-dockerfile-ce5746617cd</a>.</li><li>Deploying loklak Server on Kubernetes with External Elasticsearch — <a href="https://blog.fossasia.org/deploying-loklak-server-on-kubernetes-with-external-elasticsearch/">https://blog.fossasia.org/deploying-loklak-server-on-kubernetes-with-external-elasticsearch/</a></li><li>Dockerfile Best Practices — <a href="https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/">https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/</a>.</li><li>How to Optimize Your Dockerfile — <a href="https://blog.tutum.co/2014/10/22/how-to-optimize-your-dockerfile/">https://blog.tutum.co/2014/10/22/how-to-optimize-your-dockerfile/</a>.</li></ul><p><em>Originally published at </em><a href="https://blog.fossasia.org/optimising-docker-images-for-loklak-server/"><em>blog.fossasia.org</em></a><em> on August 15, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d40ada95517" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persistent Storage and Kubernetes]]></title>
            <link>https://singhpratyush.medium.com/persistent-storage-and-kubernetes-e0a1ed3f0b53?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0a1ed3f0b53</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[google-summer-of-code]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Thu, 10 Aug 2017 20:00:06 GMT</pubDate>
            <atom:updated>2018-05-10T07:00:20.039Z</atom:updated>
            <content:encoded><![CDATA[<h4>Storing server dumps on Kubernetes with Google Cloud Platform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*6cmEfsFW4wzvxvwf." /></figure><p>In an <a href="https://blog.fossasia.org/deploying-loklak-server-on-kubernetes-with-external-elasticsearch/">earlier blog post</a>, I discussed loklak setup on <a href="https://kubernetes.io/">Kubernetes</a>. The deployment mentioned in the post was to test the development branch. Next, we needed to have a deployment where all the messages are collected and dumped in text files that can be reused.</p><p>In this blog post, I will be discussing the challenges with such deployment and the approach to tackle them.</p><h3>Volatile Disk in Kubernetes</h3><p>The pods that hold deployments in Kubernetes have disk storage. Any data that gets written by the application stays only until the same version of deployment is running. As soon as the deployment is updated/relocated, the data stored during the application is cleaned up.</p><p>Due to this, dumps are written when loklak is running but they get wiped out when the deployment image is updated. In other words, all dumps are lost when the image updates. We needed to find a solution to this as we needed a permanent storage when collecting dumps.</p><h3>Persistent Disk</h3><p>In order to have a storage which can hold data permanently, we can mount persistent disk(s) on a pod at the appropriate location. This ensures that the data that is important to us stays with us, even when the deployment goes down.</p><p>In order to add persistent disks, we first need to create a persistent disk. On Google Cloud Platform, we can use the gcloud CLI to create disks in a given region –</p><pre>gcloud compute disks create --size=&lt;required size&gt; --zone=&lt;same as cluster zone&gt; &lt;unique disk name&gt;</pre><p>After this, we can mount it on a Docker volume defined in Kubernetes configurations –</p><pre>      ...<br>      volumeMounts:<br>        - mountPath: /path/to/mount<br>          name: volume-name<br>  volumes:<br>    - name: volume-name<br>      gcePersistentDisk:<br>        pdName: disk-name<br>        fsType: fileSystemType</pre><p>But this setup can’t be used for storing loklak dumps. Let’s see “why” in the next section.</p><h3>Rolling Updates and Persistent Disk</h3><p>The Kubernetes deployment needs to be updated when the master branch of loklak server is updated. This update of master deployment would create a new pod and try to start loklak server on it. During all this, the older deployment would also be running and serving the requests.</p><p>The control will not be transferred to the newer pod until it is ready and all the probes are passing. The newer deployment will now try to mount the disk which is mentioned in the configuration, but it would fail to do so. This would happen because the older pod has already mounted the disk.</p><p>Therefore, all new deployments would simply fail to start due to insufficient resources. To overcome such issues, Kubernetes allows persistent volume claims. Let’s see how we used them for loklak deployment.</p><h3>Persistent Volume Claims</h3><p>Kubernetes provides <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistentvolumeclaims">Persistent Volume Claims</a> which claim resources (storage) from a <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">Persistent Volume</a> (just like a pod does from a node). The higher level APIs are provided by Kubernetes (configurations and kubectl command line). In the loklak deployment, the persistent volume is a Google Compute Engine disk –</p><pre>apiVersion: v1<br>kind: PersistentVolume<br>metadata:<br>  name: dump<br>  namespace: web<br>spec:<br>  capacity:<br>    storage: 100Gi<br>  accessModes:<br>    - ReadWriteOnce<br>  persistentVolumeReclaimPolicy: Retain<br>  storageClassName: slow<br>  gcePersistentDisk:<br>    pdName: &quot;data-dump-disk&quot;<br>    fsType: &quot;ext4&quot;</pre><p>[<a href="https://github.com/singhpratyush/loklak_server/blob/63d3dee241d5d163a5798bb40181e35495bd4257/kubernetes/yamls/master/api-server/api-persistence.yml">SOURCE</a>]</p><p>It must be noted here that a persistent disk by the name of data-dump-index is already created in the same region.</p><p>The storage class defines the way in which the PV should be handled, along with the provisioner for the service –</p><pre>kind: StorageClass<br>apiVersion: storage.k8s.io/v1<br>metadata:<br>  name: slow<br>  namespace: web<br>provisioner: kubernetes.io/gce-pd<br>parameters:<br>  type: pd-standard<br>  zone: us-central1-a</pre><p>[<a href="https://github.com/singhpratyush/loklak_server/blob/63d3dee241d5d163a5798bb40181e35495bd4257/kubernetes/yamls/master/api-server/api-storage.yml">SOURCE</a>]</p><p>After having the StorageClass and PersistentVolume, we can create a claim for the volume by using appropriate configurations –</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: dump<br>  namespace: web<br>spec:<br>  accessModes:<br>    - ReadWriteOnce<br>  resources:<br>    requests:<br>      storage: 100Gi<br>  storageClassName: slow</pre><p>[<a href="https://github.com/singhpratyush/loklak_server/blob/63d3dee241d5d163a5798bb40181e35495bd4257/kubernetes/yamls/master/api-server/api-pvc.yml">SOURCE</a>]</p><p>After this, we can mount this claim on our Deployment –</p><pre>  ...<br>  volumeMounts:<br>    - name: dump<br>      mountPath: /loklak_server/data<br>volumes:<br>  - name: dump<br>    persistentVolumeClaim:<br>      claimName: dump</pre><p>[<a href="https://github.com/singhpratyush/loklak_server/blob/63d3dee241d5d163a5798bb40181e35495bd4257/kubernetes/yamls/master/api-server/api-deployment.yml#L29L35">SOURCE</a>]</p><h3>Verifying persistence of Dumps</h3><p>To verify this, we can redeploy the cluster using the same persistent disk and check if the earlier dumps are still present there –</p><pre>$ http http://link.to.deployment/dump/<br>HTTP/1.1 200 OK<br>Cache-Control: public, max-age=60<br>Content-Type: text/html;charset=utf-8<br>...<br><br><br>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 3.2 Final//EN&quot;&gt;<br>…<br>&lt;h1&gt;Index of /dump&lt;/h1&gt;<br>&lt;pre&gt;      Name <br>[gz ] &lt;a href=&quot;messages_20170802_71562040.txt.gz&quot;&gt;messages_20170802_71562040.txt.gz&lt;/a&gt;   Thu Aug 03 00:07:21 GMT 2017   132M<br>[gz ] &lt;a href=&quot;messages_20170803_69925009.txt.gz&quot;&gt;messages_20170803_69925009.txt.gz&lt;/a&gt;   Mon Aug 07 15:40:04 GMT 2017   532M<br>[gz ] &lt;a href=&quot;messages_20170807_36357603.txt.gz&quot;&gt;messages_20170807_36357603.txt.gz&lt;/a&gt;   Wed Aug 09 10:26:24 GMT 2017   377M<br>[txt] &lt;a href=&quot;messages_20170809_27974404.txt&quot;&gt;messages_20170809_27974404.txt&lt;/a&gt;      Thu Aug 10 08:51:49 GMT 2017  1564M<br>&lt;hr&gt;&lt;/pre&gt;<br>...</pre><h3>Conclusion</h3><p>In this blog post, I discussed the process of deployment of loklak with persistent dumps on Kubernetes. This deployment is intended to work as root.loklak.org in near future. The changes were proposed in <a href="https://github.com/loklak/loklak_server/pull/1377">loklak/loklak_server#1377</a> by <a href="https://github.com/singhpratyush">@singhpratyush</a> (me).</p><h3>Resources</h3><ul><li>Deployment loklak image — <a href="https://github.com/loklak/loklak_server/blob/e896ee9e77f818e5c1c872ab0e623af71fa396b8/kubernetes/images/master/Dockerfile">https://github.com/loklak/loklak_server/blob/e896ee9e77f818e5c1c872ab0e623af71fa396b8/kubernetes/images/master/Dockerfile</a>.</li><li>Kubernetes Volumes — <a href="https://kubernetes.io/docs/concepts/storage/volumes/">https://kubernetes.io/docs/concepts/storage/volumes/</a>.</li><li>Dynamic Provisioning and Storage Classes in Kubernetes — <a href="http://blog.kubernetes.io/2016/10/dynamic-provisioning-and-storage-in-kubernetes.html">http://blog.kubernetes.io/2016/10/dynamic-provisioning-and-storage-in-kubernetes.html</a>.</li><li>Elasticsearch deployment in loklak — <a href="https://github.com/loklak/loklak_server/tree/e896ee9e77f818e5c1c872ab0e623af71fa396b8/kubernetes/yamls/development/elasticsearch">https://github.com/loklak/loklak_server/tree/e896ee9e77f818e5c1c872ab0e623af71fa396b8/kubernetes/yamls/development/elasticsearch</a>.</li></ul><p><em>Originally published at </em><a href="https://blog.fossasia.org/persistently-storing-loklak-server-dumps-on-kubernetes/"><em>blog.fossasia.org</em></a><em> on August 10, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0a1ed3f0b53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mosquitto as a Message Broker for MQTT]]></title>
            <link>https://singhpratyush.medium.com/mosquitto-as-a-message-broker-for-mqtt-b23ac79f634c?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/b23ac79f634c</guid>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[google-summer-of-code]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Tue, 08 Aug 2017 19:42:24 GMT</pubDate>
            <atom:updated>2018-05-23T05:10:33.241Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lightweight streaming for IoT devies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*N55pKOVA0zfFjdq8." /></figure><p>In <a href="http://api.loklak.org/">loklak server</a>, messages are collected from various sources and indexed using Elasticsearch. To know when a message of interest arrives, users can poll the search endpoint. But this method would require a lot of HTTP requests, most of them being redundant. Also, if a user would like to collect messages for a particular topic, he would need to make a lot of requests over a period of time to get enough data.</p><p>For GSoC 2017, my proposal was to introduce stream API in the loklak server so that we could save ourselves from making too many requests and also add many use cases.</p><p><a href="https://mosquitto.org/">Mosquitto</a> is <a href="https://www.eclipse.org/">Eclipse</a>’s project which acts as a message broker for the popular <a href="http://mqtt.org/">MQTT</a> protocol. MQTT, based on the pub-sub model, is a lightweight and IOT friendly protocol. In this blog post, I will discuss the basic setup of Mosquitto in the loklak server.</p><h3>Installation and Dependency for Mosquitto</h3><p>The installation process of Mosquitto is very simple. For Ubuntu, it is available from the pre installed PPAs –</p><pre>sudo apt-get install mosquitto</pre><p>Once the message broker is up and running, we can use the clients to connect to it and publish/subscribe to channels. To add MQTT client as a project dependency, we can introduce following line in Gradle dependencies file –</p><pre>compile group: &#39;net.sf.xenqtt&#39;, name: &#39;xenqtt&#39;, version: &#39;0.9.5&#39;</pre><p>[<a href="https://github.com/loklak/loklak_server/blob/b122c65531eee101bd7de692606b9a249a8e4cda/build.gradle#L137">SOURCE</a>]</p><p>After this, we can use the client libraries in the server code base.</p><h3>The MQTTPublisher Class</h3><p>The MQTTPublisher class in loklak would provide an interface to perform basic operations in MQTT. The implementation uses AsyncClientListener to connect to Mosquitto broker –</p><pre>AsyncClientListener listener = new AsyncClientListener() { <br>  // Override methods according to needs<br>};</pre><p>[<a href="https://github.com/loklak/loklak_server/blob/b122c65531eee101bd7de692606b9a249a8e4cda/src/org/loklak/stream/MQTTPublisher.java#L17L55">SOURCE</a>]</p><p>The publish method for the class can be used by other components of the project to publish messages on the desired channel –</p><pre>public void publish(String channel, String message) {<br>    this.mqttClient.publish(<br>        new PublishMessage(channel, QoS.AT_LEAST_ONCE, message)<br>    );<br>}</pre><p>[<a href="https://github.com/loklak/loklak_server/blob/b122c65531eee101bd7de692606b9a249a8e4cda/src/org/loklak/stream/MQTTPublisher.java#L61L63">SOURCE</a>]</p><p>We also have methods which allow publishing of multiple messages to multiple channels in order to increase the functionality of the class.</p><h3>Starting Publisher with Server</h3><p>The flags which signal using of streaming service in loklak are located in <a href="https://github.com/loklak/loklak_server/blob/development/conf/config.properties">conf/config.properties</a>. These configurations are referred while initializing the Data Access Object and an MQTTPublisher is created if needed –</p><pre>String mqttAddress = getConfig(<br>    &quot;stream.mqtt.address&quot;,<br>    &quot;tcp://127.0.0.1:1883&quot;<br>);<br>streamEnabled = getConfig(&quot;stream.enabled&quot;, false);<br>if (streamEnabled) {<br>    mqttPublisher = new MQTTPublisher(mqttAddress);<br>}</pre><p>[<a href="https://github.com/loklak/loklak_server/blob/b122c65531eee101bd7de692606b9a249a8e4cda/src/org/loklak/data/DAO.java#L403L409">SOURCE</a>]</p><p>The mqttPublisher can now be used by other components of loklak to publish messages to the channel they want.</p><h3>Adding Mosquitto to Kubernetes</h3><p>Since loklak has also a nice Kubernetes setup, it was very simple to introduce a new deployment for Mosquitto to it.</p><h3>Changes in Dockerfile</h3><p>The Dockerfile for master deployment has to be modified to discover Mosquitto broker in the Kubernetes cluster. For this purpose, corresponding flags in config.properties have to be changed to ensure that things work fine –</p><pre>sed -i.bak &#39;s/^\(stream.enabled\).*/\1=true/&#39; conf/config.properties &amp;&amp; \<br>sed -i.bak &#39;s/^\(stream.mqtt.address\).*/\1=mosquitto.mqtt:1883/&#39; conf/config.properties &amp;&amp; \</pre><p>[<a href="https://github.com/singhpratyush/loklak_server/blob/7659f6323151eb0753b34643a47fc84f8fd81be2/kubernetes/images/development/Dockerfile#L18L19">SOURCE</a>]</p><p>The Mosquitto broker would be available at mosquitto.mqtt:1883 because of the service that is created for it (explained in later section).</p><h3>Mosquitto Deployment</h3><p>The Docker image used in Kubernetes deployment of Mosquitto is taken from <a href="https://github.com/toke/docker-mosquitto">toke/docker-kubernetes</a>. Two ports are exposed for the cluster but no volumes are needed –</p><pre>apiVersion: extensions/v1beta1<br>kind: Deployment<br>metadata:<br>  name: mosquitto<br>  namespace: mqtt<br>spec:<br>  ...<br>  template:<br>    ...<br>    spec:<br>      containers:<br>      - name: mosquitto<br>        image: toke/mosquitto<br>        ports:<br>        - containerPort: 9001<br>        - containerPort: 8883</pre><p>[<a href="https://github.com/singhpratyush/loklak_server/blob/7659f6323151eb0753b34643a47fc84f8fd81be2/kubernetes/yamls/development/mosquitto/mqtt-deployment.yaml">SOURCE</a>]</p><h3>Exposing Mosquitto to the Cluster</h3><p>Now that we have the deployment running, we need to expose the required ports to the cluster so that other components may use it. The port 9001 appears as port 80 for the service and 1883 is also exposed –</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: mosquitto<br>  namespace: mqtt<br>  ...<br>spec:<br>  ...<br>  ports:<br>  - name: mosquitto<br>    port: 1883<br>  - name: mosquitto-web<br>    port: 80<br>    targetPort: 9001</pre><p>[<a href="https://github.com/singhpratyush/loklak_server/blob/7659f6323151eb0753b34643a47fc84f8fd81be2/kubernetes/yamls/development/mosquitto/mqtt-service.yaml">SOURCE</a>]</p><p>After creating the service using this configuration, we will be able to connect our clients to Mosquitto at address mosquitto.mqtt:1883.</p><h3>Conclusion</h3><p>In this blog post, I discussed the process of adding Mosquitto to the loklak server project. This is the first step towards introducing the stream API for messages collected in loklak.</p><p>These changes were introduced in pull requests <a href="https://github.com/loklak/loklak_server/pull/1393">loklak/loklak_server#1393</a> and <a href="https://github.com/loklak/loklak_server/pull/1398">loklak/loklak_server#1398</a> by <a href="https://github.com/singhpratyush">@singhpratyush</a> (me).</p><h3>Resources</h3><ul><li>Deploying loklak Server on Kubernetes with External Elasticsearch — <a href="https://blog.fossasia.org/deploying-loklak-server-on-kubernetes-with-external-elasticsearch/">https://blog.fossasia.org/deploying-loklak-server-on-kubernetes-with-external-elasticsearch/</a>.</li><li>Mosquitto Documentation — <a href="https://mosquitto.org/documentation/">https://mosquitto.org/documentation/</a>.</li><li>Manage data in containers — <a href="https://docs.docker.com/engine/tutorials/dockervolumes/">https://docs.docker.com/engine/tutorials/dockervolumes/</a>.</li><li>Services in Kubernetes — <a href="https://kubernetes.io/docs/concepts/services-networking/service/">https://kubernetes.io/docs/concepts/services-networking/service/</a>.</li><li>xenqtt API Documentation — <a href="http://xenqtt.sourceforge.net/apidocs/0.9.6/">http://xenqtt.sourceforge.net/apidocs/0.9.6/</a>.</li></ul><p><em>Originally published at </em><a href="https://blog.fossasia.org/using-mosquitto-as-a-message-broker-for-mqtt-in-loklak-server/"><em>blog.fossasia.org</em></a><em> on August 8, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b23ac79f634c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Elasticsearch based Application with Kubernetes]]></title>
            <link>https://singhpratyush.medium.com/deploying-elasticsearch-based-application-with-kubernetes-bb4839b6e406?source=rss-4747a35cc359------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb4839b6e406</guid>
            <category><![CDATA[google-summer-of-code]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Pratyush Singh]]></dc:creator>
            <pubDate>Mon, 07 Aug 2017 09:29:05 GMT</pubDate>
            <atom:updated>2018-05-11T04:54:51.711Z</atom:updated>
            <content:encoded><![CDATA[<h4>Automation, health checks, load balancing and data persistence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*DYZEc25o4oBRRaYvH9YKcA.png" /></figure><blockquote><em>Kubernetes is an open-source system for automating deployment, scaling, and management of containerized applications.</em></blockquote><p>It’s an awesome system, which ensures reliable operation of cloud applications. It supports automated health tests, smart roll out and rollbacks, simple scaling and a lot more.</p><p>So as a part of GSoC, I worked on taking the <a href="http://api.loklak.org/">loklak</a> server to Kubernetes on <a href="https://cloud.google.com/">Google Cloud Platform</a>. In this blog post, I will be discussing the approach followed to deploy development branch of loklak on Kubernetes.</p><h3>New Docker Image</h3><p>Since Kubernetes deployments work on Docker images, we needed one for the loklak project. The <a href="https://github.com/loklak/loklak_server/blob/development/Dockerfile">existing image</a> would not be up to the mark for Kubernetes as it contained the declaration of volumes and exposing of ports. So I wrote a <a href="https://github.com/loklak/loklak_server/blob/development/kubernetes/images/development/Dockerfile">new Docker image</a> which could be used in Kubernetes.</p><p>The image would simply clone loklak server, build the project and trigger the server as CMD –</p><pre>FROM alpine:latest<br><br>ENV LANG=en_US.UTF-8<br>ENV JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8<br><br>WORKDIR /loklak_server<br><br>RUN apk update &amp;&amp; apk add openjdk8 git bash &amp;&amp; \<br>    git clone https://github.com/loklak/loklak_server.git /loklak_server &amp;&amp; \<br>    git checkout development &amp;&amp; \<br>    ./gradlew build -x test -x checkstyleTest -x checkstyleMain -x jacocoTestReport &amp;&amp; \<br>    # Some Configurations and Cleanups<br><br>CMD [&quot;bin/start.sh&quot;, &quot;-Idn&quot;]</pre><p>This image wouldn’t have any volumes or exposed ports and we are now free to configure them in the configuration files (discussed in a later section).</p><h3>Building and Pushing Docker Image using Travis</h3><p>To automatically build and push on a commit to the master branch, Travis build is used. In the after_success section, a call to push Docker image is made.</p><p>Travis environment variables hold the username and password for Docker hub and are used for logging in –</p><pre>docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD</pre><p>We needed checks there to ensure that we are on the right branch for the push and we are not handling a pull request –</p><pre># Build and push Kubernetes Docker image<br>KUBERNETES_BRANCH=loklak/loklak_server:latest-kubernetes-$TRAVIS_BRANCH<br>KUBERNETES_COMMIT=loklak/loklak_server:kubernetes-$TRAVIS_COMMIT<br>  <br>if [ &quot;$TRAVIS_BRANCH&quot; == &quot;development&quot; ]; then<br>    docker build -t loklak_server_kubernetes kubernetes/images/development<br>    docker tag loklak_server_kubernetes $KUBERNETES_BRANCH<br>    docker push $KUBERNETES_BRANCH<br>    docker tag $KUBERNETES_BRANCH $KUBERNETES_COMMIT<br>    docker push $KUBERNETES_COMMIT<br>elif [ &quot;$TRAVIS_BRANCH&quot; == &quot;master&quot; ]; then<br>    # Build and push master<br>else<br>    echo &quot;Skipping Kubernetes image push for branch $TRAVIS_BRANCH&quot;<br>fi</pre><h3>Kubernetes Configurations for loklak</h3><p>Kubernetes cluster can completely be configured using configurations written in YAML format. The deployment of loklak uses the previously built image. Initially, the image tagged as latest-kubernetes-development is used –</p><pre>apiVersion: apps/v1beta1<br>kind: Deployment<br>metadata:<br>  name: server<br>  namespace: web<br>spec:<br>  replicas: 1<br>  template:<br>    metadata:<br>      labels:<br>        app: server<br>    spec:<br>      containers:<br>      - name: server<br>        image: loklak/loklak_server:latest-kubernetes-development<br>        ...</pre><h3>Readiness and Liveness Probes</h3><p>Probes act as the top level tester for the health of a deployment in Kubernetes. The probes are performed periodically to ensure that things are working fine and appropriate steps are taken if they fail.</p><p>When a new image is updated, the older pod still runs and servers the requests. It is replaced by the new ones only when the probes are successful, otherwise, the update is rolled back.</p><p>In loklak, the /api/status.json endpoint gives information about status of deployment and hence is a good target for probes –</p><pre>livenessProbe:<br>  httpGet:<br>    path: /api/status.json<br>    port: 80<br>  initialDelaySeconds: 30<br>  timeoutSeconds: 3<br>readinessProbe:<br>  httpGet:<br>    path: /api/status.json<br>    port: 80<br>  initialDelaySeconds: 30<br>  timeoutSeconds: 3</pre><p>These probes are performed periodically and the server is restarted if they fail (non-success HTTP status code or takes more than 3 seconds).</p><h3>Ports and Volumes</h3><p>In the configurations, port 80 is exposed as this is where Jetty serves inside loklak –</p><pre>ports:<br>- containerPort: 80<br>  protocol: TCP</pre><p>If we notice, this is the port that we used for running the probes. Since the development branch deployment holds no dumps, we didn’t need to specify any explicit volumes for persistence.</p><h3>Load Balancer Service</h3><p>While creating the configurations, a new public IP is assigned to the deployment using Google Cloud Platform’s load balancer. It starts listening on port 80 –</p><pre>ports:<br>- containerPort: 80<br>  protocol: TCP</pre><p>Since this service creates a new public IP, it is recommended not to replace/recreate this services as this would result in the creation of new public IP. Other components can be updated individually.</p><h3>Kubernetes Configurations for Elasticsearch</h3><p>To maintain a persistent index, this deployment would require an external Elasticsearch cluster. loklak is able to connect itself to external Elasticsearch cluster by changing a few configurations.</p><h3>Docker Image and Environment Variables</h3><p>The image used for Elasticsearch is taken from <a href="https://github.com/pires/docker-elasticsearch-kubernetes">pires/docker-elasticsearch-kubernetes</a>. It allows easy configuration of properties from environment variables in configurations. Here is a list of configurable variables, but we needed just a few of them to do our task –</p><pre>image: quay.io/pires/docker-elasticsearch-kubernetes:2.0.0<br>env:<br>- name: KUBERNETES_CA_CERTIFICATE_FILE<br>  value: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt<br>- name: NAMESPACE<br>  valueFrom:<br>    fieldRef:<br>      fieldPath: metadata.namespace<br>- name: &quot;CLUSTER_NAME&quot;<br>  value: &quot;loklakcluster&quot;<br>- name: &quot;DISCOVERY_SERVICE&quot;<br>  value: &quot;elasticsearch&quot;<br>- name: NODE_MASTER<br>  value: &quot;true&quot;<br>- name: NODE_DATA<br>  value: &quot;true&quot;<br>- name: HTTP_ENABLE<br>  value: &quot;true&quot;[<a href="https://github.com/loklak/loklak_server/blob/development/kubernetes/yamls/development/elasticsearch/es-deployment.yaml#L34L51">SOURCE</a>]</pre><h3>Persistent Index using Persistent Cloud Disk</h3><p>To make the index last even after the deployment is stopped, we needed a stable place where we could store all that data. Here, Google Compute Engine’s standard persistent disk was used. The disk can be created using GCP web portal or the gcloud CLI.</p><p>Before attaching the disk, we need to declare a volume where we could mount it –</p><pre>volumeMounts:<br>- mountPath: /data<br>  name: storage</pre><p>Now that we have a volume, we can simply mount the persistent disk on it –</p><pre>volumes:<br>- name: storage<br>  gcePersistentDisk:<br>    pdName: data-index-disk<br>    fsType: ext4</pre><p>Now, whenever we deploy these configurations, we can reuse the previous index.</p><h3>Exposing Kubernetes to Cluster</h3><p>The HTTP and transport clients are enabled on port 9200 and 9300 respectively. They can be exposed to the rest of the cluster using the following service –</p><pre>apiVersion: v1<br>kind: Service<br>...<br>Spec:<br>  ...<br>  ports:<br>  - name: http<br>    port: 9200<br>    protocol: TCP<br>  - name: transport<br>    port: 9300<br>    protocol: TCP</pre><p>Once deployed, other deployments can access the cluster API from ports 9200 and 9300.</p><h3>Connecting loklak to Kubernetes</h3><p>To connect loklak to external Elasticsearch cluster, <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.0/transport-client.html">TransportClient</a> Java API is used. In order to enable these settings, we simply need to make some changes in <a href="https://github.com/loklak/loklak_server/blob/development/conf/config.properties#L161L169">configurations</a>.</p><p>Since we enable the service named “elasticsearch” in namespace “elasticsearch”, we can access the cluster at address elasticsearch.elasticsearch:9200 (web) and elasticsearch.elasticsearch:9300 (transport).</p><p>To confine these changes only to Kubernetes deployment, we can use sed command while building the image (in Dockerfile) –</p><pre>sed -i.bak &#39;s/^\(elasticsearch_transport.enabled\).*/\1=true/&#39; conf/config.properties &amp;&amp; \<br>sed -i.bak &#39;s/^\(elasticsearch_transport.addresses\).*/\1=elasticsearch.elasticsearch:9300/&#39; conf/config.properties &amp;&amp; \</pre><p>Now when we create the deployments in Kubernetes cluster, loklak auto connects to the external elasticsearch index and creates indices if needed.</p><h3>Verifying persistence of the Elasticsearch Index</h3><p>In order to see that the data persists, we can completely delete the deployment or even the cluster if we want. Later, when we recreate the deployment, we can see all the messages already present in the index.</p><pre>I  [2017-07-29 09:42:51,804][INFO ][node                     ] [Hellion] initializing ...<br> <br>...<br> <br>I  [2017-07-29 09:42:58,082][INFO ][gateway                  ] [Hellion] <strong>recovered [8] indices into cluster_state</strong></pre><p>In the last line from the logs, we can see that indices already present on the disk were recovered. Now if we head to the public IP assigned to the cluster, we can see that the message count is restored.</p><h3>Conclusion</h3><p>In this blog post, I discussed how we utilised the Kubernetes setup to shift loklak to Google Cloud Platform. The deployment is active and can be accessed from the link provided under <a href="https://github.com/loklak/loklak_server/wiki">wiki</a> section of <a href="https://github.com/loklak/loklak_server">loklak/loklak_server</a> repo.</p><p>I introduced these changes in pull request <a href="https://github.com/loklak/loklak_server/pull/1349">loklak/loklak_server#1349</a> with the help of <a href="https://github.com/niranjan94">@niranjan94</a>, <a href="https://github.com/uday96">@uday96</a> and <a href="https://github.com/chiragw15">@chiragw15</a>.</p><h3>Resources</h3><ul><li>Docker Tutorial Series : Writing a Dockerfile — <a href="https://rominirani.com/docker-tutorial-series-writing-a-dockerfile-ce5746617cd">https://rominirani.com/docker-tutorial-series-writing-a-dockerfile-ce5746617cd</a>.</li><li>Introduction to YAML: Creating a Kubernetes deployment — <a href="https://www.mirantis.com/blog/introduction-to-yaml-creating-a-kubernetes-deployment/">https://www.mirantis.com/blog/introduction-to-yaml-creating-a-kubernetes-deployment/</a>.</li><li>Configure Liveness and Readiness Probes — <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/">https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/</a>.</li><li>Setting up HTTP Load Balancing with Ingress — <a href="https://cloud.google.com/container-engine/docs/tutorials/http-balancer">https://cloud.google.com/container-engine/docs/tutorials/http-balancer</a>.</li><li>Persistent Volumes in Kubernetes — <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/">https://kubernetes.io/docs/concepts/storage/persistent-volumes/</a>.</li><li>Rolling updates with Kubernetes: Replication Controllers vs Deployments — <a href="https://ryaneschinger.com/blog/rolling-updates-kubernetes-replication-controllers-vs-deployments/">https://ryaneschinger.com/blog/rolling-updates-kubernetes-replication-controllers-vs-deployments/</a>.</li><li>DNS Pods and Services — <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/">https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/</a>.</li></ul><p><em>Originally published at </em><a href="https://blog.fossasia.org/deploying-loklak-server-on-kubernetes-with-external-elasticsearch/"><em>blog.fossasia.org</em></a><em> on August 7, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4839b6e406" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>