<?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[Oliver&#39;s Tech Blog - Medium]]></title>
        <description><![CDATA[I blog about things I’ve learnt and hope to revisit sometime in the future. - Medium]]></description>
        <link>https://medium.com/olivers-tech-blog?source=rss----c6aa0e7593d4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Oliver&amp;#39;s Tech Blog - Medium</title>
            <link>https://medium.com/olivers-tech-blog?source=rss----c6aa0e7593d4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:42:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/olivers-tech-blog" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Transforming Spark Datasets using Scala transformation functions]]></title>
            <link>https://medium.com/olivers-tech-blog/transforming-spark-datasets-using-scala-transformation-functions-1ef3abdac9?source=rss----c6aa0e7593d4---4</link>
            <guid isPermaLink="false">https://medium.com/p/1ef3abdac9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Wed, 25 Sep 2019 16:11:42 GMT</pubDate>
            <atom:updated>2020-05-01T08:10:48.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvMy342xIwuiII3aS6b6yg.png" /><figcaption>Transforming Spark Datasets</figcaption></figure><p>There are few times where I’ve chosen to use Spark as an ETL tool for it’s ease of use when it comes to reading/writing parquet, csv or xml files.</p><p>Reading any of these file formats is as simple as one line of spark code (after you ensure you have the required dependencies of course)</p><h3>Intent</h3><p>Most of the reference material available online for transforming Datasets points to calling createOrReplaceTempView() and registering the Dataset/Dataframe as a table, then performing SQL operations on it.</p><p>While this may be fine for most use cases, there are times when it feels more natural to use Spark’s Scala transformation functions instead, especially if you already have some pre existing transformation logic written in Scala or ReactiveX or even Java 8.</p><p>If this sounds like something you’d like to do, then please read on.</p><h3>I’ve decided to move this article to my personal blog</h3><p><a href="https://olivermascarenhas.com/2019-09-25-how-to-transform-a-spark-dataset/">Transforming Spark Datasets using Scala transformation functions</a></p><h3>I’ve also written an extension to this article</h3><p><a href="https://olivermascarenhas.com/2020-05-01-apache-spark-dataframe-transform-using-udf/">Spark DataFrame transform using a User Defined Function (UDF)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ef3abdac9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/olivers-tech-blog/transforming-spark-datasets-using-scala-transformation-functions-1ef3abdac9">Transforming Spark Datasets using Scala transformation functions</a> was originally published in <a href="https://medium.com/olivers-tech-blog">Oliver&#39;s Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a Spark Dataframe to an Elasticsearch Index]]></title>
            <link>https://medium.com/olivers-tech-blog/writing-a-spark-dataframe-to-an-elasticsearch-index-77a9de7dc3aa?source=rss----c6aa0e7593d4---4</link>
            <guid isPermaLink="false">https://medium.com/p/77a9de7dc3aa</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Sun, 06 Jan 2019 17:26:16 GMT</pubDate>
            <atom:updated>2021-06-03T14:58:24.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*c1SVmMzkLSoPgBl5cv4nNw.png" /></figure><p><strong><em>2021 Update: I have an updated version of this tutorial on YouTube. It has the latest dependencies and a slightly different approach to passing in configurations.</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9pfEVQ9te5E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9pfEVQ9te5E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9pfEVQ9te5E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/205b6ca92f1a19c626602a665ee60d4a/href">https://medium.com/media/205b6ca92f1a19c626602a665ee60d4a/href</a></iframe><p>In this post we will walk through the process of writing a Spark DataFrame to an Elasticsearch index.</p><p>Elastic provides Apache Spark Support via <a href="https://www.elastic.co/guide/en/elasticsearch/hadoop/master/spark.html">elasticsearch-hadoop</a>, which has native integration between Elasticsearch and Apache Spark.</p><p><strong>Note: All examples are written in Scala 2.11 with Spark SQL 2.3.x. Prior experience with Apache Spark is a pre-requisite.</strong></p><h3>Breakdown:</h3><ul><li>Maven Dependencies.</li><li>Spark-ES Configurations.</li><li>writeToIndex() Code.</li></ul><h3>Maven Dependencies</h3><p>The dependencies mentioned below should be present in your classpath. elasticsearch-spark-20 provides the native Elasticsearch support to Spark and commons-httpclient is needed to make RESTful calls to the Elasticsearch APIs. For some strange reason this version of elasticsearch-spark-20 omitted the http client dependency so it had to be added manually.</p><pre>-------------------<br>Snippet of the pom.xml<br>-------------------<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;<br>    &lt;artifactId&gt;spark-sql_2.11&lt;/artifactId&gt;<br>    &lt;version&gt;2.3.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;commons-httpclient&lt;/groupId&gt;<br>    &lt;artifactId&gt;commons-httpclient&lt;/artifactId&gt;<br>    &lt;version&gt;3.1&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.elasticsearch&lt;/groupId&gt;<br>    &lt;artifactId&gt;elasticsearch-spark-20_2.11&lt;/artifactId&gt;<br>    &lt;version&gt;6.4.2&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h3>Spark-ES Configurations</h3><p>In order for Spark to communicate with the Elasticsearch, we’ll need to know where the ES node(s) are located as well as the port to communicate with. These are provided to the SparkSession by setting the spark.es.nodes and spark.es.port configurations.</p><p><em>Note: The example here used Elasticsearch hosted to AWS and hence needed an additional configuration </em><em>spark.es.nodes.wan.only to be set to </em><em>true.</em></p><p>Let’s see some code to create the SparkSession.</p><pre><strong>val</strong> spark <strong>=</strong> <strong>SparkSession</strong><br>   <strong>.</strong>builder<strong>()</strong><br>   <strong>.</strong>appName<strong>(</strong>&quot;WriteToES&quot;<strong>)</strong><br>   <strong>.</strong>master<strong>(</strong>&quot;local[*]&quot;<strong>)</strong><br>   <strong>.</strong>config<strong>(</strong>&quot;spark.es.nodes&quot;<strong>,</strong>&quot;&lt;IP-OF-ES-NODE&gt;&quot;<strong>)</strong><br>   <strong>.</strong>config<strong>(</strong>&quot;spark.es.port&quot;<strong>,</strong>&quot;&lt;ES-PORT&gt;&quot;<strong>)</strong><br>   <strong>.</strong>config<strong>(</strong>&quot;spark.es.nodes.wan.only&quot;<strong>,</strong>&quot;true&quot;<strong>)</strong> <em>//Needed for ES on AWS<br></em>   <strong>.</strong>getOrCreate<strong>()</strong></pre><h3>writeToIndex() Code</h3><p>First we’ll define a <strong>case</strong> <strong>class</strong> to represent our index structure.</p><pre><strong>case</strong> <strong>class</strong> <strong>AlbumIndex(</strong>artist<strong>:String,</strong> yearOfRelease<strong>:Int,</strong> albumName<strong>:</strong> <strong>String)</strong></pre><p>Next we’ll create a Seq of AlbumIndex objects and convert them to a DataFrame using the handy .toDF() function, which can be invoked by importing spark.implicits._.</p><pre><strong>import</strong> spark.implicits._<br><br>   <strong>val</strong> indexDocuments <strong>=</strong> <strong>Seq(</strong><br>        <strong>AlbumIndex(</strong>&quot;Led Zeppelin&quot;<strong>,</strong>1969<strong>,</strong>&quot;Led Zeppelin&quot;<strong>),</strong><br>        <strong>AlbumIndex(</strong>&quot;Boston&quot;<strong>,</strong>1976<strong>,</strong>&quot;Boston&quot;<strong>),</strong><br>        <strong>AlbumIndex(</strong>&quot;Fleetwood Mac&quot;<strong>,</strong> 1979<strong>,</strong>&quot;Tusk&quot;<strong>)</strong><br>   <strong>).</strong>toDF</pre><p><em>Note: </em><em>spark here represents the </em><em>SparkSession object.</em></p><p>Once we have our DataFrame ready, all we need to do is import org.elasticsearch.spark.sql._ and invoke the .saveToEs() method on it.</p><pre><strong>import</strong> org.elasticsearch.spark.sql._<br><br>indexDocuments<strong>.</strong>saveToEs<strong>(</strong>&quot;demoindex/albumindex&quot;<strong>)</strong></pre><p>Here is the entire source code.</p><pre><strong>import</strong> org.apache.spark.sql.SparkSession<br><strong>import</strong> org.elasticsearch.spark.sql._<br><br><strong>object</strong> <strong>WriteToElasticSearch</strong> <strong>{</strong><br><br> <strong>def</strong> main<strong>(</strong>args<strong>:</strong> <strong>Array[String]):</strong> <strong>Unit</strong> <strong>=</strong> <strong>{</strong><br>   <strong>WriteToElasticSearch.</strong>writeToIndex<strong>()</strong><br> <strong>}</strong><br><br> <strong>def</strong> writeToIndex<strong>():</strong> <strong>Unit</strong> <strong>=</strong> <strong>{</strong><br><br>   <strong>val</strong> spark <strong>=</strong> <strong>SparkSession</strong><br>    <strong>.</strong>builder<strong>()</strong><br>    <strong>.</strong>appName<strong>(</strong>&quot;WriteToES&quot;<strong>)</strong><br>    <strong>.</strong>master<strong>(</strong>&quot;local[*]&quot;<strong>)</strong><br>    <strong>.</strong>config<strong>(</strong>&quot;spark.es.nodes&quot;<strong>,</strong>&quot;&lt;IP-OF-ES-NODE&gt;&quot;<strong>)</strong><br>    <strong>.</strong>config<strong>(</strong>&quot;spark.es.port&quot;<strong>,</strong>&quot;&lt;ES-PORT&gt;&quot;<strong>)</strong><br>    <strong>.</strong>config<strong>(</strong>&quot;spark.es.nodes.wan.only&quot;<strong>,</strong>&quot;true&quot;<strong>)</strong> <em>//Needed for ES on AWS<br></em>    <strong>.</strong>getOrCreate<strong>()</strong><br><br>   <strong>import</strong> spark.implicits._<br><br>   <strong>val</strong> indexDocuments <strong>=</strong> <strong>Seq(</strong><br>       <strong>AlbumIndex(</strong>&quot;Led Zeppelin&quot;<strong>,</strong>1969<strong>,</strong>&quot;Led Zeppelin&quot;<strong>),</strong><br>       <strong>AlbumIndex(</strong>&quot;Boston&quot;<strong>,</strong>1976<strong>,</strong>&quot;Boston&quot;<strong>),</strong><br>       <strong>AlbumIndex(</strong>&quot;Fleetwood Mac&quot;<strong>,</strong> 1979<strong>,</strong>&quot;Tusk&quot;<strong>)</strong><br>   <strong>).</strong>toDF<br><br>   indexDocuments<strong>.</strong>saveToEs<strong>(</strong>&quot;demoindex/albumindex&quot;<strong>)</strong><br> <strong>}</strong><br><strong>}</strong><br><br><strong>case</strong> <strong>class</strong> <strong>AlbumIndex(</strong>artist<strong>:String,</strong> yearOfRelease<strong>:Int,</strong> albumName<strong>:</strong> <strong>String)</strong></pre><h3>References</h3><ol><li><a href="https://www.elastic.co/guide/en/elasticsearch/hadoop/master/spark.html">Elasticsearch Spark Support.</a></li></ol><p><em>Also posted on </em><a href="https://olivermascarenhas.com/2019-01-06-writing-spark-dataframes-to-es/"><em>https://olivermascarenhas.com/2019-01-06-writing-spark-dataframes-to-es/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a9de7dc3aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/olivers-tech-blog/writing-a-spark-dataframe-to-an-elasticsearch-index-77a9de7dc3aa">Writing a Spark Dataframe to an Elasticsearch Index</a> was originally published in <a href="https://medium.com/olivers-tech-blog">Oliver&#39;s Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Profiling with Java Agents — Part 2]]></title>
            <link>https://medium.com/olivers-tech-blog/profiling-with-java-agents-part-2-37792b0d2f53?source=rss----c6aa0e7593d4---4</link>
            <guid isPermaLink="false">https://medium.com/p/37792b0d2f53</guid>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[instrumentation]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Sun, 30 Dec 2018 08:53:44 GMT</pubDate>
            <atom:updated>2020-03-08T04:51:13.829Z</atom:updated>
            <content:encoded><![CDATA[<h3>Profiling with Java Agents — Part 2</h3><p>In-case you haven’t read Part 1, you can find it <a href="https://medium.com/olivers-tech-blog/profiling-with-java-agents-part-1-a-hello-world-example-d5531189c418">here</a>.</p><h3>Introduction</h3><p>Let’s look at the Java Pyramid program we will be profiling. We will assume we do not have access to the source code. The program gives us the following output.</p><pre>   1<br>  1 1<br> 1 1 1<br>1 1 1 1<br>    1<br>   1 1<br>  1 1 1<br> 1 1 1 1<br>1 1 1 1 1<br>     1<br>    1 1<br>   1 1 1<br>  1 1 1 1<br> 1 1 1 1 1<br>1 1 1 1 1 1</pre><p>On running our profiler with the Java Pyramid program we get the following metrics</p><pre>========= Method Count Metrics =========<br>com.oliver.printpyramid.PrintPyramid.printPyramid--&gt;3<br>com.oliver.printpyramid.PrintPyramid.main--&gt;1<br>com.oliver.printpyramid.PrintPyramid.getLine--&gt;15<br>========= End Method</pre><p>Now we have some insight into which methods are being called by the Pyramid program.</p><p>This basic idea can be extended to record other metrics like method execution time, the results of which can be used to ease out performance bottlenecks.</p><h4>Motivation</h4><p>Java development tools like <a href="https://zeroturnaround.com/software/jrebel/"><strong>JRebel</strong></a> and <a href="https://zeroturnaround.com/software/xrebel/"><strong>XRebel</strong></a> as well as Application Monitoring tools like <a href="http://newrelic.com/java"><strong>New Relic APM</strong></a> are built upon similar albeit more complicated concepts of Java agents and byte-code instrumentation.</p><h3>Let’s Begin</h3><p>In sections below will look at:</p><ol><li>A quick overview of <a href="http://jboss-javassist.github.io/javassist/">Javassist</a>.</li><li>Define the Metrics Collector Interface.</li><li>Implement and Register a custom Class File Transformer.</li><li>Generate a Fat Jar i.e. a jar with dependencies.</li></ol><h3>A quick overview of Javassist</h3><p><em>Javassist is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*Z8rp7Yrgqx-zCMwu.png" /></figure><p><a href="http://blog.newrelic.com/wp-content/uploads/BM4.png"><em>Image Source</em></a></p><p>The main components of Javassist as indicated by the image above consist of</p><ul><li>CtClass</li><li>ClassPool</li><li>CtMethod</li></ul><h4>CtClass</h4><p>A CtClass object is an abstraction of a class file. In order to manipulate the byte-code of a class we will have to obtain its CtClass representation from the ClassPool.</p><h4>ClassPool</h4><p>The ClassPool object holds multiple CtClass objects.</p><h4>CtMethod</h4><p>A CtMethod object is an abstraction of a method in a class. Once we obtain the CtMethodrepresentation of a method we can manipulate its byte-code using the various methods present. In this example we will use the insertBefore method to add our instrumentation code.</p><p><em>Note: For a more complete and detailed explanation on Javassist please see references 2 and 3.</em></p><h3>The Metrics Collector Interface</h3><p>Here is the MetricsCollector interface which will be instrumented into the Java Pyramid program. The implementation of this interface is pretty straightforward and can be followed through with just the javadoc comments.</p><pre>package com<strong>.</strong>oliver<strong>.</strong>jagent<strong>.</strong>mectrics<strong>;</strong><br><br><strong>public</strong> <strong>interface</strong> <strong>MetricsCollector</strong> <strong>{</strong><br><br>	<em>/**<br>	 * This method is invoked at the beginning of every method call, it increments<br>	 * the counter associated with the the &lt;code&gt;methodName&lt;/code&gt; param.<br>	 * <br>	 * @param className<br>	 * @param methodName<br>	 */</em><br>	<strong>public</strong> <strong>void</strong> <strong>logMethodCall(</strong>String className<strong>,</strong> String methodName<strong>);</strong><br><br>	<em>/**<br>	 * This method registers the names of the methods which will invoke<br>	 * logMethodCall() on every call.<br>	 * <br>	 * @param className<br>	 * @param methodName<br>	 */</em><br>	<strong>public</strong> <strong>void</strong> <strong>registerMethod(</strong>String className<strong>,</strong> String methodName<strong>);</strong><br><br>	<em>/**<br>	 * Prints out the recorded Metric values<br>	 * <br>	 * @return<br>	 */</em><br>	<strong>public</strong> String <strong>printMetrics();</strong><br><strong>}</strong></pre><p>registerMethod() will be invoked by our agent code to register all the method names that will be instrumented.</p><ul><li>logMethodCall() will be instrumented into the Java Pyramid program code via byte-code modification so that it is invoked every-time a method of the Java Pyramid program is invoked.</li><li>printMetrics() will be invoked by our agent code on shut-down and will print out the metrics.</li></ul><h3>Registering a custom Class File Transformer</h3><p>In the <a href="https://oliversavio.github.io/java/2016/03/22/profiling-with-java-agents-part-one.html">first post</a> we implemented the premain method and displayed a “Hello World! Java Agent” message. In order to modify byte-code we need to write and register a custom ClassFileTransformer. This is done by using the addTransformer method of the java.lang.instrument.Instrumentation interface.</p><pre>package com<strong>.</strong>oliver<strong>.</strong>jagent<strong>;</strong><br><br>import java.lang.instrument.Instrumentation<strong>;</strong><br><br><strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>premain(</strong>String agentArgs<strong>,</strong> Instrumentation inst<strong>){</strong><br>		inst<strong>.</strong>addTransformer<strong>(new</strong> MyClassTransformer<strong>());</strong><br><strong>}</strong></pre><h3>Implementing MyClassTransformer</h3><p>The MyClassTransformer class implements the ClassFileTransformer interface and the transform method. We have initialized a ClassPool with the default class pool, this is fine when running a simple application like the Java Pyramid program in this example. However for applications running on web application servers like Tomcat and JBoss which use multiple class loaders, creating multiple instances of ClassPool might be necessary; an instance of ClassPool should be created for each class loader. You may find mode details on this <a href="https://jboss-javassist.github.io/javassist/tutorial/tutorial.html">here</a>.</p><pre>import java.lang.instrument.ClassFileTransformer<strong>;</strong><br>import java.lang.instrument.IllegalClassFormatException<strong>;</strong><br>import javassist.ClassPool<strong>;</strong><br><br><strong>public</strong> <strong>class</strong> <strong>MyClassTransformer</strong> <strong>implements</strong> ClassFileTransformer <strong>{</strong><br><br>  <strong>private</strong> ClassPool pool<strong>;</strong><br><br>  <strong>public</strong> <strong>MyClassTransformer()</strong> <strong>{</strong><br>	<strong>this.</strong>pool <strong>=</strong> ClassPool<strong>.</strong>getDefault<strong>();</strong><br>  <strong>}</strong>	<br><br>  <strong>public</strong> <strong>byte[]</strong> <strong>transform(</strong>ClassLoader loader<strong>,</strong> String className<strong>,</strong> Class<strong>&lt;?&gt;</strong> classBeingRedefined<strong>,</strong><br>	ProtectionDomain protectionDomain<strong>,</strong> <strong>byte[]</strong> classfileBuffer<strong>)</strong> <strong>throws</strong> IllegalClassFormatException <strong>{</strong><br>	<strong>...</strong><br>	<strong>}</strong><br><strong>}</strong></pre><h4>Filtering out Classes we do not intent to modify</h4><p>Our agent code will intercept all the classes to be loaded by the VM including the its own classes, hence we need to filter out these classes in the transformer and return their byte-code without any modification. The following code snippet does just this.</p><pre><strong>byte[]</strong> modifiedByteCode <strong>=</strong> classfileBuffer<strong>;</strong><br>String clazzName <strong>=</strong> className<strong>.</strong>replace<strong>(</strong>&quot;/&quot;<strong>,</strong> &quot;.&quot;<strong>);</strong><br><em>//Skip all agent classes</em><br><strong>if</strong> <strong>(</strong>clazzName<strong>.</strong>startsWith<strong>(</strong>&quot;com.oliver.jagent&quot;<strong>))</strong> <strong>{</strong><br>	<strong>return</strong> classfileBuffer<strong>;</strong><br><strong>}</strong><br><em>//Skip class if it doesn&#39;t belong to our Java Pyramid program</em><br><strong>if</strong> <strong>(!</strong>clazzName<strong>.</strong>startsWith<strong>(</strong>&quot;com.oliver.printpyramid&quot;<strong>))</strong> <strong>{</strong><br>	<strong>return</strong> classfileBuffer<strong>;</strong><br><strong>}</strong></pre><h4>Adding the instrumentation code</h4><p>Now that we have filtered out the unwanted classes it’s time to add our instrumentation code. The following code snippet will obtain a class representation from the ClassPool, iterate over all the methods presents in the class and use insertBefore() to add our instrumentation code at the start of every method.</p><pre><strong>private</strong> MetricsCollector collector <strong>=</strong> MetricsCollectorImpl<strong>.</strong>instance<strong>();</strong><br><strong>...</strong><br><em>//Records a package name so that the Javassist compiler may resolve a class name.</em><br><em>//This enables the compiled to resolve the class &quot;MetricsCollectorImpl&quot; below</em><br>pool<strong>.</strong>importPackage<strong>(</strong>&quot;com.oliver.jagent.mectrics&quot;<strong>);</strong><br><em>//Retrieve the class representation i.e. CtClass object</em><br>CtClass cclass <strong>=</strong> pool<strong>.</strong>get<strong>(</strong>clazzName<strong>);</strong><br>		<br><strong>for</strong> <strong>(</strong>CtMethod method <strong>:</strong> cclass<strong>.</strong>getDeclaredMethods<strong>())</strong> <strong>{</strong><br>	<em>//Register the method with our MetricsCollector</em><br>	collector<strong>.</strong>registerMethod<strong>(</strong>clazzName<strong>,</strong> method<strong>.</strong>getName<strong>());</strong><br>	<em>//Insert the instrumentation code at the start of the method.</em><br>	method<strong>.</strong>insertBefore<strong>(</strong>&quot;MetricsCollectorImpl.instance().logMethodCall(\&quot;&quot; <strong>+</strong> clazzName <strong>+</strong> &quot;\&quot;,\&quot;&quot; <strong>+</strong> method<strong>.</strong>getName<strong>()</strong> <strong>+</strong> &quot;\&quot;);&quot;<strong>);</strong><br><strong>}</strong></pre><p><em>Note: Exception handling has been omitted for brevity.</em></p><h3>Generating a Fat JAR</h3><p>In this example, we have used Javassist which is a third-party library. When running this version of the agent you will need to specify a path to this jar as well. In order to keep things simple, tools like JRebel create a “fat jar” or “jar with dependencies”, which uses a single JAR file. This can be achieved using the maven-assembly-plugin.</p><pre><strong>&lt;</strong>plugin<strong>&gt;</strong><br>	<strong>&lt;</strong>groupId<strong>&gt;</strong>org<strong>.</strong>apache<strong>.</strong>maven<strong>.</strong>plugins<strong>&lt;/</strong>groupId<strong>&gt;</strong><br>	<strong>&lt;</strong>artifactId<strong>&gt;</strong>maven<strong>-</strong>assembly<strong>-</strong>plugin<strong>&lt;/</strong>artifactId<strong>&gt;</strong><br>	<strong>&lt;</strong>version<strong>&gt;</strong>2.6<strong>&lt;/</strong>version<strong>&gt;</strong><br>	<strong>&lt;</strong>configuration<strong>&gt;</strong><br>	  <strong>&lt;</strong>descriptorRefs<strong>&gt;</strong><br>	    <strong>&lt;</strong>descriptorRef<strong>&gt;</strong>jar<strong>-</strong>with<strong>-</strong>dependencies<strong>&lt;/</strong>descriptorRef<strong>&gt;</strong><br>	  <strong>&lt;/</strong>descriptorRefs<strong>&gt;</strong><br>	  <strong>&lt;</strong>archive<strong>&gt;</strong><br>	    <strong>&lt;</strong>manifestFile<strong>&gt;</strong>src<strong>/</strong>main<strong>/</strong>resources<strong>/</strong>META<strong>-</strong>INF<strong>/</strong>MANIFEST<strong>.</strong>MF<strong>&lt;/</strong>manifestFile<strong>&gt;</strong><br>	  <strong>&lt;/</strong>archive<strong>&gt;</strong><br>	<strong>&lt;/</strong>configuration<strong>&gt;</strong><br>	<strong>&lt;</strong>executions<strong>&gt;</strong><br>	  <strong>&lt;</strong>execution<strong>&gt;</strong><br>	    <strong>&lt;</strong>id<strong>&gt;</strong>assemble<strong>-</strong>all<strong>&lt;/</strong>id<strong>&gt;</strong><br>	    <strong>&lt;</strong>phase<strong>&gt;</strong>package<strong>&lt;/</strong>phase<strong>&gt;</strong><br>	    <strong>&lt;</strong>goals<strong>&gt;</strong><br>		 <strong>&lt;</strong>goal<strong>&gt;</strong>single<strong>&lt;/</strong>goal<strong>&gt;</strong><br>	    <strong>&lt;/</strong>goals<strong>&gt;</strong><br>	  <strong>&lt;/</strong>execution<strong>&gt;</strong><br>	<strong>&lt;/</strong>executions<strong>&gt;</strong><br><strong>&lt;/</strong>plugin<strong>&gt;</strong></pre><p>Similar to Part 1, &lt;manifestFile&gt; contains the path to our custom manifest file, no changes have been made there except a change in the agent class name.</p><pre>Manifest<strong>-</strong>Version: 1.0<br>Premain<strong>-</strong>Class: com<strong>.</strong>oliver<strong>.</strong>jagent<strong>.</strong>Agent</pre><p>The agent is run in exactly the same way as described in <a href="https://medium.com/olivers-tech-blog/profiling-with-java-agents-part-1-a-hello-world-example-d5531189c418">Part 1</a>.</p><h3>Conclusion</h3><p>We have created a basic java profiler which gives us insights into the inner workings of applications and have run the profiler as a java agent.</p><h3>References</h3><ol><li><a href="https://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html">Java Instrumentation Package</a></li><li><a href="http://jboss-javassist.github.io/javassist/">Javassist</a></li><li><a href="https://blog.newrelic.com/2014/09/29/diving-bytecode-manipulation-creating-audit-log-asm-javassist/">Diving into Bytecode Manipulation: Creating an Audit Log with ASM and Javassist</a>.</li><li><a href="https://github.com/zeroturnaround/callspy">Callspy</a> — A simple trace agent.</li></ol><p><em>Also posted on </em><a href="https://olivermascarenhas.com/2016-03-28-profiling-with-java-agents-part-two/"><em>https://olivermascarenhas.com/2016-03-28-profiling-with-java-agents-part-two/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37792b0d2f53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/olivers-tech-blog/profiling-with-java-agents-part-2-37792b0d2f53">Profiling with Java Agents — Part 2</a> was originally published in <a href="https://medium.com/olivers-tech-blog">Oliver&#39;s Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Profiling with Java Agents — Part 1: A Hello World Example]]></title>
            <link>https://medium.com/olivers-tech-blog/profiling-with-java-agents-part-1-a-hello-world-example-d5531189c418?source=rss----c6aa0e7593d4---4</link>
            <guid isPermaLink="false">https://medium.com/p/d5531189c418</guid>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[instrumentation]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Sun, 30 Dec 2018 08:45:49 GMT</pubDate>
            <atom:updated>2020-03-08T04:52:00.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKBgpTQj_ddsI0Eh_KaFOQ.jpeg" /></figure><h3>Profiling with Java Agents — Part 1: A Hello World Example</h3><p>The Java Agent technology has been around since JDK 1.5. Here we will build a simple profiler which will instrument our Java program and give us method execution count metrics. The profiler will be run as a Java Agent.</p><h3>Java Agent</h3><p>A Java agent is started by adding the following command line argument.</p><p><strong>-</strong>javaagent:jarpath<strong>[=</strong>options<strong>]</strong></p><p>Where jarpath is the path to the JAR file.</p><p>A Java agent JAR file must conform to the following conventions:</p><ol><li>The manifest of the JAR must contain the Premain-Class attribute, its value is the name of the agent class.</li><li>The agent class must implement one of the two following methods</li></ol><ul><li>public static void premain(String agentArgs, Instrumentation inst);</li><li>public static void premain(String agentArgs);</li></ul><p>The premain method serves as an entry point for the Java agent the same way main servers as an entry point to regular Java class.</p><p><em>Note: A Java agent class may also contain an </em><em>agentmain method which is invoked when an agent is attached to an already running VM.</em></p><h3>“Hello World” Java Agent</h3><p>Let’s use the conventions mentioned above to create a simple “Hello World” implementation.</p><p>Create a simple maven project. Add the Apache maven-jar-plugin plugin to the pom.xml.</p><pre>&lt;build&gt;<br>  &lt;plugins&gt;<br>    &lt;plugin&gt;<br>	 &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>	 &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;<br>	 &lt;version&gt;2.4&lt;/version&gt;<br>	 &lt;configuration&gt;<br>	   &lt;archive&gt;<br>	     &lt;manifestFile&gt;src/main/resources/META-INF/MANIFEST.MF&lt;/manifestFile&gt;<br>	   &lt;/archive&gt;<br>	 &lt;/configuration&gt;<br>   &lt;/plugin&gt;<br> &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>&lt;manifestFile&gt; contains the path to our custom MANIFEST.MF file. This is the only modification needed to the pom.xml.</p><p>Create the agent class HelloWorldAgent.</p><pre>package com<strong>.</strong>oliver<strong>.</strong>javaagent<strong>.</strong>helloworldagent<strong>;</strong><br><br>import java.lang.instrument.Instrumentation<strong>;</strong><br><br><strong>public</strong> <strong>class</strong> <strong>HelloWorldAgent</strong> <strong>{</strong><br><br>	<strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>premain(</strong>String agentArgs<strong>,</strong> Instrumentation inst<strong>)</strong> <strong>{</strong><br>		System<strong>.</strong>out<strong>.</strong>println<strong>(</strong>&quot;Hello World! Java Agent&quot;<strong>);</strong><br>	<strong>}</strong><br>	<br><strong>}</strong></pre><p>Create MANIFEST.MF at src/main/resources/META-INF/ with the following content.</p><pre>Manifest<strong>-</strong>Version: 1.0 <br>Premain<strong>-</strong>Class: com<strong>.</strong>oliver<strong>.</strong>javaagent<strong>.</strong>helloworldagent<strong>.</strong>HelloWorldAgent</pre><p>To test our Agent class let’s use the default App class generated by maven. I have added the word “App” to the sysout statement.</p><pre>package com<strong>.</strong>oliver<strong>.</strong>javaagent<strong>.</strong>helloworldagent<strong>;</strong><br><em>/**<br> * Hello world!<br> *<br> */</em><br><strong>public</strong> <strong>class</strong> <strong>App</strong> <br><strong>{</strong><br>    <strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>main(</strong> String<strong>[]</strong> args <strong>)</strong><br>    <strong>{</strong><br>        System<strong>.</strong>out<strong>.</strong>println<strong>(</strong> &quot;Hello World! App&quot; <strong>);</strong><br>    <strong>}</strong><br><strong>}</strong></pre><p><em>Note: For the purposes of this example we are using a test class in the same package as the Agent class, however this will work with any class.</em></p><p>Now run a maven install to create the agent JAR. Here is a screenshot of the disassembled JAR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*2RJ3XuPwZUdgNwnw.png" /></figure><p>Run the App class with the -javaagent command line argument.</p><pre>java <strong>-</strong>javaagent:<strong>&lt;</strong>path<strong>-</strong>to<strong>-</strong>jar<strong>-</strong>file<strong>&gt;/</strong>helloworldagent<strong>-</strong>0.0<strong>.</strong>1<strong>-</strong>SNAPSHOT<strong>.</strong>jar com<strong>.</strong>oliver<strong>.</strong>javaagent<strong>.</strong>helloworldagent<strong>.</strong>App<br><br>Output:<br>Hello World<strong>!</strong> Java Agent<br>Hello World<strong>!</strong> App</pre><h3>Conclusion and Next Steps</h3><p>In this post we have seen how to create a simple Java Agent. Our agent however doesn’t really do much, in the next post we will take a look at the java.lang.instrument package and javassistwhich will enable us to manipulate byte-code and profile our Java program.</p><h3>References</h3><ol><li><a href="https://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html">Java Instrumentation Package</a></li></ol><p><em>Also posted on </em><a href="https://olivermascarenhas.com/2016-03-22-profiling-with-java-agents-part-one/"><em>https://olivermascarenhas.com/2016-03-22-profiling-with-java-agents-part-one/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5531189c418" width="1" height="1" alt=""><hr><p><a href="https://medium.com/olivers-tech-blog/profiling-with-java-agents-part-1-a-hello-world-example-d5531189c418">Profiling with Java Agents — Part 1: A Hello World Example</a> was originally published in <a href="https://medium.com/olivers-tech-blog">Oliver&#39;s Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Spark SQL applications with a remote Hive cluster]]></title>
            <link>https://medium.com/olivers-tech-blog/running-spark-sql-applications-with-a-remote-hive-cluster-fac753feed81?source=rss----c6aa0e7593d4---4</link>
            <guid isPermaLink="false">https://medium.com/p/fac753feed81</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Sun, 30 Dec 2018 02:16:00 GMT</pubDate>
            <atom:updated>2020-03-08T04:45:25.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*JGynkG7OqF4eHf1QwAGHBQ.png" /></figure><p>The graphic above depicts a common workflow for running Spark SQL apps. The Hive metastore holds table schemas (this includes the location of the table data), the Spark clusters, AWS EMR clusters in this case are treated as ephemeral, they spin up, run their application(s) and terminate.</p><p>This setup enables you to run multiple Spark SQL applications without having to worry about correctly configuring a multi-tenant Hive cluster.</p><p><strong>Note: All examples are written in Scala 2.11 with Spark SQL 2.3.x. Prior experience with Apache Spark is pre-requisite.</strong></p><h3>Topics this post will cover:</h3><ul><li>Running Spark SQL with Hive.</li><li>Connecting to a remote Hive cluster.</li><li>Connecting to a remote Hive cluster with HA (High Availability) enabled.</li></ul><h3>Running Spark SQL with Hive</h3><p>Spark SQL supports the HiveQL syntax as well as Hive SerDes and UDFs, allowing you to access existing Hive warehouses. Connecting to a Hive metastore is straightforward — all you need to do is enable hive support while instantiating the SparkSession.</p><pre><strong>import</strong> org.apache.spark.sql.SparkSession<br><br><em>// warehouseLocation points to the default location for managed databases and tables<br></em><strong>val</strong> warehouseLocation <strong>=</strong> <strong>new</strong> <strong>File(</strong>&quot;spark-warehouse&quot;<strong>).</strong>getAbsolutePath<br><br><strong>val</strong> spark <strong>=</strong> <strong>SparkSession</strong><br>  <strong>.</strong>builder<strong>()</strong><br>  <strong>.</strong>appName<strong>(</strong>&quot;Simple Spark SQL App&quot;<strong>)</strong><br>  <strong>.</strong>config<strong>(</strong>&quot;spark.sql.warehouse.dir&quot;<strong>,</strong> warehouseLocation<strong>)</strong><br>  <strong>.</strong>enableHiveSupport<strong>()</strong><br>  <strong>.</strong>getOrCreate<strong>()</strong></pre><p>This assumes that the Spark application is co-located with the Hive installation.</p><h3>Connecting to a remote Hive cluster</h3><p>In order to connect to a remote Hive cluster, the SparkSession needs to know where the Hive metastore is located. This is done by specifying the hive.metastore.uris property.</p><p>This property can be found in the hive-site.xml file located in the /conf directory on the remote Hive cluster, for Horton Data Platform (HDP) and AWS EMR the location is /etc/hive/conf/hive-site.xml. Only a sub-set of all the properties mentioned in the file are needed.</p><p>Create a file named hive-site.xml with the following configuration:</p><pre>&lt;configuration&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;hive.metastore.uris&lt;/name&gt;<br>        &lt;value&gt;thrift://[ip-to-hive-metastore]:9083&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;hive.metastore.client.connect.retry.delay&lt;/name&gt;<br>        &lt;value&gt;5&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;hive.metastore.client.socket.timeout&lt;/name&gt;<br>        &lt;value&gt;1800&lt;/value&gt;<br>    &lt;/property&gt;<br>&lt;/configuration&gt;</pre><p><em>Note: Although </em><em>hive.metastore.client.connect.retry.delay and </em><em>hive.metastore.client.socket.timeout are nice to have properties in a production environment, they aren’t mandatory.</em></p><p>This file needs to be passed as a parameter when running the spark-submit command as follows:</p><pre>spark-submit \<br>--master yarn \<br>--deploy-mode cluster \<br>--files hive-site.xml \<br>--class com.oliver.SparkSqlExample \<br>...<br>...</pre><p>And that’s about it, the code to create the SparkSession remains exactly the same as mentioned above.</p><h3>Connecting to a remote Hive cluster with HA (High Availability) enabled</h3><p>This is where things start to get interesting. In addition to location of the remote metastore, for HA (High Availability) enabled Hive clusters the SparkSession needs to know about DFS Nameservice configuration.</p><p>These properties can be found in the hdfs-site.xml file located in the /conf directory on the remote Hive cluster, for Horton Data Platform (HDP) and AWS EMR the location is /etc/hadoop/conf/hdfs-site.xml. Only a sub-set of the all the properties mentioned in the file are needed.</p><p>Create a file named hdfs-site.xml with the following configuration:</p><pre>&lt;configuration&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;dfs.nameservices&lt;/name&gt;<br>        &lt;value&gt;[HA-namenode-nameservice]&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;dfs.client.failover.proxy.provider.[HA-namenode-nameservice]&lt;/name&gt;<br>        &lt;value&gt;org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;dfs.ha.namenodes.[HA-namenode-nameservice]&lt;/name&gt;<br>        &lt;value&gt;nn1,nn2&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;dfs.namenode.rpc-address.[HA-namenode-nameservice].nn1&lt;/name&gt;<br>        &lt;value&gt;[namenode-one-address]:8020&lt;/value&gt;<br>    &lt;/property&gt;<br>    &lt;property&gt;<br>        &lt;name&gt;dfs.namenode.rpc-address.[HA-namenode-nameservice].nn2&lt;/name&gt;<br>        &lt;value&gt;[namenode-two-address]:8020&lt;/value&gt;<br>    &lt;/property&gt;<br>&lt;/configuration&gt;</pre><p><em>Note: The configuration above assumes the HDFS cluster has been configured with two Name Nodes i.e. nn1 and nn2.</em></p><p>Finally, both hive-site.xml and hdfs-site.xml need to be passed as parameters to the spark-submit command.</p><pre>spark-submit \ <br>--master yarn \ <br>--deploy-mode cluster \ <br>--files hive-site.xml,hdfs-site.xml \ <br>--class com.oliver.SparkSqlExample \ <br>... <br>...</pre><h3>References</h3><ol><li><a href="https://spark.apache.org/sql/">Spark SQL</a></li><li><a href="https://spark.apache.org/docs/2.3.0/sql-programming-guide.html">Spark SQL Programming Guide</a></li></ol><p><em>Note: Also posted on </em><a href="https://olivermascarenhas.com/2018-12-28-connecting-spark-application-with-remote-hive-metastore/"><em>https://olivermascarenhas.com/2018-12-28-connecting-spark-application-with-remote-hive-metastore/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fac753feed81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/olivers-tech-blog/running-spark-sql-applications-with-a-remote-hive-cluster-fac753feed81">Running Spark SQL applications with a remote Hive cluster</a> was originally published in <a href="https://medium.com/olivers-tech-blog">Oliver&#39;s Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting sensor failure using the MQTT protocol, an IoT Proof of Concept]]></title>
            <link>https://medium.com/olivers-tech-blog/detecting-sensor-failure-using-the-mqtt-protocol-an-iot-proof-of-concept-284cc5a0684c?source=rss----c6aa0e7593d4---4</link>
            <guid isPermaLink="false">https://medium.com/p/284cc5a0684c</guid>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 17:47:32 GMT</pubDate>
            <atom:updated>2020-03-08T04:47:19.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>Detecting sensor failure using the MQTT protocol</h3><h3>Motivation</h3><p>IoT technology is beginning to witness wide scale adoption in the consumer as well as industrial environments. In a typical enterprise scenario, you may have a large number of inexpensive sensor nodes interacting with machinery and sending data to Gateway nodes. These Gateway nodes are responsible for aggregating sensor data before sending it to the back-end systems which may reside in the cloud. Detecting a failure in one or more of these inexpensive sensor nodes is critical in preempting catastrophic failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*5E3jYUe0BTa9ay9S.png" /></figure><p><a href="https://cdn.thenewstack.io/media/2015/07/Node_Gateway.png"><em>Image Source</em></a></p><h3>Breakdown</h3><p>In the sections below, we will look at:</p><ol><li>What is MQTT?</li><li>Essential MQTT Concepts.</li><li>MQTT on the Arduino.</li><li>A simple Java client.</li></ol><h3>1) What is MQTT?</h3><p>The FAQ page at mqtt.org provides an apt answer.</p><p><em>“MQTT stands for MQ Telemetry Transport. It is a publish/subscribe, extremely simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-latency or unreliable networks. The design principles are to minimise network bandwidth and device resource requirements whilst also attempting to ensure reliability and some degree of assurance of delivery. These principles also turn out to make the protocol ideal of the emerging “machine-to-machine” (M2M) or “Internet of Things” world of connected devices, and for mobile applications where bandwidth and battery power are at a premium.”</em></p><p>In short, MQTT is a messaging protocol that’s light weight, reliable and easy to implement. It was invented by IBM in 1999.</p><h3>2) Essential MQTT Concepts</h3><p>MQTT works over TCP/IP and uses a standard port 1883. An MQTT connection is always established between a client and a broker. No client can connect directly to another client.</p><h4>Client</h4><p>Any device from a small micro controller to a full fledge server, which is capable of running a MQTT library and can connect to a MQTT Broker, is considered a MQTT client. MQTT clients may be publishers or subscribers or both.</p><p><strong><em>In this PoC, the Arduino will be the publishing client and a Java program will act as a subscribing client.</em></strong></p><h4>Broker (Gateway Node)</h4><p>A MQTT Broker should typically be capable of handling thousands of concurrently connected MQTT clients. Brokers are responsible for receiving, filtering and sending messages to subscribed clients. Needless to say, brokers should be highly scalable, capable of integrating with back-end systems and resistant to failures. Mosquitto is an open source MQTT server, the Eclipse Paho project hosts an instance of the Mosquitto broker as a public sandbox.</p><p><strong><em>We will be using the freely available Eclipse Paho MQTT broker sandbox.</em></strong></p><h4>Quality of Service (QoS)</h4><p>MQTT is a reliable protocol and provides a QoS level agreement between the sender and the receiver of a message. The three levels are as follows.</p><ul><li>QoS 0 (At most once)</li><li>QoS 1 (At least once)</li><li>QoS 2 (Exactly once)</li></ul><p><strong>QoS 0</strong> is often known as fire and forget, messages aren’t acknowledged by the receiver nor stored by the sender for redelivery.</p><p><strong>QoS 1</strong> guarantees that each message will be delivered to the receiver, however the message may also be delivered more than once. Receivers return an acknowledgment (<a href="http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718043">PUBACK</a>) to the sender. Senders will store the message until it gets this acknowledgment. In the case of redelivery, a duplicate flag is set. This flag is ignored by the broker and client in the case of QoS 1.</p><p><strong>QoS 2</strong> guarantees that each message will be received only once. Once the received get a QoS 2 message, it sends back a “Publish Received” (<a href="http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718048">PUBREC</a>) packet and stores a reference to the packet identifier until it sends a “Publish Complete” (<a href="http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718058">PUBCOMP</a>) to the sender. This is important so that the message isn’t processed more than once.</p><p>Once the sender gets a PUBREC it can safely discard the initial publish, stores the PUBREC and responds with a “Publish release” (<a href="http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718053">PUBREL</a>). Once the receiver gets the PUBREL message, it will discard the stored state and respond with a PUBCOMP.</p><p>This two step flow makes QoS 2 the safest and slowest service level.</p><h4>Retained Messages</h4><p>A Retained Message is a normal MQTT message with the retained flag set to true. A broker will store a single retained message for each topic. Subscribing clients may match a topic using a pattern which may include wildcards. Retained messages are pushed to clients immediately after subscribing to a topic, they needn’t wait until a new message is made available.</p><p>It is important to note that a broker will store only the last retained message and the corresponding QoS for a topic.</p><h4>Last Will Testament (LWT)</h4><p>Last Will Testament (LWT) is an MQTT feature with is used to notify all clients which are subscribed to a topic that the publishing client has been disconnected abruptly. As per the <a href="http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html">MQTT 3.1.1 specifications</a>the broker may distribute a LWT of a client in the following cases.</p><ul><li>A network or I/O error is detected by the server.</li><li>The clients fails to communicate within the Keel Alive time.</li><li>The client closes the network connection without sending the DISCONNECT package first.</li><li>The server closes the network connection because of network error.</li></ul><p>The LWT is set as part of the CONNECT message when a connection is established between the client and the broker.</p><p><strong><em>We will use the LWT feature along with Retained Messages and QoS 1 to notify subscribing clients when a publisher (in this case a sensor node) disconnects abruptly.</em></strong></p><h3>3) MQTT on the Arduino</h3><p>I followed <a href="http://www.hivemq.com/blog/mqtt-client-library-encyclopedia-arduino-pubsubclient/">this</a> article by Nick O’Leary to install the MQTT library (PubSubClient) on the Arduino and to write some simple code.</p><p>The following snippet contains the initial setup required for the Ethernet client as well as defining the IP address to the MQTT broker, which is the Eclipse Paho Sandbox environment.</p><pre><em>// Update these with values suitable for your network.<br>// These values are used by the Ethernet shield<br></em>byte mac[]    <strong>=</strong> {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEE };<br>IPAddress ip(192, 168, 0, 111);<br><br><em>// Eclipse Paho Mqtt broker sandbox url &quot;iot.eclipse.org&quot; resolved to IP address<br></em>IPAddress brokerServer(198, 41, 30, 241);<br>EthernetClient ethClient;<br>PubSubClient mqttClient(ethClient);</pre><p>Next we will need our LWT parameters, namely the QoS, the will topic, the will message and the retained flag. As the retained flag is set to true, any new client subscribing to the status topic will immediately get the value.</p><pre><em>//LWT message constants<br></em>byte willQoS <strong>=</strong> 1;<br><strong>const</strong> <strong>char*</strong> willTopic <strong>=</strong> &quot;com/oliver/arduino/status&quot;;<br><strong>const</strong> <strong>char*</strong> willMessage <strong>=</strong> &quot;Arduino Offline&quot;;<br>boolean willRetain <strong>=</strong> true; </pre><p>Next the mqttClientConnect() function will setup the connection and if successful, publish an “Online” status to the “com/oliver/arduino/status” topic with a retained set to true. Since this is the same as the LWT topic, clients will always get the last known good value. <a href="http://pubsubclient.knolleary.net/api.html#connect2">Here</a> is the link to the API documentation of the connect() function.</p><pre><strong>void</strong> <strong>mqttClientConnect</strong>() {<br>  <strong>while</strong>(<strong>!</strong>mqttClient.connected()) {<br>    boolean connected <strong>=</strong> mqttClient.connect(&quot;arduinoClientId98&quot;, willTopic, willQoS, willRetain, willMessage);<br>    <strong>if</strong>(connected) {<br>      <em>//Publish a status of Online on the will topic once the client is connected.<br></em>      <em>//Retained is set to true so that new clients connecting will know the status immediately.<br></em>      mqttClient.publish(willTopic,&quot;Arduino Online&quot;, true);<br>    } <strong>else</strong> {<br>      <em>// Wait 5 seconds before retrying<br></em>      delay(5000);<br>    }<br>  }<br>}</pre><p><em>Note: I am intentionally leaving out the </em><em>loop() and </em><em>setup() functions for brevity.</em></p><h3>4) A Simple Java Client</h3><p>Below are code snippets of the Java client. It connects to the MQTT broker, and subscribes to the “com/oliver/arduino/status” topic. Assuming the Arduino client has been successfully connected earlier, this subscribing client should receive the “Audrino Online” message. On abruptly disconnecting the Arduino client (I yanked out the Ethernet cable), it should received the “Arduino Offline” message. The Java code is written using the <a href="https://eclipse.org/paho/clients/java/">Eclipse Paho MQTT library for Java</a>.</p><pre><em>//Initial Setup parameters</em><br><strong>public</strong> <strong>static</strong> <strong>final</strong> String BROKER_URL <strong>=</strong> &quot;tcp://iot.eclipse.org:1883&quot;<strong>;</strong><br><strong>public</strong> <strong>static</strong> <strong>final</strong> String CLIENT_ID <strong>=</strong> &quot;subClientId98&quot;<strong>;</strong><br><strong>public</strong> <strong>static</strong> <strong>final</strong> String SUB_TOPIC_PATTERN <strong>=</strong> &quot;com/oliver/ad/status&quot;<strong>;</strong><br><strong>private</strong> MqttClient mqttSubClient<strong>;</strong></pre><p>he setCallback() method takes a class to callback when events for the client arrives, I have provided a simple in-line implementation for the purposes of this PoC. The messageArrived()method prints the message out to standard output.</p><pre><strong>public</strong> <strong>void</strong> <strong>start()</strong> <strong>{</strong><br>	<strong>try</strong> <strong>{</strong><br>		mqttSubClient<strong>.</strong>setCallback<strong>(new</strong> MqttCallback<strong>()</strong> <strong>{</strong><br>		 <strong>public</strong> <strong>void</strong> <strong>messageArrived(</strong>String topic<strong>,</strong> MqttMessage message<strong>)</strong> <strong>throws</strong> Exception <strong>{</strong><br>		  System<strong>.</strong>out<strong>.</strong>println<strong>(</strong>&quot;Status: &quot; <strong>+</strong> message<strong>.</strong>toString<strong>());</strong><br>		 <strong>}</strong><br><br>		 <strong>public</strong> <strong>void</strong> <strong>deliveryComplete(</strong>IMqttDeliveryToken token<strong>)</strong> <strong>{</strong><br>		 <strong>}</strong><br><br>		 <strong>public</strong> <strong>void</strong> <strong>connectionLost(</strong>Throwable cause<strong>)</strong> <strong>{</strong><br>		 <strong>}</strong><br>	  <strong>});</strong><br>	 mqttSubClient<strong>.</strong>connect<strong>();</strong><br>	 mqttSubClient<strong>.</strong>subscribe<strong>(</strong>SUB_TOPIC_PATTERN<strong>);</strong><br><br>  <strong>}</strong> <strong>catch</strong> <strong>(</strong>MqttException e<strong>)</strong> <strong>{</strong><br>    e<strong>.</strong>printStackTrace<strong>();</strong><br> <strong>}</strong><br><strong>}</strong></pre><h3>Conclusion</h3><p>In this post, we have seen how to use the Last Will Testament and Retained message features of the MQTT protocol to detect abrupt disconnections of publishing clients.</p><h3>References</h3><ol><li><a href="http://mqtt.org/faq">Mqtt.org FAQs</a></li><li><a href="http://www.hivemq.com/mqtt-essentials/">MQTT Essentials</a></li><li><a href="http://pubsubclient.knolleary.net/api.html#connect2">PubSubClient API Documentation</a></li></ol><p><em>Also published on </em><a href="https://olivermascarenhas.com/2017-06-02-detecting-sensor-failure-using-mqtt-protocol-an-iot-proof-of-concept/"><em>https://olivermascarenhas.com/2017-06-02-detecting-sensor-failure-using-mqtt-protocol-an-iot-proof-of-concept/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=284cc5a0684c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/olivers-tech-blog/detecting-sensor-failure-using-the-mqtt-protocol-an-iot-proof-of-concept-284cc5a0684c">Detecting sensor failure using the MQTT protocol, an IoT Proof of Concept</a> was originally published in <a href="https://medium.com/olivers-tech-blog">Oliver&#39;s Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time-Series Scatter Plot of Server Requests using Python]]></title>
            <link>https://medium.com/olivers-tech-blog/time-series-scatter-plot-of-server-requests-using-python-9624da9250b5?source=rss----c6aa0e7593d4---4</link>
            <guid isPermaLink="false">https://medium.com/p/9624da9250b5</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[matplotlib]]></category>
            <dc:creator><![CDATA[Oliver Mascarenhas]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 17:33:06 GMT</pubDate>
            <atom:updated>2020-03-08T04:52:44.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jAKcgYTv7wm9f7-r_X_zA.png" /></figure><p>In this post I will attempt to explain how I used <a href="http://pandas.pydata.org/">Pandas</a> and <a href="http://matplotlib.org/">Matplotlib</a> to quickly generate server requests reports on a daily basis.</p><p>Problem To Be Solved: Generate a Scatter plot of the number of requests to a particular URL along with the 99th, 95th and 90th percentile of requests for the duration of a day.</p><p>Breakdown:</p><ol><li>Reading multiple server access log files.</li><li>Parsing the timestamp fields so that the graph can be scaled appropriately.</li><li>Aggregating the timestamp fields.</li><li>Calculating the Quantile values.</li><li>Generating the Scatter Plot.</li></ol><p>In this post I will leave out the details related to point number 1 and will concentrate on the remaining points. Since this was a fairly mundane task and had to be done daily for a couple of weeks, I intended on automating the process as well as generating the scatter plot as quickly as possible.</p><h3>Parsing the timestamp fields so that the graph can be scaled appropriately</h3><p>Let’s assume the input file contains only timestamps and the file has been read into a list using the following code.</p><pre>lines = [line.rstrip(&#39;\n&#39;) for line in open(file_name)]</pre><p>Since the x-axis of the scatter plot will contain timestamp values, the lines List which currently contains string values, needs to be converted into a List of timestamp values. My initial instinct was to use an explicit for loop. In an effort to speed up my script I came across python’s built-in map()function and the concept of List comprehension which reduce the for loop overhead when the loop body is relatively simple, check <a href="https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops">here</a> for more details. After a bit of benchmarking I settled on using the List comprehension method.</p><pre>from datetime import timedelta, datetime</pre><pre>dt_lst = [datetime.strptime(date_str, &#39;%H:%M:%S&#39;) for date_str in lines]</pre><h3>Aggregating the datetime fields</h3><p>In this aggregation step the goal was to perform a group-by on the timestamps in order to calculate the number of requests per second. To achieve this I used <a href="http://www.numpy.org/">Numpy</a> which is a package for scientific computing and <a href="http://pandas.pydata.org/">Pandas</a> which is a data analysis library. The <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html">Series</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html">DataFrame</a> objects from the Pandas library and the ones() method from the Numpy package are used to generate the data structure show in <em>Figure 1</em>, the code snippet below contains the details.</p><p><em>Note: I could have probably achieved the same result using only Pandas.</em></p><pre>import pandas as pd<br>import numpy as np<br>from pandas import DataFrame, Series</pre><pre><em># Create a Series named &quot;Request_Time&quot;</em><br>sr_dt = Series(dt_lst, name=&#39;Request_Time&#39;) <br><em># Create a DataFrame using the Request_Time Series</em><br>df = DataFrame(sr_dt)<br><em># Create an array of 1&#39;s using Numpy</em><br>count = sr_dt.size<br>ones = np.ones(count, dtype=int)<br><em># Add the ones array to the DataFrame with the header &quot;Counts&quot;</em><br>df[&#39;Counts&#39;] = ones</pre><p>The <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html">DataFrame</a> object is a tabular data structure with labeled rows and columns, you may think of it as an Excel Spreadsheet. After creating the DataFrame df you will end up with a structure as displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*vt4SfxsdW5iUIcx98289_Q.png" /><figcaption>Figure 1</figcaption></figure><p>The next step is to group-by the <em>Request_Time</em> column and sum up the counts, this is achieved by calling the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby">groupby</a> method on the DataFrame object.</p><pre>grouped = df.groupby(&#39;Request_Time&#39;).count()</pre><p>This gives us an aggregated DataFrame as displayed below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*bpFJEZ5yaeFLlYTs4FHeTQ.png" /><figcaption>Figure 2</figcaption></figure><h3>Calculating the Quantile values</h3><pre>ninety_five_quant = grouped.quantile(.95)[0] <em># [0] since we only need the quantile value</em><br>ninety_ninth_quant = grouped.quantile(.99)[0] <em># [0] since we only need the quantile value</em><br>ninety_eight_quant = grouped.quantile(.98)[0] <em># [0] since we only need the quantile value</em></pre><h3>Generating the Scatter Plot</h3><p>The Scatter plot is generated using the <a href="http://matplotlib.org/">Matplotlib</a> library. Since we are plotting timestamp values on the x-axis we will use the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot_date">plot_date()</a> method.</p><pre>ax.plot_date(x, y, xdate=True, ydate=False, color=&#39;skyblue&#39;)</pre><p>The x-axis contains the timestamp values, the y-axis contains the request counts, xdate=Trueindicates the x-axis contains date values.</p><p><em>Note: The Matplotlib library contains extensive documentation on all it’s API’s as well as a vast array of examples, hence I will refrain from going into more details in this post, you may check </em><a href="http://matplotlib.org/examples/pylab_examples/date_demo1.html"><em>this link</em></a><em> for more details.</em></p><p><em>The snippet below contains code related to rendering the Scatter Plot. I have taken a very simplistic and naive approach since it was good enough for my requirement.</em></p><pre>import matplotlib.pyplot as plt</pre><pre>total_req =  &#39;Total request: &#39; + str(count)<br>nine_five_quant_str =  &#39;95th Quantile: &#39; + str(ninety_five_quant)<br>nine_eight_quant_str =  &#39;98th Quantile: &#39; + str(ninety_eight_quant)<br>nine_nine_quant_str = &#39;99th Quantile: &#39; + str(ninety_ninth_quant)</pre><pre><em># x and y axis values are extracted from the grouped DataFrame</em><br>x = grouped.index<br>y = grouped.values</pre><pre>print &#39;Plotting Graph..&#39;<br>fig = plt.figure()<br>fig.suptitle(&#39;Scatter Plot&#39;, fontsize=14, fontweight=&#39;bold&#39;)<br>ax = fig.add_subplot(111)<br>fig.subplots_adjust(top=0.85)</pre><pre>ax.set_xlabel(&#39;Request Time&#39;)<br>ax.set_ylabel(&#39;Request Count&#39;)</pre><pre>text_x_axis_value = 0.9<br>ax.text(text_x_axis_value, 0.90, total_req, horizontalalignment=&#39;center&#39;, verticalalignment=&#39;center&#39;, transform = ax.transAxes)<br>ax.text(text_x_axis_value, 0.88, nine_five_quant_str, horizontalalignment=&#39;center&#39;, verticalalignment=&#39;center&#39;, transform = ax.transAxes)<br>ax.text(text_x_axis_value, 0.86, nine_eight_quant_str, horizontalalignment=&#39;center&#39;, verticalalignment=&#39;center&#39;, transform = ax.transAxes)<br>ax.text(text_x_axis_value, 0.84, nine_nine_quant_str, horizontalalignment=&#39;center&#39;, verticalalignment=&#39;center&#39;, transform = ax.transAxes)</pre><pre>ax.plot_date(x, y, xdate=True, ydate=False, color=&#39;skyblue&#39;)<br>plt.show()</pre><h3>Summary</h3><p>In this post we have seen how:</p><ul><li>List comprehension can give us better performance over an explicit for loop when the loop body is relatively simple. Please check <a href="https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops">here</a> for more details on the topic.</li><li>The <a href="http://pandas.pydata.org/">Pandas</a> library can be used to calculate aggregates and quantiles. We used the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html">Series</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html">DataFrame</a> objects which are the core data structures of the Pandas library to achieve this.</li><li>Generate a Time-Series Scatter Plot using the <a href="http://matplotlib.org/">Matplotlib</a> library.</li></ul><p><em>Also posted on </em><a href="https://olivermascarenhas.com/2016-02-21-time-series-scatter-plot-of-server-requests-in-python/"><em>https://olivermascarenhas.com/2016-02-21-time-series-scatter-plot-of-server-requests-in-python/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9624da9250b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/olivers-tech-blog/time-series-scatter-plot-of-server-requests-using-python-9624da9250b5">Time-Series Scatter Plot of Server Requests using Python</a> was originally published in <a href="https://medium.com/olivers-tech-blog">Oliver&#39;s Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>