Monday, August 13, 2018

Nifi Tuning Tip - Using Backpressure and Max Retries

Apache Nifi supports buffering of queuing data. This is very useful when ur downstream processor is not working as expected (say due to a connection timeout) in which case Nifi queues up the flow files for processing.

However this can also turn out to be a negative if downstream system remains out for a longer than handled time. In such a case, the number of flow files can build up causing stress on the Nifi cluster and may even cause failure. Another scenario can be wherein a processor is translating an input message. A message in incorrect format might cause the processor to retry it an indefinite number of times causing queuing up of other messages and unnecessary stress on the cluster.


The best way to avoid this is to use a combination of Backpressure &Threshold, and impose a max limit on the number of retries. Backpressure implies limiting the amount or size of messages that can be queued up. Once the threshold value is reached, the connector doesn’t allow any further flow files or messages to get build up.  



Apache Nifi supports buffering of queuing data. This is very useful when ur downstream processor is not working as expected (say due to a connection timeout) in which case Nifi queues up the flow files for processing.

However this can also turn out to be a negative if downstream system remains out for a longer than handled time. In such a case, the number of flow files can build up causing stress on the Nifi cluster and may even cause failure. Another scenario can be wherein a processor is translating an input message. A message in incorrect format might cause the processor to retry it an indefinite number of times causing queuing up of other messages and unnecessary stress on the cluster.

The best way to avoid this is to use a combination of Backpressure &Threshold, and impose a max limit on the number of retries. Backpressure implies limiting the amount or size of messages that can be queued up. Once the threshold value is reached, the connector doesn’t allow any further flow files or messages to get build up.  

Thursday, March 29, 2018

Clearing hdfs space on CDH cluster

Problem Statement: On our dev CDH cluster we were frequently facing issues related to hdfs space getting filled up due to which HDFS and related services would halt. This would then
interrupt our development work. 

What we used to do: We would resort to dropping temporary tables which would free up some space but that would give us only a week's breathing space at max.

A more permanent solution: To find a more permanent fix I ran "hdfs dfsadmin -report" command on any of the datanodes. This command showed up DFS used and available capacity on all data nodes in the cluster. As expected, the nodes had run out of free space. 

Then i ran command "hdfs dfs -du -h /". This showed that some TBs of space was occupied by /tmp folder. 
On further drilling down i found that multiple folders (including logs folder) were hogging space but the information they had was not needed. 

So a simple hdfs dfs -rm -r /tmp/<folder name> followed by cleaning of hdfs trash folder did the trick. However free space did not immediately reflect on CDH cluster but took a couple of hours
before CDH started reporting hdfs as normal.

While this is too simple a thing to write a post on but sometimes simple things end up taking a lot of time too :)

Wednesday, January 17, 2018

Implementing mocking with JUNITs

JUNITs are an easy and effective way to unit test your code. However when writing a JUNIT you need to ensure that the scope of test case remains within that class
only and does not go beyond it.
What this means is that say you have a class A which call a method of Class B from within it. Then ur unit test case should be limited to methods of Class A and
should not test method of Class B otherwise the test case will become an integration test. This can be achieved using a Mock framework such as Mockito and this is
where JUNITs become tricky as well.

I was trying to write JUNITs using Mockito for a simple case as mentioned above. Class code below:

Class to be tested:

public Class A {
  public String parseEvent(String line) {
// some business logic
ClassB bObj = new ClassB();
String randomNum = bObj.getRandomNum().toString();
return line.append(randomNum);
  }
}

Junit:

public class ATest {

   @Test
   public void testParseEvent() {
       String inputLine= <some data>;
       String expectedOutput =<some data>;
       
       ClassB bObject = mock(ClassB.class);
       when(bOject.getRandomNum()).thenReturn(2);
       
       Class A aObject = new ClassA();
       String result = aObject.parseEvent(inputLine);
       Assert.assertArrayEquals(expectedOutput.getBytes(),result.getBytes());
       
   }

}

This looked alright to me. I was trying to mock class B's method so as to return a predetermined number and then compare expected and actual output.
However despite trying above and many other approaches I could see that B's method was actually getting called instead of getting mocked.

After a lot of googling found out that the issue was not with Junit or Mocking but with the way Class A was written. Since it was instantiating object of Class B, 
the mock object got lost and acutal instance got called. After refactoring Class A, Junit worked fine. Refactored code below:

public ClassA {

   private ClassB obj=null;

   public ClassA(ClassB obj) {
this.obj=obj;
   }

  public String parseEvent(String line) {
// some business logic
String randomNum = obj.getRandomNum().toString();
return line.append(randomNum);
  }
}

After refactoring Class A's code, in my JUNIT i passed the mocked object of Class B when creating object of Class A. The mocking worked fine and Junit returned 
expected result. 
Happy Ending :) 

Thursday, December 29, 2016

Hive - Querying Hive table data via Mapreduce job using HCatalog

Problem: While querying hive db via Pig is a pretty common use case, what we had to attempt was a comparatively less common scenario - to query hive database via Mapreduce. For this we resorted to using HCatalog.

Below solution has been tried using embedded derby DB for hive, and running mapreduce job in standalone mode from console. In addition, below blog link was a lot of help:

In job apart from setting mapper and reducer, we tell it to use HCatInputFormat and pass database, table name as input. 
Using HCatOutputFormat we specify output database and table details.

package callhive;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hive.hcatalog.data.DefaultHCatRecord;
import org.apache.hive.hcatalog.data.schema.HCatSchema;
import org.apache.hive.hcatalog.mapreduce.HCatInputFormat;
import org.apache.hive.hcatalog.mapreduce.HCatOutputFormat;
import org.apache.hive.hcatalog.mapreduce.OutputJobInfo;

public class OnTimeDriver extends Configured implements Tool{

    public int run( String[] args ) throws Exception{
     System.out.println("Job started.............");
     Configuration conf = new Configuration();
     Job job = new Job(conf, "OnTimeCount");
     job.setJarByClass(OnTimeDriver.class); 
     job.setMapperClass(OnTimeMapper.class);
     job.setReducerClass(OnTimeReducer.class);

     HCatInputFormat.setInput(job, "airline", "ontimeperf");
     //FileOutputFormat.setOutputPath(job, new Path(args[0]));
     job.setInputFormatClass(HCatInputFormat.class);
     job.setMapOutputKeyClass(IntPair.class);
     job.setMapOutputValueClass(IntWritable.class);
     job.setOutputKeyClass(Text.class);
     job.setOutputValueClass(DefaultHCatRecord.class);
     job.setOutputFormatClass(HCatOutputFormat.class);
     System.out.println("Reached here ..Setting HCATOUTPUT");
     
   
     
     HCatOutputFormat.setOutput(job, OutputJobInfo.create("airline", "flight_count", null));
     HCatSchema s = HCatOutputFormat.getTableSchema(job.getConfiguration());
     HCatOutputFormat.setSchema(job, s);
     
     return (job.waitForCompletion(true)? 0:1);
    }
    
    public static void main(String[] args) throws Exception{
    int exitCode = ToolRunner.run(new OnTimeDriver(), args);
    System.exit(exitCode);
    }
}

Mapper code queries a table called ontimeperf which contains columns month(int), year(int) and dayofmonth(int). It creates a custom key to store month and year with dayofmonth as value.

public class OnTimeMapper extends Mapper<WritableComparable,HCatRecord,IntPair,IntWritable> {
@Override
protected void map(WritableComparable key, HCatRecord value,
Mapper<WritableComparable, HCatRecord, IntPair, IntWritable>.Context context)
throws IOException, InterruptedException {
System.out.println(" Mapper invoked....");
System.out.println(" Mapper ...."+value.toString());
try {
HCatSchema schema = HCatBaseInputFormat.getTableSchema(context.getConfiguration());
Integer year = new Integer(value.getInteger("year", schema));
   Integer month = new Integer(value.getInteger("month", schema));
   Integer DayofMonth = value.getInteger("dayofmonth", schema);
   System.out.println("Data read from input table "+year+"||"+month+"||"+DayofMonth);
   context.write(new IntPair(year, month), new IntWritable(DayofMonth));
   System.out.println("Mapper done with");
} catch (Exception ex) {
ex.printStackTrace();
} 
}
}

In Reducer, I iterated over set of year, month pairs and their count was no of flight occurrences. Saved this data to another hive table (flight_count having columns year-int, month-int and flightcount-int

public class OnTimeReducer extends Reducer<IntPair, IntWritable, NullWritable, HCatRecord> {

public void reduce(IntPair key, Iterable<IntWritable> value, Context context)
throws IOException, InterruptedException {

System.out.println(" Reducer called ....");

try {

int count = 0; // records counter for particular year-month
for (IntWritable s : value) {
count++;
}

// define output record schema
List columns = new ArrayList(3);
columns.add(new HCatFieldSchema("year", HCatFieldSchema.Type.INT, ""));
columns.add(new HCatFieldSchema("month", HCatFieldSchema.Type.INT, ""));
columns.add(new HCatFieldSchema("flightCount", HCatFieldSchema.Type.INT, ""));
HCatSchema schema = new HCatSchema(columns);
HCatRecord record = new DefaultHCatRecord(3);

record.setInteger("year", schema, key.getFirstInt());
record.set("month", schema, key.getSecondInt());
record.set("flightCount", schema, count);
System.out.println("record is " + record.toString());
context.write(NullWritable.get(), record);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Troubleshooting tips: Faced below keys errors when running the code

  • Caused by: javax.jdo.JDOFatalUserException: There is no available StoreManager of type "rdbms". Make sure that you have put the relevant DataNucleus store plugin in your CLASSPATH and if defining a connection via JNDI or DataSource you also need to provide persistence property "datanucleus.storeManagerType.
Solved by setting below classpath. 
export HADOOP_CLASSPATH=myspace-1.0.1.jar:$HCAT_HOME/share/hcatalog/hive-hcatalog-core-2.1.0.jar:$HIVE_HOME/lib/hive-exec-2.1.0.jar:$HIVE_HOME/lib/datanucleus-core-4.1.6.jar:$HIVE_HOME/lib/datanucleus-api-jdo-4.2.1.jar:$HIVE_HOME/lib/javax.jdo-3.2.0-m3.jar:$HIVE_HOME/lib/datanucleus-rdbms-4.1.7.jar:$HIVE_HOME/lib/derby-10.10.2.0.jar:$HIVE_HOME/lib/antlr-runtime-3.4.jar

  • Required table missing : "VERSION" in Catalog "" Schema "". DataNucleus requires this table to perform its persistence operations. Either your MetaData is incorrect, or you need to enable "datanucleus.schema.autoCreateTables"
            Solved by adding hive conf folder to classpath and modifying hive-site.xml to have below entry:
<property>
   <name>javax.jdo.PersistenceManagerFactoryClass</name>
   <value>org.datanucleus.api.jdo.JDOPersistenceManagerFactory</value>
   <description>class implementing the jdo persistence</description>
</property>

Friday, November 18, 2016

Hive - Creating and loading data in an external partitioned table


I have been ramping up on Hive concepts these days. 
This post is on one interesting and a bit tricky concept that I came across and thought of sharing.
It deals with creating and loading data in an external PARTITIONED table and then querying it for data

Hive version: 2.1.0 from Apache

First let’s create an EXTERNAL table with a three fields and partitioned on one of these fields.

CREATE EXTERNAL TABLE my_dest_table (
                         primary_alias_type string,
                         primary_alias_id string)
PARTITIONED BY (d string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
LOCATION '/home/input/testData/my_dest_table/'
As you can see I have created an external table with partitions and at the location mentioned I have placed a csv file having three columns and plenty of data.

Now I run a select statement to view data:
hive> select * from my_dest_table;
OK
Time taken: 1.467 seconds

As you can see I don’t see any output here. Had this been a Non Partitioned External table the query would have returned results but in this case it needs some more effort. You need to create partitions and load data in those partitions as well. 

ALTER TABLE my_dest_table ADD PARTITION(d = 20000)
LOCATION '/home/input/testData/my_dest_table/20000';

As you can see above I have created a partition using ALTER TABLE command to add this info to the metastore. Also created corresponding folder and placed relevant snapshot of csv file data in the folder. You can alternatively create all partition folders in the filesystem and then use MSCK REPAIR TABLE command to load partition info in metastore in one go.

Now when I do a select, I can see the data in query output.

Some more points of note are that an external table is only created in metastore and you wont see its info in the warehouse folder (as you can see for MANAGED tables).

Tuesday, September 20, 2016

Effective Interviewing

I have been taking interviews for my organisation for more than 2 yrs now and must have taken 80+ interviews. So when I was invited to attend Effective Interviewing Skills workshop, it felt more like a waste of time. After all what more was there to learn I felt. Thankfully my bubble of overconfidence burst and in a pleasant way.

I viewed interviewing as a non avoidable task and a hindrance in the way of completing my work on time. I used to approach the interviews with a very straight face and kept it to the point. However during this session I realised I had got it all wrong.

An interview is a candidate's first face to face interaction with the company, and first impressions are often hard to change. So it must be given its due importance and time.
I found that its important for an interviewer to introduce himself as well, talk a brief about the organisation, specially points that cannot be found on the world of internet. Also its good to understand if the candidate knows the role and job profile he is appearing for, and set the expectations correctly. Now that I have implemented this, it has become a good way to break the ice and gives some time to the candidate to settle down as well.

I also found that one should read the candidate's resume in advance (rather than go through it in front of them) so that they are well aware of candidate's skill sets and know what to ask. When I went ahead and implemented this, I found the candidates many a times were both amused and surprised that I had read their profile so deeply.

You might be taking a technical interview but its important not to limit yourself to technical stuff only during the discussion. One must evaluate the candidate on his/her attitude as well and not leave it for the manager or HR. After all attitude at many times plays an as important role as knowledge.
While you can argue that attitude is not easy to judge, BEI or Behavioural Event Interviewing plays an important role here. This strategy stresses on questioning the candidate a behavioural question and asking him to supplement the answer with actual instances from the past. e,g Tell me about a situation where in you were faced with a very challenging situation. What was it and how did you deal with it. Since the answer needs to focus on past experience there is lesser scope for manipulation. Also what a candidate considers challenging may or may not suit your project needs and will give you a good idea on whether he/she will fit in or not.

Last but not the least dont try to cut an interview short. Evaluating a candidate can easily take upwards of 45 mins so be patient and keep pending work tasks off your mind :)

Saturday, August 20, 2016

Documenting in the Agile world

Documentation is considered pretty un-Agilish in the Agile development world. However based on my short tryst with Agile, I feel its a necessary evil. Without adequate documentation, debugging; bug fixing and maintenance tend to become nightmares. Infact I have seen more time getting consumed by developers trying to understand other developers code than it would take to document it.
I definitely DO NOT support the elaborate documentation style that comes with Waterfall - High level designs, Low level designs and more but should be minimal enough to support the needs.

One way to do so is to add more comments than lines of code you write. This way your code would look like a beautiful story - easy to read, understand and maintain. Block comments, method comments and class level comments - all add to the readability of your code. Also this needs to be done while you are coding and not at a later stage (because that time never comes).

To document business aspect of your application you can maintain a running technical design document where in developments done in a Sprint can be jotted down for reference later on.

In these two ways you can keep your application maintenance low-cost even as it expands and still adhere to Agile's short timelines.

This post is based on my experience with Agile. Any thoughts or recommendations are welcome. Please feel free to comment.