<?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 Paweł Dawczak on Medium]]></title>
        <description><![CDATA[Stories by Paweł Dawczak on Medium]]></description>
        <link>https://medium.com/@pawel_dawczak?source=rss-9c38567654f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*juGCC1mWC_LpUf95dKM0bg.jpeg</url>
            <title>Stories by Paweł Dawczak on Medium</title>
            <link>https://medium.com/@pawel_dawczak?source=rss-9c38567654f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:17:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pawel_dawczak/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[Elixir Distribution, ELI5]]></title>
            <link>https://medium.com/@pawel_dawczak/elixir-distribution-eli5-309193004119?source=rss-9c38567654f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/309193004119</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[mesh-networks]]></category>
            <category><![CDATA[beam]]></category>
            <dc:creator><![CDATA[Paweł Dawczak]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 09:54:02 GMT</pubDate>
            <atom:updated>2022-11-25T07:57:14.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IALSjDe2i9ZlDIhvBfPWEw.png" /></figure><p>Maybe you heard about Elixir or Erlang being great technologies for Distributed Programming… Maybe you even tried connecting a few Nodes into a Cluster on your laptop… But do you know the key pieces that allow the magic that happen behind the scenes?</p><p>Interested? Let’s dive in!</p><h3>Let’s form cluster locally</h3><p>To start a new Node, we need to give it a name — that will make such a Node to be started in a “Distributed Node”.</p><p>To name a Node, there are two strategies. Let’s check the first one — with “Short Name”.</p><p>Let’s start three instances with this strategy — in three separate terminals, issue the following commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7acd49e9eaf4adc9023ac43710cd0984/href">https://medium.com/media/7acd49e9eaf4adc9023ac43710cd0984/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXQV-R27t3AtjDQbE8k_sw.png" /><figcaption>Start three Nodes</figcaption></figure><p>The first thing you’ll notice is the fact the “standard” prompt changed from</p><pre>iex(1)&gt;</pre><p>to a one similar to:</p><pre>iex(foo@pop-os)1&gt;</pre><p>It indicates this Node is started in a Distributed mode, and what its name is.</p><p>Let’s check registered Nodes:</p><pre>iex(foo@pop-os)1&gt; Node.list()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDo0l_wgkKZ1VQZdRntK6g.png" /><figcaption>List Nodes in the Cluster</figcaption></figure><p>Whoops! There are no Nodes listed! That’s not very exciting, is it?</p><p>There is first point to know about Distribution in Elixir/Erlang — there is no magic, nothing will happen out-of-the-box.</p><p>Ok, let’s try to form a cluster.</p><p>In the foo app, let’s issue the following:</p><pre>iex(foo@pop-os)2&gt; Node.ping(:&quot;bar@pop-os&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GU4EL_FLsf5CmB7pURvBkQ.png" /><figcaption>Let’s ping another Node</figcaption></figure><p>The result might not look great initially, but when we query the Nodes again:</p><pre>iex(foo@pop-os)3&gt; Node.list()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RY8sAk6O5JElvHMD1Q_law.png" /><figcaption>List the foo’s Nodes again</figcaption></figure><p>It actually lists the name of the other Node! Let’s quickly do the same on the other node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h9zcqgvw94lsAFF8fR72Gg.png" /><figcaption>List the bar’s Nodes</figcaption></figure><p>Oh! That looks more exciting now! Unfortunately, baz is still pretty lonely for now:</p><pre>iex(baz@pop-os)1&gt; Node.list()<br>[]</pre><p>Before we draw conclusions, let baz ping foo :</p><pre>iex(baz@pop-os)2&gt; Node.ping(:&quot;foo@pop-os&quot;)</pre><p>and let’s examine the list of known Nodes:</p><pre>iex(baz@pop-os)3&gt; Node.list()</pre><p>Can you guess what will it list? Probably! But the answer might actually be a bit different!</p><p>Let’s see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MygD6YaTA_czuJnbYTwgVg.png" /><figcaption>List baz’s known Nodes</figcaption></figure><p>Wait, what!? Let’s quickly check the others too!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwamxa0a3RhCZ7j55wrF9w.png" /><figcaption>Let’s check all the Nodes</figcaption></figure><p>Here is the second important point — when a new Node joins Cluster, it forms a Mesh — every Node in the cluster knows about all the other Nodes, even when only one Node was connected explicitly (eg. with ping).</p><h3>A quiet hero</h3><p>Ok, that looks pretty cool so far!</p><p>We’ve got a Mesh Cluster of Elixir Nodes where we connected all the instances, but in fact, there was something else happening in the background, to help…</p><p>In another terminal, let’s issue:</p><pre>epmd -names</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FB3_fydxJ_9QzaGObgbxow.png" /><figcaption>Query epmd</figcaption></figure><p>When starting a first Node in a Distributed mode, there was another process started alongside — epmd — <a href="https://www.erlang.org/doc/man/epmd.html">Erlang Port Mapper Daemon</a>.</p><p>It is a process that (by default) runs on port 4369 and lists all known Nodes (with their names) and it shows ports they have allocated.</p><h3>Getting serious</h3><p>That’s awesome progress, but running all the Nodes locally is not <em>really</em> Distribution, is it?</p><p>Let’s do something more advanced then.</p><p>I’ve got two laptops in my network. I’ll try to start Nodes on each one and connect them. For this, we will need to use another naming strategy — a “full name” or “fully qualified name”.</p><p>When assigning the Node’s name, it will need to consist of the location where it’s based, eg. IP address of the machine it runs on.</p><p>For example, one of my machine’s IP is 192.168.1.176 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUY0au9nG6WJfBn-0MtCJA.png" /><figcaption>IP Address of one computer</figcaption></figure><p>And the other ones is 192.168.1.153 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*scIrlcIzF-LUeTkjgGWnGA.png" /><figcaption>IP address of the other computer</figcaption></figure><p>Once we have this information, let’s try to connect the Nodes:</p><pre>&gt; iex --name foo@192.168.1.176</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuACfLIYcnRrm-7O12XtwQ.png" /><figcaption>Start foo on the first computer</figcaption></figure><p>And:</p><pre>&gt; iex --name bar@192.168.1.153</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yhgbztcxXHQufl6Pn6hLA.png" /><figcaption>Start bar on the other computer</figcaption></figure><p>And let’s try to connect them two:</p><pre>iex(bar@192.168.1.153)1&gt; Node.ping(:&quot;foo@192.168.1.176&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNBiQeyrJRCG43oUyGBVAg.png" /><figcaption>Connect Nodes — first attempt</figcaption></figure><p>pang ? That looks strange, let’s see connected Nodes:</p><pre>iex(bar@192.168.1.153)2&gt; Node.list()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8pm3KBU5E8g0xQCnQhemw.png" /><figcaption>List known Nodes</figcaption></figure><p>No Nodes? Oh, but the other Node seems to have logged something:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzTAa_3fK987LVliQvvUZQ.png" /><figcaption>A log message</figcaption></figure><p>Ok — this is interesting. It looks like there was an attempt from the other machine to connect, but it failed!</p><p>There is last point to land today — for the Nodes to connect, they need to share the same Cookie. The Cookie is a string and it’s not quite so much a security mechanism, it’s rather a way to prevent “accidentally” joining a Cluster in a Mesh.</p><p>Let’s try to start the Nodes again, but this time — let’s pass the Cookie explicitly:</p><pre>iex --name foo@192.168.1.176 --erl &quot;-setcookie for_fun&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNgye22gRpCa3fk_y-lycw.png" /><figcaption>Start a named Node with Cookie</figcaption></figure><p>And:</p><pre>iex --name bar@192.168.1.153 --erl &quot;-setcookie for_fun&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8N6EFZtButlBziUU9e0nZA.png" /><figcaption>Start another Node with the same Cookie</figcaption></figure><p>And let’s try to connect them again:</p><pre>iex(bar@192.168.1.153)1&gt; Node.ping(:&quot;foo@192.168.1.176&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlZZNC953bWkZkV3W2-3iA.png" /><figcaption>Connect Nodes — second attempt</figcaption></figure><p>This time we have pong answer, which looks much more promising! Let’s see know Nodes:</p><pre>iex(bar@192.168.1.153)2&gt; Node.list()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBbQF7EY4XABGTyE2blgLw.png" /><figcaption>List known foo’s Nodes</figcaption></figure><p>Awesome! And how about bar ?</p><pre>iex(foo@192.168.1.176)1&gt; Node.list()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2323Yvco8vmG2jwzCMPp0w.png" /><figcaption>Bar’s known Nodes</figcaption></figure><p>Amazing!</p><p>Lastly, let’s check each machine’s epmd registry.</p><p>foo first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLhVOnT4sk_bqf6-zwhuYQ.png" /><figcaption>epmd on foo</figcaption></figure><p>and bar :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iK5VCbC7kNulmm3XtJP6kQ.png" /><figcaption>epmd on bar</figcaption></figure><h3>Conclusion</h3><p>Elixir and Erlang are awesome technologies that allow forming Mesh Clusters of Nodes relatively easy, and there are a few things to remember:</p><ol><li>There are two strategies to start BEAM Node in a Distributed mode:<br>* With a “short name” (--sname option) that is sufficient to start Nodes on the same machine<br>* With a “fully qualified name” (--name option) that has to include the location of the Node, eg. the IP address of the machine it is hosted on</li><li>For the Nodes to connect, they have to share the same Cookie (via --erl &quot;-setcookie &lt;cookie&gt;&quot;)</li><li>When starting BEAM in a Distributed Node, additional process — EPMD- is started, which tracks the ports for each registered Node.<br>In fact, when the cross-machine communication is established, this is a very first attempt between Nodes — when one Node tries to connect to the other, it will check with EPMD first, and a random port, upon successful connection will be allocated.<br>In fact, port management will be very important when deploying applications eg. in AWS’ environment, so we will need to make sure proper ports are configured, otherwise — the Nodes won’t be able to connect.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=309193004119" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Elixir App in AWS, PT2]]></title>
            <link>https://medium.com/@pawel_dawczak/distributed-elixir-app-in-aws-pt2-5bd29aea922a?source=rss-9c38567654f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd29aea922a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Paweł Dawczak]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 19:14:33 GMT</pubDate>
            <atom:updated>2020-07-08T08:58:59.505Z</atom:updated>
            <content:encoded><![CDATA[<h3>Distributed Elixir App in AWS, PT2 — Let’s compile the application</h3><p>We are on the second step in our series of posts:</p><ul><li><a href="https://medium.com/@pawel_dawczak/distributed-elixir-app-in-aws-pt1-lets-build-the-application-a5ce4ac62d26">Build the application</a></li><li>Make it compile locally, but make it run in EC2 (this post)</li><li>Create the whole infrastructure using Terraform (pending)</li></ul><p>Now, <a href="https://medium.com/@pawel_dawczak/distributed-elixir-app-in-aws-pt1-lets-build-the-application-a5ce4ac62d26">when we have our application ready</a>, it would be great to put it somewhere live. If you’re any familiar with the state of compiling Elixir (or any BEAM based language), it is nothing like Java, that you can compile your application in one environment and deploy it to a different one.</p><p>As unfortunate as it sounds, there are a few options — you can either download the source code to the machine where you’re going to run your application and compile it there or, another option is to compile it in Docker, so you can replicate the destination’s environment anywhere.</p><p>In this blog post, it’s the “Docker approach” I wanted to try…</p><h3>Amazon’s system on my computer?</h3><p>For the purpose of this App, I’ll use the default system available in AWS. In the <a href="https://hub.docker.com/_/amazonlinux">Docker hub</a>, there is an official image that can be used for building your containers!</p><p>Let’s use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a93a79d517cffe2f394d317e2abe5e0/href">https://medium.com/media/9a93a79d517cffe2f394d317e2abe5e0/href</a></iframe><p>Later, when we will be installing dependencies for Erlang and Elixir, they will rely on specific encoding configured, let’s provide it next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50d04b244478f92bf4fb9f7c3d3eb8d6/href">https://medium.com/media/50d04b244478f92bf4fb9f7c3d3eb8d6/href</a></iframe><p>Now we can start installing lower-level dependencies in the system that will be required for compiling our application. Let’s do the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b65b903e948cc4cfa0379808f3a3468/href">https://medium.com/media/1b65b903e948cc4cfa0379808f3a3468/href</a></iframe><p>This will update the system, install compilers and other tools that Erlang’s compiler will require. Additionally, as a matter of best practice — let’s clean all unnecessary artifacts and remove the cache.</p><p>At this point, we should have all low-level dependencies in place, so we can start installing and compiling languages we need.</p><p>First, let’s install Node which we will use to compile our assets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ace6fdf2bc82c12358aa800f8aa7f59f/href">https://medium.com/media/ace6fdf2bc82c12358aa800f8aa7f59f/href</a></iframe><p>Next, let’s install Erlang:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ef12b1ae5334bac7f10841f78856fb4/href">https://medium.com/media/3ef12b1ae5334bac7f10841f78856fb4/href</a></iframe><p>Finally, Elixir itself:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/613f8c3252546c23d7e9bf188b7931bd/href">https://medium.com/media/613f8c3252546c23d7e9bf188b7931bd/href</a></iframe><p>We’ve got nearly everything we need. Node, Erlang and Elixir, so next, let’s install build tools: hex and rebar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ecac59e1ef200aa3d2b39d877633fc1/href">https://medium.com/media/2ecac59e1ef200aa3d2b39d877633fc1/href</a></iframe><p>With this in place, let’s move the application’s sources to the container:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bf612600be040cfbb9a31f9299085d7/href">https://medium.com/media/6bf612600be040cfbb9a31f9299085d7/href</a></iframe><p>All the above will be only required as a “one-off” kind of activity. Compiling the Application will be a little bit more involved and I didn’t find any better way of expressing it than in a custom shell script.</p><p>Let’s make Dockerfile to move it in and execute as a default command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/814d0e10abc1c22825c194bfa8a59b0d/href">https://medium.com/media/814d0e10abc1c22825c194bfa8a59b0d/href</a></iframe><p>Now, let’s implement the shell script itself.</p><p>There will be a few exports we will need to configure as they will be read during compilation. First, let’s make sure the application will be compiled in the prod environment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69585ba156a32a769aef4c697dda6ed1/href">https://medium.com/media/69585ba156a32a769aef4c697dda6ed1/href</a></iframe><p>Secondly, for the application we will need to install only the production-required dependencies, plus, the compilation for the production environment will require setting SECRET_KEY_BASE, for security purposes.</p><p>Normally, Phoenix has a mix command that will generate one for us, but at this point, we didn’t install any dependencies yet! To avoid downloading them twice — once for the development environment, to generate SECRET_KEY_BASE and then again, to install production required only dependencies, we can actually generate SECRET_KEY_BASE ourselves:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99e8be2f7d1a624819952ae205864e84/href">https://medium.com/media/99e8be2f7d1a624819952ae205864e84/href</a></iframe><p>Perfect! With this in place, we can now download dependencies and compile them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42cb2a9bf2e1290759c71c834eee1dfb/href">https://medium.com/media/42cb2a9bf2e1290759c71c834eee1dfb/href</a></iframe><p>Next, we can compile our frontend assets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff05dff5ce2edb27846d8c99858982e8/href">https://medium.com/media/ff05dff5ce2edb27846d8c99858982e8/href</a></iframe><p>and generate manifests, so Phoenix knows how to identify generated artifacts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6713bdf58eb2c50d0877097eff6be6bd/href">https://medium.com/media/6713bdf58eb2c50d0877097eff6be6bd/href</a></iframe><p>Finally, we can compile the application itself:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c36dfa3d9c4954c11250eb7d1314cdee/href">https://medium.com/media/c36dfa3d9c4954c11250eb7d1314cdee/href</a></iframe><p>Now, when that’s ready, we can use Elixir’s built-in release tool to actually generate the application’s release. Let’s do it and put it temporarily in /artifact:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/705a1f6c1f4844130e833c519db07b45/href">https://medium.com/media/705a1f6c1f4844130e833c519db07b45/href</a></iframe><p>Because this command doesn’t compress it to one file, we will need to do it manually:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7eaa42efd421351bb3a67693321583d/href">https://medium.com/media/d7eaa42efd421351bb3a67693321583d/href</a></iframe><p>And finally, let’s move generated tar to a directory, we will mount into the container every time we will run Docker. On this occasion, to avoid potential conflicts in file names when we run the command multiple times, let’s rename the file in a way we will prepend the timestamp:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7eed68af46162e5f7ef67623f22c3e7/href">https://medium.com/media/e7eed68af46162e5f7ef67623f22c3e7/href</a></iframe><h3>The first release</h3><p>Now, with the Dockerfile in place, let’s give it a try. Let’s build the image first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/563a49819e37e31110c880ecfbc5b10d/href">https://medium.com/media/563a49819e37e31110c880ecfbc5b10d/href</a></iframe><p>This will take quite a considerable amount of time as it will download Erlang’s sources and compile it. There is not much we can do about it at this point. Once this is complete, let’s create a local directory we will later mount when running the image:</p><pre>mkdir built_release</pre><p>And finally, let’s use the image to generate a release for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a76243f65daf54c5658cae4825a38efe/href">https://medium.com/media/a76243f65daf54c5658cae4825a38efe/href</a></iframe><p>Here, I’ll let Docker mount my local directory, the directory it will use to output the generated tar file. After that completes, I can see, there certainly is a compiled and compressed release:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7c8fa3e04900ce4f045af94aaba9703/href">https://medium.com/media/d7c8fa3e04900ce4f045af94aaba9703/href</a></iframe><p>It wouldn’t make much sense to untar it on my computer and start the app, as it won&#39;t work — remember? We’ve compiled it for the AWS’ system architecture!</p><p>Let’s start a new EC2 instance and give the release a go!</p><h3>EC2 setup</h3><p>Firstly, in AWS, let’s go to the EC2 console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*co932dOQaVf8vCkJ1VGnUA.png" /><figcaption>EC2 Console 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WldXUtw46bk3XFVZZcAffw.png" /><figcaption>EC2 Console 2</figcaption></figure><p>Then, let’s choose Amazon Linux as a system for the instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeYsYuO5sQtfaTrEPM1VaA.png" /><figcaption>System selection</figcaption></figure><p>For the next few screens, let’s just use defaults:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgUiLWVcq1Xg7iP_u-9Lew.png" /><figcaption>Instance type selection</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_8oK_5ic5YuDGljz-D97Q.png" /><figcaption>Instance configuration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fX1yZLPtzFWFeSY_Fua1Sg.png" /><figcaption>Storage configuration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlILwtQfD5lv43m2x2uOFw.png" /><figcaption>Adding tags</figcaption></figure><p>Now, in the security groups’ screen, by default, there will be SSH port pre-configured already; as we’re going to host our web app here, let’s add one more configuration - by default, Phoenix’ web server will start on a port 4000, so let’s configure that one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gd1O-6khCvca-tePPT_mHQ.png" /><figcaption>Security Group config</figcaption></figure><p>Then, let’s confirm our selections in the summary screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5UeVHb2t6F78UrTv1fwlg.png" /><figcaption>Summary screen</figcaption></figure><p>Finally, we will be required to configure the access keys. In my case, I’ll re-use already created keys, but in your case, you might be prompted to create a new set of keys and download the file.</p><p>Let’s do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtV8iaSOVIKP0oxOnhrJlQ.png" /><figcaption>Key pair selection</figcaption></figure><p>After a while, the instance should be up and running. It will have IP address attached to it, so let’s take a note of it, as it will be important in a moment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CeF4fli-tmYKOHDzkmRgQ.png" /><figcaption>Ready instance</figcaption></figure><h3>But does it really work?</h3><p>Now, when the instance is ready, let’s upload the tarfile. Notice, when constructing command for scp, we will need to specify the format of the destination like: &lt;user&gt;@&lt;ip_address&gt;:&lt;path/to/upload&gt;.</p><p>User, in this case, will always be ec2-user and the ip_address is the one that has been allocated to our instance - check the previous screenshot.</p><p>Additionally, it is also important to specify -i flag, that points to the file with key-pair we have just downloaded. In my case, the file is located in the current directory and the file is named distfun_simple.pem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea9ecf3254faed5ef3fbd8c03049b96a/href">https://medium.com/media/ea9ecf3254faed5ef3fbd8c03049b96a/href</a></iframe><p>Then, let’s ssh into the instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2f1ed47c6ac232b5e3ce44f327d668d/href">https://medium.com/media/b2f1ed47c6ac232b5e3ce44f327d668d/href</a></iframe><p>untar the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c086917feb98e97b505fbbc72b9ea80a/href">https://medium.com/media/c086917feb98e97b505fbbc72b9ea80a/href</a></iframe><p>and let’s start the application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7259a57718fac1ba5c6abff695c1acf1/href">https://medium.com/media/7259a57718fac1ba5c6abff695c1acf1/href</a></iframe><p>If there were no errors, we should be able to visit the page.</p><p>For this, we can use another property allocated to our instance, the Public DNS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQPp3xEK6_JK7jANw2UIsA.png" /><figcaption>Allocated Public DNS</figcaption></figure><p>Let’s use is in the browser, and remember — the server is started using port 4000, so we need to specify it in the URL:</p><p><a href="http://ec2-54-219-109-17.us-west-1.compute.amazonaws.com:4000/">http://ec2-54-219-109-17.us-west-1.compute.amazonaws.com:4000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TlA_fUFPpjJolda--0as5w.png" /><figcaption>A static list of nodes in the cluster</figcaption></figure><p>And we can see it is live!</p><p>Let’s try to visit the live-view page:</p><p><a href="http://ec2-54-219-109-17.us-west-1.compute.amazonaws.com:4000/nodes_live">http://ec2-54-219-109-17.us-west-1.compute.amazonaws.com:4000/nodes_live</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bHXy_Z-3wUMpMqA4xoeOw.png" /><figcaption>A LiveView page listing nodes in the cluster</figcaption></figure><p>And it seems to be loading fine initially, but the spinner is constantly displayed and the reload of the page seems to be happening!</p><p>If we take a look at the console where we’re running the app, we can see the following error:</p><pre>[error] Could not check origin for Phoenix.Socket transport.</pre><pre>Origin of the request: <a href="http://ec2-54-219-109-17.us-west-1.compute.amazonaws.com:4000/">http://ec2-54-219-109-17.us-west-1.compute.amazonaws.com:4000</a></pre><pre>This happens when you are attempting a socket connection to<br>a different host than the one configured in your config/<br>files. For example, in development the host is configured<br>to &quot;localhost&quot; but you may be trying to access it from<br>&quot;127.0.0.1&quot;. To fix this issue, you may either:</pre><pre>  1. update [url: [host: ...]] to your actual host in the<br>     config file for your current environment (recommended)</pre><pre>  2. pass the :check_origin option when configuring your<br>     endpoint or when configuring the transport in your<br>     UserSocket module, explicitly outlining which origins<br>     are allowed:</pre><pre>        check_origin: [&quot;https://example.com&quot;,<br>                       &quot;//another.com:888&quot;, &quot;//other.com&quot;]</pre><p>Hmm… let’s try to follow this suggestion to update our config file and point the host to the value assigned in AWS console:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/311cd6fd6e0d7d0daf8b71f110f6123f/href">https://medium.com/media/311cd6fd6e0d7d0daf8b71f110f6123f/href</a></iframe><p>Next, let’s generate a new release and deploy it with the following commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/563a49819e37e31110c880ecfbc5b10d/href">https://medium.com/media/563a49819e37e31110c880ecfbc5b10d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a76243f65daf54c5658cae4825a38efe/href">https://medium.com/media/a76243f65daf54c5658cae4825a38efe/href</a></iframe><p>Pro-tip — you can make it a one-line command by chaining the commands with &amp;&amp;:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acf6bfb33def46db0c27b537c7622642/href">https://medium.com/media/acf6bfb33def46db0c27b537c7622642/href</a></iframe><p>You will notice, this time build is much faster, as Docker doesn’t have to go through all the steps of downloading and compiling Erlang and Elixir - they are cached! It does, however, load our source files in, and in the process of run, it generates a new release with updated code.</p><p>Let’s upload it next — notice, there are two compressed files here, as we have generated the release twice! Now you can see how convenient it was to make Docker prepend the timestamp to the generated tar file, so they don’t conflict with each other:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32b71ff34a9ce0b2401f3d9f505c8da2/href">https://medium.com/media/32b71ff34a9ce0b2401f3d9f505c8da2/href</a></iframe><p>and back in the EC2 instance, if you still have your app running, just stop it with CTRL+C CTRL+C, untar the new release and start it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad25c98c7626ac1075a5153e0e575cef/href">https://medium.com/media/ad25c98c7626ac1075a5153e0e575cef/href</a></iframe><p>This time both our URLs work, and there is no error, nor spinner displayed in the live-view page, which means — our WebSocket connection has been established successfully!</p><p>That was a very productive day! Let’s finish this exercise here today and don’t forget to terminate the instance to avoid incurring any costs if you don’t need the instance anymore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntOAuhdKn7j2m7n93mIRrg.png" /><figcaption>Terminating the instance</figcaption></figure><h3>Summary and Key Takeaways</h3><p>That was a very productive session! With Docker, we’ve got really easily reproducible environment for compiling the Elixir app and generating the release we can safely deploy to AWS’ instance. In this exercise, I’ve used image of Amazon’s system, but in fact — you can build your own image off any image you like and adjust the rest of Dockerfile accordingly!</p><p>At this point, we have an app ready and a way for compiling it which we have already tested in a production-like environment, and there are a few gotchas worth highlighting:</p><ul><li>When fetching Elixir’s app dependencies for prod environment, the scripts assume the existence of SECRET_KEY_BASE. Phoenix offers a script to <a href="https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Secret.html">generate a secret</a>, but to avoid downloading dependencies twice, I used a shell script to generate it</li><li>When creating an EC2 instance, we need to make sure the required ports are configured properly, otherwise, it would be impossible to connect to the web app. In our case, we needed to configure to traffic for port 4000</li><li>Finally, when allowing the WebSocket connections for LiveView, it was important to provide proper configuration for our app, so the connection could be validated and properly established</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd29aea922a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Elixir App in AWS, PT1 — Let’s build the application]]></title>
            <link>https://medium.com/@pawel_dawczak/distributed-elixir-app-in-aws-pt1-lets-build-the-application-a5ce4ac62d26?source=rss-9c38567654f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5ce4ac62d26</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[liveview]]></category>
            <dc:creator><![CDATA[Paweł Dawczak]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 05:31:25 GMT</pubDate>
            <atom:updated>2020-07-08T08:58:43.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>Distributed Elixir App in AWS, PT1 — Let’s build the application</h3><p>Let’s build a distributed application. A very simple one, but the one that will show us some interesting building blocks and demystify some concepts.</p><p>This very simple application that will track automatically nodes in the cluster, will allow dynamically displaying the list of nodes over web sockets. It will be deployed to multiple EC2 instances in AWS and compiled locally, using Docker.</p><p>This will be a series of posts:</p><ul><li>Build the application (this post)</li><li><a href="https://medium.com/@pawel_dawczak/distributed-elixir-app-in-aws-pt2-5bd29aea922a">Make it compile locally, but make it run in EC2</a></li><li>Create the whole infrastructure using Terraform (pending)</li></ul><p>It’s not a comprehensive guide and will not be applicable in all use-cases, it will not meet all the best security standards, as this guide is intended to show some interesting concepts and give a starting point for your development.</p><p>Interested? Let’s start!</p><h3>Start a new project</h3><p>It will be a very simple app and we will not need DB access, but we will use the new Phoenix’ generator to provide the initial code for LiveView, which we will use for real-time capabilities:</p><pre>&gt; mix phx.new distfun_simple --no-ecto --live</pre><p>First, let’s implement a GenServer, that will track all the nodes connected in the cluster. Let’s build the initial functionality that will allow us starting a new process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/233df6c04e3623d51a5c5c3292ac7c07/href">https://medium.com/media/233df6c04e3623d51a5c5c3292ac7c07/href</a></iframe><p>Fairly standard implementation for GenServer. Important is the point 1.. It will register the process to monitor the nodes that will join and leave the cluster. We will get back to what it provides a bit later…</p><p>Next, let’s add a very basic public interface that will allow returning the list of all nodes in the cluster the process is aware of:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c5d97d9fdd426c2af2f6eacb3e942bb/href">https://medium.com/media/3c5d97d9fdd426c2af2f6eacb3e942bb/href</a></iframe><p>It will return the list of all nodes, including the node the application is running but will make it a very first entry in the list. It will be useful later, for demonstration purposes, when we will hide all the apps behind a load balancer.</p><p>Next, let’s handle the information the process will receive when a new node will join the cluster (it will be of a form of {:nodeup, node}) or leave the cluster (it will look like {:nodedown, node}). Both of them will be handled by handle_info callback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3939208d6dfa91461bb59b17d337ed22/href">https://medium.com/media/3939208d6dfa91461bb59b17d337ed22/href</a></iframe><p>It’s only a few lines of code, but it already starts to feel quite messy, so let’s take this opportunity to refactor it a bit. First, let’s introduce a submodule to store our state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72e112e7a8bf6c1bbbdc3e23d801e996/href">https://medium.com/media/72e112e7a8bf6c1bbbdc3e23d801e996/href</a></iframe><p>Next, let’s use the new functions in our GenServer callbacks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffbabbc368dc8c54d40669fd67f0dde4/href">https://medium.com/media/ffbabbc368dc8c54d40669fd67f0dde4/href</a></iframe><p>Great! Looks much cleaner!</p><p>Next, let’s make sure the ClusterManager will start alongside the app. In order to do so, we need to modify Application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c590367030d1bc1d7283ef7e95156fd4/href">https://medium.com/media/c590367030d1bc1d7283ef7e95156fd4/href</a></iframe><p>We are nearly ready to test it in action, but there is one more change we need to add. At the moment, Phoenix web server will start on port 4000, but we will want to start more nodes, so to avoid port conflicts, let’s make the port to be configurable.</p><p>Let’s open configuration and change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d51d5d374fb7e18ed346cf27bfa521d7/href">https://medium.com/media/d51d5d374fb7e18ed346cf27bfa521d7/href</a></iframe><p>And let’s see it in action. First, let’s start two instances of the app. In two separate terminals, run the following:</p><pre>&gt; PORT=4000 iex --sname a -S mix</pre><pre>&gt; PORT=4001 iex --sname b -S mix</pre><p>And now, from one of the instances, let’s try to connect to the other one. Here, I’ll execute the following from my b node:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b7c6ca1a2014eda27c85cbfd3ff52b7/href">https://medium.com/media/0b7c6ca1a2014eda27c85cbfd3ff52b7/href</a></iframe><p>Looks promising! Let’s test the following in the other:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96a1793f2e8b2ebf78deb96623d64c4c/href">https://medium.com/media/96a1793f2e8b2ebf78deb96623d64c4c/href</a></iframe><p>Great! It works!</p><p>In the next step, let’s open our ClusterManager for other processes to listen for changes in the registered nodes’ lists.</p><p>Firstly, let’s add the changes to our State:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/630a84a88044f827e59e7197a7cecf10/href">https://medium.com/media/630a84a88044f827e59e7197a7cecf10/href</a></iframe><p>Next, let’s update the interface to allow registering processes. Upon registering, we would like to give access to a copy of the already stored nodes. We can do it like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b02b8c1fd4c7d778fb3163922d50bc7d/href">https://medium.com/media/b02b8c1fd4c7d778fb3163922d50bc7d/href</a></iframe><p>Our ClusterManager will store a list of all listeners interested to be notified about changes in the list of nodes in the cluster; but processes can finish their work, exit, or even die and will be unable to de-register themselves. This is why we set the monitor, so as soon as the listener goes down, our ClusterManager will receive a new message indicating this fact.</p><p>When a process monitors another process, and that process “goes down”, the message will be delivered to a monitoring process and will be a tuple of the following format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f48c449e8cb5072f06a4e86b1947af95/href">https://medium.com/media/f48c449e8cb5072f06a4e86b1947af95/href</a></iframe><p>In case of a GenServer, this message will be handled by handle_info callback. All we have to do is to add that function that will handle the message, let’s do it next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5341af43e4dbc0d78063071abfc5adc/href">https://medium.com/media/d5341af43e4dbc0d78063071abfc5adc/href</a></iframe><p>Great! Now, when we have the infrastructure in place, let’s add functionality to notifylisteners.</p><p>First, let’s add a function that will broadcast the updated list of nodes to all listeners:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/672c7033a2b1f2bf861379081ad74018/href">https://medium.com/media/672c7033a2b1f2bf861379081ad74018/href</a></iframe><p>It will accept GenServer’s internal state, and will return it. It will allow us to compose it nicely with the rest of the code using pipe operator. Let’s do it next - in the functions that are invoked every time a node joins the cluster or leaves it, let’s change the code to look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfae4210e78a78b47f5c0eac0d1023ee/href">https://medium.com/media/bfae4210e78a78b47f5c0eac0d1023ee/href</a></iframe><p>With that in place, let’s give it a try and see how it works — shall we?</p><p>Let’s start two iex sessions again:</p><pre>&gt; PORT=4000 iex --sname a -S mix</pre><pre>&gt; PORT=4001 iex --sname b -S mix</pre><p>In shell a, let’s use this new function to get a list of nodes and subscribe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82109fc303ff1d6feb63f516d19c8ecf/href">https://medium.com/media/82109fc303ff1d6feb63f516d19c8ecf/href</a></iframe><p>That’s correct, for now, we have two instances running separately and the next thing to do is to connect them. Let’s do the following in session b:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/798fd59c860eb0928e07dc6e15f1aba8/href">https://medium.com/media/798fd59c860eb0928e07dc6e15f1aba8/href</a></iframe><p>and back in session a, as it’s the iex session’s process that’s subscribed for updates, we can use flush() to see all the messages in its mailbox. Let’s try it next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99e0ec5783acd308c3addf825b329839/href">https://medium.com/media/99e0ec5783acd308c3addf825b329839/href</a></iframe><p>Perfect! It did receive a new message with the updated list of nodes! Next, let’s kill the session b, that is connected to the cluster, and see what happens! In the session b, hit ctrl-c + ctrl-c, and again in session a:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4497a3cb63a369c3b9850692978cafb8/href">https://medium.com/media/4497a3cb63a369c3b9850692978cafb8/href</a></iframe><p>It works!</p><h3>Going Web</h3><p>Now, when we have lower-level components ready, let’s try to expose the information through a web interface.</p><p>The way we generated the app, it already set up a new route for us, for live-view. Let’s change the URL where it will be mounted as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/201fe2a6b1fafdb2c92c6e81c1ac7e59/href">https://medium.com/media/201fe2a6b1fafdb2c92c6e81c1ac7e59/href</a></iframe><p>Next, let’s update the PageLive. Let’s make mount to look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/569af45e5826e925f3560e4bf14c6fb0/href">https://medium.com/media/569af45e5826e925f3560e4bf14c6fb0/href</a></iframe><p>As mount will be invoked twice - first time, when the user “visits” the page, it will perform “standard” HTTP call. This will return a “static” web page, and for this purpose, it will be just enough, to obtain a list of currently registered nodes: get_all_nodes().</p><p>However, after this “static” page is loaded, and JavaScript will initiate the Web socket connection, it will invoke mount again! But this time, it will be a new long-running process. connected? is a function, that helps to determine exactly that, and it’s that case, we want the WebSocket’s process to subscribe for the changes of the list of nodes.</p><p>Now, when the WebSocket’s process is subscribed for the changes, every time the change will occur, the process will be notified and will receive a message that will be handled by handle_info callback. Let’s implement it next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a9f068bdff466b0b1ba225710e11bb5/href">https://medium.com/media/8a9f068bdff466b0b1ba225710e11bb5/href</a></iframe><p>All it will do is to receive the new list of nodes and assign it to the socket. So last piece of work we need is to provide a template for displaying this list. Let’s add it next:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a5d86746522bb2840a461aeeba46154/href">https://medium.com/media/7a5d86746522bb2840a461aeeba46154/href</a></iframe><p>With the changes in place, let’s start two servers, visit them in separate browsers, navigate to the live-view page, and then, connect the nodes:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlCYxKtvLIHA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlCYxKtvLIHA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlCYxKtvLIHA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1149fb264e0f5f196bb65948b44b8e3/href">https://medium.com/media/f1149fb264e0f5f196bb65948b44b8e3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5ce4ac62d26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models for Ruby applications using PyCall]]></title>
            <link>https://medium.com/@pawel_dawczak/deploying-machine-learning-models-for-ruby-applications-using-pycall-1f77d5e26990?source=rss-9c38567654f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f77d5e26990</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Paweł Dawczak]]></dc:creator>
            <pubDate>Sat, 16 Mar 2019 21:10:07 GMT</pubDate>
            <atom:updated>2019-03-17T09:39:54.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zdmHd_0ivCyZcpYCtmNFA.png" /></figure><p><a href="https://medium.com/@pawel_dawczak/deploying-ml-models-for-ruby-applications-ff10a4bd4d1f">Previously</a>, we have trained a really simple model that was predicting income level between “&lt;= 50K” and “&gt; 50K”. It was a very simple classification problem for which we could use <a href="https://github.com/nok/sklearn-porter">Sklearn-porter</a> to generate Ruby code based on the trained model.</p><p>Unfortunately, Sklearn-porter doesn’t support any regression algorithms and only a limited set of classification algorithms. This limitation might be quickly reached when your needs outgrow its capability. What to do then?</p><p>This time I decided to pick a more complicated dataset for regression problem. To complicate the project a little bit more and make it look more like “real-life”, we implement <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">Sklearn’s pipeline</a> that will transform the data into the shape expected by an estimator.</p><h3>The application — “PalmSpringBnB”</h3><p>“PalmSpringsBnB” is a Machine Learning powered project that is able to suggest a list of prices (nightly price, weeknight price, weekend night price, weekly price and monthly price) based on information about the property.</p><p>The Machine Learning model has been trained on the <a href="https://www.kaggle.com/datafiniti/palm-springs-vacation-rentals">Palm Springs Vacation Rentals</a> dataset available on Kaggle.</p><p>This application uses <a href="https://github.com/mrkn/pycall.rb">PyCall</a> Ruby gem that allows calling Python code from Ruby.</p><p>Unfortunately, due to requirements of <em>how Python should be installed</em> to allow<br>accessing from Ruby, the way <a href="https://github.com/mrkn/pycall.rb/issues/62#issuecomment-377846006">it is installed on Heroku</a>, it wasn’t possible to<br>deploy it with default settings.</p><p>For this technical restriction, I recorded a short demo of how it works:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FggG5sFgQwDM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DggG5sFgQwDM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FggG5sFgQwDM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1f3906a74040294301b0cfc3e90ba72/href">https://medium.com/media/a1f3906a74040294301b0cfc3e90ba72/href</a></iframe><p>The whole source code of the application is available <a href="https://github.com/pdawczak/palm_springs_bnb">on Github</a> and whole research is available <a href="https://github.com/pdawczak/palm_springs_bnb/blob/master/ML/Palm_Springs_Pricing.ipynb">in this Jupyter Notebook</a>.</p><h3>Training the Model</h3><p>For training the model, the following features were selected (here it shows their correlation to the target ”price” we want to predict):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d11b0170ca126937f47b7828b90d6f39/href">https://medium.com/media/d11b0170ca126937f47b7828b90d6f39/href</a></iframe><p>The model’s accuracy achieved was as follows:</p><pre>| Model            | TRAIN Accuracy | TEST Accuracy |<br>|------------------+----------------+---------------|<br>| Decision Tree    |         80.04% |        78.39% |<br>| Random Forest    |         80.04% |        78.44% |<br>| LinearRegression |         35.23% |             - |<br>| Ridge            |         35.23% |             - |</pre><p>The table shows accuracy achieved both on Train and Test sets (there are no results for LinearRegression and Ridge models for test sets because they were not performing well on the Train set).</p><p>As expected — the accuracy is a bit lower on the Test sets (the data the model didn’t see before), but the difference to the accuracy achieved when training the model isn’t too big at that point so it doesn’t look like the models were prone to the overfitting.</p><p>We will productionise the RandomForest as it has a slightly better score.</p><h3>Deploy the Model</h3><p>Because PyCall allows calling Python code from Ruby like it was native to it, we can export the required pre-trained pipeline and estimator from Jupyter.</p><h4>What are pipeline and estimator?</h4><p>To allow Machine Learning models perform predictions, it is required the data is passed in a certain format. It’s not uncommon, that the shape of the data passed by the user will have to change before passing to the model to perform predictions.</p><p>Assuming the user created a new property with the following data:</p><pre>| numBed | numBathroom | numBedroom | numPeople | city         |<br>|--------+-------------+------------+-----------+--------------|<br>|      1 |           1 |          1 |         2 | Palm Springs |</pre><p>It will have to be transformed to something like:</p><pre>| 1 | 1 | 1 | 2 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |</pre><p>The rules of encoding are not important at the moment, because it’s the job of the pipeline that will know how to turn the first table in the second one.</p><p>It’s the last table that will be passed to the estimator (our Model) that will perform the predictions.</p><h4>Exporting pipeline and estimator</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f55e6df765a6cf001faca708fac60e6/href">https://medium.com/media/4f55e6df765a6cf001faca708fac60e6/href</a></iframe><h4>Ruby class that will use the Python exported code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98a9dc46a9cce63b1267d4b45009051a/href">https://medium.com/media/98a9dc46a9cce63b1267d4b45009051a/href</a></iframe><ol><li>Initialises the pipeline — it will load and instantiate the Python code</li><li>Initialises the estimator — this is similar initialisation for the estimator</li><li>Defines a method that will accept Property parameters specified by the user</li><li>Prepares 5 variants — enriches the data by appending one of five possible time periods</li><li>Prepares data to the format that will be possible to perform estimations</li><li>Performs predictions</li><li>Turns predictions into the format that will be easier to handle by the caller. The result of this will be a hash that will look like:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9063cf59ea55fb04029fd20aaa591d6/href">https://medium.com/media/a9063cf59ea55fb04029fd20aaa591d6/href</a></iframe><h4>Ruby code that will allow cleaner integration with the rest of the application</h4><p>The earlier code loads Python code and knows a lot of low-level details we don’t want to expose to the rest of the application, so let’s introduce another layer that will facilitate it — it will accept a Property, will extract the data and pass it for predictions, and assign results back to the Property:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a919d5329fd2efc9ebfc4955a38efdd/href">https://medium.com/media/8a919d5329fd2efc9ebfc4955a38efdd/href</a></iframe><h4>Initialising Ruby’s Ml::Estimator</h4><p>When checking how long it takes to load the Python code from the files, it is quite a slow process. It takes relatively a lot of time and it wouldn’t be a good idea to add this time to every prediction we perform.</p><p>To address this issue, we could benefit from the Rails’ initialisation phase.</p><p>Let’s add this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70aad20a9a6187a9b1aaf85238ce0560/href">https://medium.com/media/70aad20a9a6187a9b1aaf85238ce0560/href</a></iframe><p>This will ensure we will load the Python code only once when the Rails server (or any other command, eg. Rake task) is started. Without this additional overhead, all the further predictions will be rapid.</p><h3>Summary</h3><h4>Learnings</h4><p>PyCall allows great opportunity and much more flexibility for porting Python code to make it available to Ruby applications. As contrary to <a href="https://medium.com/@pawel_dawczak/deploying-ml-models-for-ruby-applications-ff10a4bd4d1f">Sklearn-porter</a>, it doesn’t have any limitations to what kind of Machine Learning algorithms it can support.</p><p>From my brief experience with PyCall I feel like: <em>If you can export the code from Jupyter, you will be able to use it in Ruby app</em> seems applicable. It is still important to have an understanding of how the particular model works internally to decide if PyCall will be a good choice.</p><p>In this example application, we exported a RandomForest — it is quite accurate, performant and the generated pickle code is not very big, but if you consider <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html">KNN</a>, that internally uses the <strong>whole dataset</strong> to make predictions, and this dataset’s size is in Gigabytes or Petabytes — could you afford such a server to host your Ruby/Rails application? Would you accept the time it would take to start such an application when it loads this whole dataset to memory?</p><h4>Further considerations</h4><p>PyCall was easy to use, but the initial set up might be a bit tricky. I have two distributions of Python installed on my machine — one by <a href="https://github.com/asdf-vm/asdf">.asdf</a> version manager, and <a href="https://www.anaconda.com/distribution/">Anaconda</a>. I had to set up my environment variables (like PYTHON) to point proper executables in order for it to work.</p><p>For this very reason, it wasn’t possible to deploy this simple app to Heroku with its default configuration. Maybe Docker would be a way to go forward?</p><p>Secondly, in this exercise I disregarded a lot of data from the original set to build model quickly and try porting the pipeline and estimator to use them in Ruby. Unfortunately, the model is not super accurate — around 78.44% accuracy achieved on the test set. I considered it good enough to productionise it and release, to find what are the technical problems with this approach, and most importantly — <em>if this would even be of interest for future users</em>, but it is not the model that could be considered final in the longer term.</p><p>Now, when it is (hypothetically) deployed and available to public use, we can get back to the research and continue improving it while monitoring if it is being used. How much does it matter if it has only 78.44% accuracy, but no one really wants to use it?</p><h4>Ideas for improving the Model</h4><p>The dataset has many more features which we didn’t consider during this exercise. We could spend more effort on extracting data from JSON columns (like property features, additional fees), or extracting some sentiment score from property description.</p><p>At the moment we have only one model that does all the predictions for all the available periods — maybe it would be a good idea to train separate models that would focus on the feature importance for a particular time periods?</p><h4>It was fun</h4><p>Analysing the data set was great fun, and this little exercise has proven, that it’s data cleaning and preparing, that is the most time-consuming part of building Machine Learning models (it might not sound exciting, but I actually enjoyed this part — I could understand the market a little bit better!).</p><p>Integrating ready model and seeing it being used from the application in such an automatic way that is completely transparent to the end user gives great satisfaction!</p><p>All of it learned and achieved in spare time was a little bit tiring. I guess I deserve some holidays in a nice place.</p><p>I’ve heard Palm Springs is quite nice :).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_TQauPdKtCM7Nr__U3saw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f77d5e26990" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models for Ruby applications with Sklearn-porter]]></title>
            <link>https://medium.com/@pawel_dawczak/deploying-ml-models-for-ruby-applications-ff10a4bd4d1f?source=rss-9c38567654f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff10a4bd4d1f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Paweł Dawczak]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 20:57:51 GMT</pubDate>
            <atom:updated>2019-03-17T07:43:42.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zdmHd_0ivCyZcpYCtmNFA.png" /></figure><h3>Deploying Machine Learning Models for Ruby applications using Sklearn-porter</h3><p>Data science and Machine Learning are hot topics recently in the IT industry, but I personally find it extremely exciting to see what computers can really do! Data wrangling and insights can provide a lot of fun (or is it only me that feels this way?), building Machine Learning models based on the data is amazing, but it’s only the moment you connect the two — this model and your application, that can apply the prediction to the user’s interaction, that is the most amazing experience of all!</p><p>I’ve already written about deploying a model to be used in the <a href="https://elixir-lang.org/">Elixir</a> application (<a href="https://medium.com/@pawel_dawczak/elixir-python-1-getting-started-165317f873fa">part 1</a> and <a href="https://medium.com/@pawel_dawczak/elixir-python-2-getting-excited-672ec35fa681">part 2</a>) and I was exploring what options are available to integrate the model with <a href="https://www.ruby-lang.org/en/">Ruby</a> application…</p><h3>Simple application — “How Much”</h3><p>“How Much” is a Machine Learning supported project for predicting the income level class. It distinguishes between classes of “&lt;= 50K” and “&gt; 50K” in US Dollars. The model is trained using <a href="https://archive.ics.uci.edu/ml/datasets/adult">Adults income dataset</a> and is integrated with really simple <a href="https://rubyonrails.org/">Rails</a> application using <a href="https://github.com/nok/sklearn-porter">Sklearn-porter</a> project, that generated native Ruby code.</p><p>The demo application is hosted on <a href="https://www.heroku.com/">Heroku</a> and is available <a href="https://how-much-ml.herokuapp.com/">here</a> (please be mindful if it takes a lot of time to load the first page — it’s hosted on free service).</p><p><em>Please note, the model’s accuracy is around 83% but is based on data gathered</em> <em>in 1994, so will not be very accurate for Today’s answers, nevertheless, it was</em> <em>great experience and fun project to build!</em></p><h3>Train the Model</h3><p>The full research, engineering and choosing features for the model, and then searching for the best model and parameters is described <a href="https://github.com/pdawczak/how_much/blob/master/ML/Adults_income.ipynb">here</a>, but the summary of findings are described below:</p><ol><li>Most correlated to the target variable features were:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ada3def89ed7965678cc4051870c84b/href">https://medium.com/media/9ada3def89ed7965678cc4051870c84b/href</a></iframe><p>2. These have been selected for training the models, which accuracy was:</p><pre>| Model         | Best accuracy |<br>|---------------|---------------|<br>| Decision Tree |         82.0% |<br>| Random Forest |         82.5% |<br>| KNN           |         82.1% |</pre><p>3. The best performing model was based on the RandomForest algorithm, and this one will be deployed.</p><h3>Deploy the Model</h3><p>Sklearn-Porter is able to generate native Ruby code, which will be used to deploy the trained model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b1583a2247e815a76c2b5e8b08c96f8/href">https://medium.com/media/9b1583a2247e815a76c2b5e8b08c96f8/href</a></iframe><p>This would generate a class with the following interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb741aa884cec998d822df431b85c70f/href">https://medium.com/media/cb741aa884cec998d822df431b85c70f/href</a></iframe><p>That could be used as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1a2b937e577ca01ae104378ec35ff65/href">https://medium.com/media/e1a2b937e577ca01ae104378ec35ff65/href</a></iframe><h3>Integrate with the rest of the application</h3><p>The features required for performing the prediction are expected to be passed in a specific order and the predicted value will be either 0 or 1 (for “&lt;= 50K” and “&gt; 50K” respectively), so for convenience - these can be wrapped in another method.</p><p>Given the prediction will be performed based on values obtained from the form submitted by the user, the helper method can look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63b1a3db909a809d64ff83a7abced552/href">https://medium.com/media/63b1a3db909a809d64ff83a7abced552/href</a></iframe><h3>Summary</h3><p>Even though the Machine Learning model has been trained on really old data (1994 was 25 years ago, when writing this post in 2019) and will most likely not be accurate for submissions of data reflecting Today’s circumstances — this still was great exercise and an amazing experience!</p><p>Now, when retrospectively considering where I spent most of my time when developing this simple app — I had to put more effort in building the frontend of the application, rather than coming up with the Machine Learning engine powering it…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*di2uq2tyx6GOFTPxCGaUeA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff10a4bd4d1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models for Elixir applications #2: Getting Excited]]></title>
            <link>https://medium.com/@pawel_dawczak/elixir-python-2-getting-excited-672ec35fa681?source=rss-9c38567654f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/672ec35fa681</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Paweł Dawczak]]></dc:creator>
            <pubDate>Sun, 09 Dec 2018 09:50:54 GMT</pubDate>
            <atom:updated>2019-03-19T08:05:34.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9ehu_8M0UK9SFzhbFlqfQ.png" /></figure><h3>If GenServer was OO</h3><p><a href="https://medium.com/@pawel_dawczak/elixir-python-1-getting-started-165317f873fa">Previously</a> we have set up the environment and managed to Elixir to talk to Python and we are in a good position to take the next step — let’s create new Python script — py_app/second.py; first, imports:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f7f52caa078640ee61d631e58ae5614/href">https://medium.com/media/7f7f52caa078640ee61d631e58ae5614/href</a></iframe><p>The process we will implement here, will have only one responsibility — receive a call with a string, and reply with the same string upper-cased.</p><p>Let’s implement the GenServer then:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d88b3e21ef0111219f2dad93dbc0100d/href">https://medium.com/media/d88b3e21ef0111219f2dad93dbc0100d/href</a></iframe><p>In the constructor we will do the wiring:</p><p>- Delegate to GenServer class with node_name<br>- Register what calls it will handle by specifying accepted_calls<br>- Register self under ”py_process” name</p><p>And let’s provide the implementation of the method — it will return the upper-cased string.</p><p>Lastly, let’s add main() method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/346c43a7503beb2e4165719479e6c039/href">https://medium.com/media/346c43a7503beb2e4165719479e6c039/href</a></iframe><p>Nothing super special here — we’re creating a new instance of PyGenServer. This will complete the setup of a node.</p><p>For convenience starting this node, let’s update the Makefile and add the<br>following entry:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc5bb6da51f0b144340d36ed9c6a1065/href">https://medium.com/media/cc5bb6da51f0b144340d36ed9c6a1065/href</a></iframe><p>Let’s give it a try:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7adf8c0272c7e9ddfbcfde2b259aafd/href">https://medium.com/media/f7adf8c0272c7e9ddfbcfde2b259aafd/href</a></iframe><p>All good so far!</p><h3>Elixir talks to Python and hears back</h3><p>Let’s fire up iex session:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/903f486f0618dfbd06fae4c51945b26b/href">https://medium.com/media/903f486f0618dfbd06fae4c51945b26b/href</a></iframe><p>and give the following a try:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ba3189cd9b3c9c71a9637e04b6397c7/href">https://medium.com/media/6ba3189cd9b3c9c71a9637e04b6397c7/href</a></iframe><p>OK, I know what you’re thinking — <em>yes, this is cool, but most certainly not exciting. What’s the deal?</em></p><p>Yes, I agree — this is a small step but in good direction…</p><p>Next, let’s try to make Python node a bit smarter…</p><h3>Python for Machine Learning</h3><p>Iris classification problem is a <em>Hello World</em> in Machine Learning world.</p><p>It contains data about flowers, alongside data associated with it. The problem is simple enough, to be able to build very first, simple classification model.</p><p>Let’s try to build such a model, and then, we will integrate it with Elixir.</p><p>First, let’s ensure you have pyex_env virtualenv enabled:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a4da0e77309dca396874352f4a1d47c/href">https://medium.com/media/9a4da0e77309dca396874352f4a1d47c/href</a></iframe><p>and install the following dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b883b3e38e5f3165eedb8eedf70c7872/href">https://medium.com/media/b883b3e38e5f3165eedb8eedf70c7872/href</a></iframe><p>Let’s download the dataset; for the exercise, I’ve used <a href="http://https//www.kaggle.com/uciml/iris/downloads/Iris.csv/2">this link</a> to obtain the CSV file.</p><p>Next, let’s start Jupyter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc7349628df2c2639dd85453defdeb52/href">https://medium.com/media/fc7349628df2c2639dd85453defdeb52/href</a></iframe><p>after the Jupyter’s server start properly, it will be opened in the web browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fr1TR9ekzWQvLLKUYcFUvg.png" /><figcaption>Main screen of Jupyter notebook</figcaption></figure><p>Let’s create a new notebook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*B7rnxQshbRhWKSK6r5zl1A.png" /><figcaption>Creating new Notebook</figcaption></figure><p>Here, let’s import pandas, load data, and for a sanity check — let’s output the<br>DataFrame for brief inspection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYnpYlr6Pd3iDe-_Raiy1w.png" /><figcaption>Loading data</figcaption></figure><p>Looks like we have accessed the data properly!</p><p>For convenience, let’s assign different “slices” of data for easier access.</p><p>By convention, the features that will form an input for our Machine Learning<br>model will be called X, and labels (values we want our model to predict) will be y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHK86idh0jrk4KgGDSd5hw.png" /><figcaption>Slicing data, step 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0X2ZWCkjCj7O9QeBdDIKA.png" /><figcaption>Slicing data, step 2</figcaption></figure><p>This looks good!</p><p>Now, when we have our variables set, we can start training our model — let’s<br>import first model, and fit the variables in. This is, when the model gets<br>trained:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVQ5sSpZC7Hia1qskPVszw.png" /><figcaption>Training the model</figcaption></figure><p>And now, this is the most exciting moment — did it learn anything form the data?<br>I’ve checked the CSV and picked two examples. I’ll let the model predict the<br>values for me:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUFcISxBE1IaSSj0qe6G-g.png" /><figcaption>Predicting</figcaption></figure><p>Yes! These labels indeed are associated with the data!</p><p>Let’s export the trained model from Juputer Notebook, so we can load it in our<br>Python node.</p><p>For this, we will use pickle format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1v4gPirMUSJx8sT9gd3dA.png" /><figcaption>Exporting trained model</figcaption></figure><h3>Loading the Model in Python</h3><p>Given the model has been serialised to pickle format, we are able to deserialise it in “pure” Python script.</p><p>Let’s do the following — first, import pickle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0e7a541c28fb10ffaaafdeeefd9f862/href">https://medium.com/media/e0e7a541c28fb10ffaaafdeeefd9f862/href</a></iframe><p>next, change the constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8938dee0d8c1f6ddc533c4d243660f86/href">https://medium.com/media/8938dee0d8c1f6ddc533c4d243660f86/href</a></iframe><ol><li>Our GenServer will handle call classify, which will use our trained model</li><li>We are loading the serialised model</li></ol><p>Next, let’s implement classify method</p><p><em>NOTE: Unfortunately, at the time of writing this post, </em><em>Pyrlang doesn’t implement full and proper serialisation and deserialisation of ETF (External Term Format), a format, that is used by Erlang to serialise data sent between nodes. To avoid this problem, I’ll serialise my data to JSON, but once issues in </em><em>Pyrlang are addressed, this could be reverted.</em></p><p>Firstly, let’s import json:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1be25193edd4b71349445155f99b51df/href">https://medium.com/media/1be25193edd4b71349445155f99b51df/href</a></iframe><p>next, the method itself:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4754136e4bde4006fb40772183ca30c/href">https://medium.com/media/d4754136e4bde4006fb40772183ca30c/href</a></iframe><ol><li>We’re implementing classify method, which will accept encoded_params_to_classify. These will be encoded in JSON</li><li>Decoding the parameters</li><li>The model is able to perform classification over a list of inputs, and as such, it returns a list of results. In this exercise we will classify only a single set of data, hence, will will access the record the first element from the result</li><li>We have to serialise the value to JSON before returning it</li></ol><h3>The Elixir side</h3><p>First, let’s create a fresh new Elixir project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45f81117e0271f6bb173216f69cd7523/href">https://medium.com/media/45f81117e0271f6bb173216f69cd7523/href</a></iframe><p>Next, add Jason dependency in mix.exs, we will use it for JSON encoding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6cefbcc4f7b2f5cf66df22869d198a0/href">https://medium.com/media/d6cefbcc4f7b2f5cf66df22869d198a0/href</a></iframe><p>and issue the command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a45dc8d2ae1c8fab019383e02751bb3/href">https://medium.com/media/5a45dc8d2ae1c8fab019383e02751bb3/href</a></iframe><p>to install the dependencies.</p><p>Next, let’s implement a function that will call corresponding process in Python node:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f5d1a94337c75fea9d1d9c2f47e60a4/href">https://medium.com/media/4f5d1a94337c75fea9d1d9c2f47e60a4/href</a></iframe><ol><li>This defines a reference to specific process in the :”py@127.0.0.1&quot; node</li><li>Transform a map of values to a list of parameters, and encode it to JSON</li><li>Send the call to the process with the params</li><li>Decode the JSON response</li></ol><h3>Trying it all together</h3><h4>Python side</h4><p>Given we have a corresponding entry in Makefile defined already, in one terminal window issue the command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db91f924cc7cb59c7aa934bb3dcba4bb/href">https://medium.com/media/db91f924cc7cb59c7aa934bb3dcba4bb/href</a></iframe><h4>Elixir side</h4><p>In another terminal window start Elixir node:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbb9990073a0c28da743ce1378c352ed/href">https://medium.com/media/cbb9990073a0c28da743ce1378c352ed/href</a></iframe><p>Once this completes, let’s issue the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89afdf1457f4c8a65cca35b3d89cd7a3/href">https://medium.com/media/89afdf1457f4c8a65cca35b3d89cd7a3/href</a></iframe><h3>What’s happened</h3><p>We managed to create a process in Python node, that was responding to calls. We have trained our first Machine Learning model, and finally, we managed to load the model into our Python code. This allowed our Elixir application to interact with it the way it didn’t know the node it sends messages to, and receives messages from, isn’t Elixir, or any other BEAM based language.</p><p>I don’t know about you, but for me this is extremely exciting — we were able to make our program to classify numeric values, all without a single if statement! Computer was able to learn the classification rules by providing it the data set only!</p><p><em>Today, it only predicts flowers, but tomorrow it might be the engine that will recommend your next car, or predict the price you’ll sell your house for!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=672ec35fa681" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Machine Learning Models for Elixir applications #1: Getting Started]]></title>
            <link>https://medium.com/@pawel_dawczak/elixir-python-1-getting-started-165317f873fa?source=rss-9c38567654f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/165317f873fa</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Paweł Dawczak]]></dc:creator>
            <pubDate>Sun, 02 Dec 2018 10:17:19 GMT</pubDate>
            <atom:updated>2019-03-19T08:06:15.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9ehu_8M0UK9SFzhbFlqfQ.png" /></figure><p>You already know how to build <em>scalable</em> and <em>fault tolerant</em> systems with Elixir, but have you thought about making them <em>smarter</em>? Machine Learning is this exciting area in IT we hear about great successes, and this builds curiosity to explore what it can do. Unfortunately, this area is dominated by Python and R, the technologies, that are foreign to BEAM based languages…</p><p>I’ve raised this question — would that be possible to train the Machine Learning models and still, make them available to Elixir programs in a way it would feel more native to the programs you implement?</p><p>There are a few ways of deploying Machine Learning models, and here, I’ll spend some time trying to make them work with the Elixir as it was part of Elixir program itself.</p><p>Finally, enabling the “native BEAM feel” to parts of Python program, will allow designing around the boundaries of the system using tools we already know and use — monitoring and linking the precesses and nodes are powerful, and serve great when we want to build highly available systems.</p><p>Join me in this exciting journey. I hope you’ll have as much fun as I had experimenting with this approach.</p><h3>Project’s setup</h3><h4>Preparing the environment</h4><p>We will need to install some Python libraries, so it is advised to create a dedicated Python’s environment, so the dependencies don’t get in conflicts with each other.</p><p>One of the tools used in Python world is virtualenv.</p><p>Let’s give it a go:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4584b64c723838eecf80980d208b2be4/href">https://medium.com/media/4584b64c723838eecf80980d208b2be4/href</a></iframe><p>and activate it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fe6d4d637e8f7187e74c60e60bf6ce5/href">https://medium.com/media/0fe6d4d637e8f7187e74c60e60bf6ce5/href</a></iframe><h4>Python dependencies</h4><p>Clone the Pyrlang repository:</p><pre>$ git clone <a href="/service/mailto:git@github.com">git@github.com</a>:Pyrlang/Pyrlang.git</pre><p>There are additional requirements needed for Pyrlang to work, and it provides a convenience script to install them.</p><p>Let’s invoke it:</p><pre>$ pip3 install -r Pyrlang/requirements.txt</pre><p>This completes the local setup and we are able to go to the next step and build a small app in Python.</p><h3>First Python app</h3><p>Firstly — required imports:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b997da262fbfc969bb15844663e88e94/href">https://medium.com/media/b997da262fbfc969bb15844663e88e94/href</a></iframe><p>Next, the body of the app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf72a20535a0fa6f99c049e8e52c68f1/href">https://medium.com/media/cf72a20535a0fa6f99c049e8e52c68f1/href</a></iframe><p>At the time of writing, Pyrlang allows specifying only a full name of a node.</p><p>The code above:</p><pre>Node(node_name=”py@127.0.0.1&quot;, cookie=”PYEX”, engine=eng)</pre><p>would be an equivalent of starting iex like:</p><pre>$ iex — name “py@127.0.0.1” — cookie “PYEX”</pre><p>and:</p><pre>node.send(sender=pid,<br>          receiver=(Atom(“ex@127.0.0.1”), Atom(“iex”)),<br>          message=Atom(“Hello from Python!”))</pre><p>would be an equivalent of Elixir’s code:</p><pre>send({:iex, :”ex@127.0.0.1&quot;}, :”Hello from Python!”)</pre><p>Let’s finish Python’s script with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0501dca4c7abe3b6d8b5849434043b7/href">https://medium.com/media/b0501dca4c7abe3b6d8b5849434043b7/href</a></iframe><p>This construct will invoke main() method automatically when executing this<br>Python script.</p><h3>Starting Elixir node</h3><p>The above code assumes a node named ex@127.0.0.1 that will be using cookie PYEX, and a process within this node named :iex.</p><p>Let’s set up such a node:</p><pre>$ iex — name ex@127.0.0.1 — cookie PYEX</pre><p>and register the process:</p><pre>iex(ex@127.0.0.1)1&gt; Process.register(self(), :iex)<br>true<br></pre><h3>Starting Python node</h3><p>Due to the fact we’ve checked out Pyrlang’s source code, Python will be unable to find the code, and as such, we have to help it a little bit specifying thePYTHONPATH; additionally, for easier debugging, we will enable more granular logging.</p><p>The full command would be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12ed1c7a556346aeb42a829cca902408/href">https://medium.com/media/12ed1c7a556346aeb42a829cca902408/href</a></iframe><p>This is quite verbose, and difficult to remember. Let’s add Makefile that will handle this for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37b1c667b2cf070c50c03bff54908eac/href">https://medium.com/media/37b1c667b2cf070c50c03bff54908eac/href</a></iframe><p>and invoke it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f44e0a02434140ae43414e8024f47167/href">https://medium.com/media/f44e0a02434140ae43414e8024f47167/href</a></iframe><p>There is a lot of logs generated, but it doesn’t look very impressive, so let’s<br>check a couple of things…</p><h3>What’s happened</h3><p>Firstly, in a separate shell, let’s check registered nodes in epmd:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c56812cb3b9bbc0c624e027cfcf7708/href">https://medium.com/media/5c56812cb3b9bbc0c624e027cfcf7708/href</a></iframe><p>We can see that there are both nodes — ex node we started first, and py<br>shortly after. Next, let’s check back our ex node. If everything went well, we should have a message from py node.</p><pre>iex(ex@127.0.0.1)2&gt; flush()<br>:”Hello from Python!”<br>:ok</pre><p>And the message indeed is here!</p><p>Unfortunately, out of the box, Pyrlang doesn’t implement whole functionality, and this won’t work:</p><pre>iex(ex@127.0.0.1)3&gt; Node.ping(:”py@127.0.0.1&quot;)<br>:pang</pre><p>However, if we monitor the node:</p><pre>iex(ex@127.0.0.1)4&gt; Node.monitor(:”py@127.0.0.1&quot;, true)<br>true</pre><p>and once we kill Python’s node (hit CTRL-c), we will be able to see this:</p><pre>iex(ex@127.0.0.1)5&gt; flush()<br>{:nodedown, :”py@127.0.0.1&quot;}<br>:ok</pre><p>Perfect — this should be just enough for our future needs.</p><p>The code is available <a href="https://github.com/pdawczak/PyEx_Project">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165317f873fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir’s “|” operator]]></title>
            <link>https://medium.com/@pawel_dawczak/elixirs-operator-c86158826205?source=rss-9c38567654f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c86158826205</guid>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Paweł Dawczak]]></dc:creator>
            <pubDate>Thu, 16 Jun 2016 11:42:58 GMT</pubDate>
            <atom:updated>2016-06-16T11:42:58.291Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I’ve seen the question on one of <a href="https://linkedin.com/">LinkedIn</a> groups asking about explanation for <em>vertical bar operator</em>, so I decided to write a post about it.</p><p>If you have <em>any</em> experience with <a href="http://elixir-lang.org/">Elixir</a>, you’re probably aware that you can create lists:</p><pre>list = [1, 2, 3]</pre><p>Pretty straightforward! However, this is just <em>simpler</em> notation of something like:</p><pre>iex&gt; [1 | [2 | [3 | []]]]<br>[1, 2, 3]</pre><p>Oh wow! This looks strange! But this is just an evidence of what list’s elements really are — basically, they are recursive structures of (<strong>head</strong>, <strong>tail</strong>) pairs.</p><p>To see if this is true, lets use <a href="http://elixir-lang.org/docs/stable/elixir/Kernel.html#hd/1"><strong>hd/1</strong></a>, to <em>read</em> the head of the list:</p><pre>hd(list)<br># =&gt; 1</pre><p>So far — looks correct. How about <em>reading</em> the <strong>tail</strong> with <a href="http://elixir-lang.org/docs/stable/elixir/Kernel.html#tl/1"><strong>tl/1</strong></a>?</p><pre>tl(list)<br># =&gt; [2, 3]</pre><p>Something interesting happened here — even if I <strong>hd/1</strong> earlier from the <strong>list</strong>, the <strong>list</strong> itself didn’t change (because the data in elixir is immutable), this is why I was able to <strong>tl/1</strong> from the same list and receive <em>two-element list</em>.</p><p>Usually this is not the way you interact with lists. More often what you want to do, is to <em>destructuring</em> them with pattern matching. So:</p><pre>[a_head | and_tail] = list<br>IO.inspect(a_head) # =&gt; 1<br>IO.inspect(and_tail) # =&gt; [2, 3]</pre><p>We have achieved similar effect with slightly more descriptive way. But with pattern matching you can go even further! Please see next example:</p><pre>[a, b | tail] = list<br>IO.inspect(a) # =&gt; 1<br>IO.inspect(b) # =&gt; 2<br>IO.inspect(tail) # =&gt; [3]</pre><p>This example translates to something like <em>ok, please give me two elements (</em><strong><em>a</em></strong><em> and </em><strong><em>b</em></strong><em>) from the </em><strong><em>list</em></strong><em>, and the rest (</em><strong><em>tail</em></strong><em>) of it</em>. This is interesting! It becomes even more powerful when it comes to defining your functions. Imagine something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d8653c230c0f54c9f6a03a73d23e990/href">https://medium.com/media/4d8653c230c0f54c9f6a03a73d23e990/href</a></iframe><p>So:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baa99285b8650dbbcd8a9eda46d31253/href">https://medium.com/media/baa99285b8650dbbcd8a9eda46d31253/href</a></iframe><p>First <strong>process/1</strong> definition will match, if the <strong>list</strong> passed contains at least two elements, and the two first elements are the same.</p><p>Second definition will match if the passed <strong>list</strong> contains at least two elements and the second element is equal <strong><em>2</em></strong>.</p><p>The third definition will match <em>anything </em>else.</p><p>Ok, this is about reading lists, but could the <strong>|</strong>operator be used for list <em>manipulation</em>? Certainly!</p><p>To prepend to the list, we could do:</p><pre>[123 | list]<br># =&gt; [123, 1, 2, 3]</pre><p>How about appending? First guess to use the operator would be like:</p><pre>[list | 4]</pre><p>However, what happens is probably not quite what you would expect, because it turns to be:</p><pre># =&gt; [[1, 2, 3], 4]</pre><p>This proofs that the <strong>|</strong> indicates <em>head-tail</em> relation of specified elements, thus, the <strong><em>list</em></strong> became a <strong>head</strong>, and <strong><em>4</em></strong> is a <strong>tail </strong>(there is limitation of what list elements can be, thus another list is perfectly valid choice), but this doesn’t mean, the <strong>head</strong> should be a single element (remember destrucuring list extracting two first elements?):</p><pre>[3, 2, 1 | list]<br># =&gt; [3, 2, 1, 1, 2, 3]</pre><p>The reason for such a behaviour is because <em>prepending</em> to the list is very fast operation, comparing to appending to the list (which would require traversing whole list). If, however, you would like to append to a list, you should turn your attention to <a href="http://elixir-lang.org/docs/stable/elixir/Kernel.html#++/2"><strong>++/2</strong></a> for concatenation:</p><pre>list ++ [4, 5]<br># =&gt; [1, 2, 3, 4, 5]</pre><p>To finish the discussion regarding the <strong>|</strong> operator and <strong>Lists</strong>, it’s worth mentioning possible problems which will be illustrated by code examples:</p><pre>hd([])<br>** (ArgumentError) argument error</pre><pre>tl([])<br>** (ArgumentError) argument error</pre><pre>[head | tail] = []<br>** (MatchError) no match of right hand side value: []</pre><pre>[a, b | tail] = [1]<br>** (MatchError) no match of right hand side value: [1]</pre><pre>[a, a | tail] = [1, 2]<br>** (MatchError) no match of right hand side value: [1, 2]</pre><h4>The | outside the world of Lists</h4><p>It turns, that the <strong>|</strong> operator is not limited to be used with <strong>Lists</strong> only, it might be used for manipulating <strong>Maps</strong> and <strong>Structs</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44afe608586d9ae9d73c2c623a34724f/href">https://medium.com/media/44afe608586d9ae9d73c2c623a34724f/href</a></iframe><p>Previously, we were able to build L<strong>ists</strong> with <strong>|</strong> operator (using it to prepend elements). This is not the case for <strong>Maps</strong> — if you try to add new key to the already existing map, it won’t work:</p><pre>user_map = %{user_map | occupation: “Developer”}<br>** (KeyError) key :occupation not found in: %{username: “PDAWCZAK”}<br> (stdlib) :maps.update(:occupation, “Developer”, %{username: “PDAWCZAK”})<br> (stdlib) erl_eval.erl:255: anonymous fn/2 in :erl_eval.expr/5<br> (stdlib) lists.erl:1262: :lists.foldl/3</pre><p>or <strong>Struct</strong>:</p><pre>user_str = %{user_str | occupation: “Developer”}<br>** (KeyError) key :occupation not found in: %User{username: “pdawczak”}<br> (stdlib) :maps.update(:occupation, “Developer”, %User{username: “PDAWCZAK”})<br> (stdlib) erl_eval.erl:255: anonymous fn/2 in :erl_eval.expr/5<br> (stdlib) lists.erl:1262: :lists.foldl/3</pre><p>In this case, you should turn your attention to <a href="http://elixir-lang.org/docs/stable/elixir/Map.html#put/3"><strong>Map#put/3</strong></a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a59f674e745343f886cb3401e02619b8/href">https://medium.com/media/a59f674e745343f886cb3401e02619b8/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c86158826205" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>