Saturday, 27 January 2018

Apache Kafka - II

In the first segment on Apache Kafka, we covered the introduction and installation of Apache Kafka. In this second part, we will take a look at how data is published and subscribed in Apache Kafka

For working with Kafka, Zookeeper needs to be up and running. Open a terminal and run the below command:

F:\>
F:\>cd kafka_2.12-1.0.0


Start Zookeeper:

F:\kafka_2.12-1.0.0>bin\windows\zookeeper-server-start.bat config\zookeeper.properties

Note that the argument to the batch file is the file config\zookeeper.properties. Opening the file we see that the port on which zookeeper will run is 2181












Last few lines of output is shown below:

[2018-01-27 10:11:23,876] INFO Server environment:user.dir=F:\kafka_2.12-1.0.0 (org.apache.zookeeper.server.ZooKeeperServer)
[2018-01-27 10:11:23,907] INFO tickTime set to 3000 (org.apache.zookeeper.server.ZooKeeperServer)
[2018-01-27 10:11:23,907] INFO minSessionTimeout set to -1 (org.apache.zookeeper.server.ZooKeeperServer)
[2018-01-27 10:11:23,907] INFO maxSessionTimeout set to -1 (org.apache.zookeeper.server.ZooKeeperServer)
[2018-01-27 10:11:23,985] INFO binding to port 0.0.0.0/0.0.0.0:2181 (org.apache.zookeeper.server.NIOServerCnxnFactory)


The last line shows that zookeeper server is running on 2181 port as per entry in the file

Start Kafka:

Next, open another terminal and start Kafka as shown below:

F:\>
F:\>cd kafka_2.12-1.0.0

F:\kafka_2.12-1.0.0>bin\windows\kafka-server-start.bat config\server.properties

Last few lines of output is shown below:

[2018-01-27 10:35:18,071] INFO [TransactionCoordinator id=0] Startup complete. (kafka.coordinator.transaction.TransactionCoordinator)
[2018-01-27 10:35:22,680] INFO Creating /brokers/ids/0 (is it secure? false) (kafka.utils.ZKCheckedEphemeral)
[2018-01-27 10:35:22,758] INFO Result of znode creation is: OK (kafka.utils.ZKCheckedEphemeral)
[2018-01-27 10:35:22,758] INFO Registered broker 0 at path /brokers/ids/0 with addresses: EndPoint(workstation,9092,ListenerName(PLAINTEXT),PLAINTEXT) (kafka.utils.ZkUtils)
[2018-01-27 10:35:22,774] INFO Kafka version : 1.0.0 (org.apache.kafka.common.utils.AppInfoParser)
[2018-01-27 10:35:22,774] INFO Kafka commitId : aaa7af6d4a11b29d (org.apache.kafka.common.utils.AppInfoParser)
[2018-01-27 10:35:22,789] INFO [KafkaServer id=0] started (kafka.server.KafkaServer)


The message indicates that Kafka server is up and running.

Create Topic:

In a third terminal, let us now proceed to create a topic called topic_1 having a replication factor as 1 and number of partitions as 3:

F:\>
F:\>cd kafka_2.12-1.0.0

F:\kafka_2.12-1.0.0>bin\windows\kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 3 --topic topic_1

Output is shown below:

WARNING: Due to limitations in metric names, topics with a period ('.') or underscore ('_') could collide. To avoid issues it is best to use either, but not both.
Created topic "topic_1".


Start Producer:

Once the topic is created, we can start producers that publish data to this topic and consumers that will subscribe to the topic that will receive the messages. Open a fourth terminal to create console producer by entering below commands:

F:\>
F:\>cd kafka_2.12-1.0.0

F:\kafka_2.12-1.0.0>bin\windows\kafka-console-producer.bat --broker-list localhost:9092 --topic topic_1

We get a prompt as shown below:

F:\kafka_2.12-1.0.0>bin\windows\kafka-console-producer.bat --broker-list localhost:9092 --topic topic_1
>


Start Consumer:

On a fifth terminal, start a console consumer as follows:

F:\kafka_2.12-1.0.0>bin\windows\kafka-console-consumer.bat --zookeeper localhost:2181 --topic topic_1

Output is shown below:

Using the ConsoleConsumer with old consumer is deprecated and will be removed in a future major release. Consider using the new consumer by passing [bootstrap-server] instead of [zookeeper].

Now, in the fourth terminal on the prompt enter below messages:

Hello, Kafka!
Message 1
Message 2
Message 3

The producer terminal is shown below:







These messages should appear in the consumer terminal as shown below:









List Topics:

Use below command to list all topics on third terminal:

bin\windows\kafka-topics --zookeeper localhost:2181 --list

Output is shown below:

F:\kafka_2.12-1.0.0>bin\windows\kafka-topics --zookeeper localhost:2181 --list
topic_1


Describe Topic:

bin\windows\kafka-topics --describe --zookeeper localhost:2181 --topic topic_1

Output is shown below:

F:\kafka_2.12-1.0.0>bin\windows\kafka-topics --describe --zookeeper localhost:2181 --topic topic_1
Topic:topic_1   PartitionCount:3        ReplicationFactor:1     Configs:
        Topic: topic_1  Partition: 0    Leader: 0       Replicas: 0     Isr: 0
        Topic: topic_1  Partition: 1    Leader: 0       Replicas: 0     Isr: 0
        Topic: topic_1  Partition: 2    Leader: 0       Replicas: 0     Isr: 0


Delete Topic:

bin\windows\kafka-topics --delete --zookeeper localhost:2181 --topic topic_1

Output is shown below:

F:\kafka_2.12-1.0.0>bin\windows\kafka-topics --delete --zookeeper localhost:2181 --topic topic_1
Topic topic_1 is marked for deletion.
Note: This will have no impact if delete.topic.enable is not set to true.


When we try to list the topics again on the third terminal, we get below output:

F:\kafka_2.12-1.0.0>bin\windows\kafka-topics --zookeeper localhost:2181 --list
__consumer_offsets
topic_1 - marked for deletion


On all terminals, click CTRL+C to exit

This concludes the introductory commands on Apache Kafka

Friday, 26 January 2018

Apache Kafka - I

In the next few posts starting with this one, we will take a look at Apache Kafka. Apache Kafka is a distributed streaming platform written in Scala and Java languages. We have already seen Sqoop and Apache Flume as ingestion tools for migrating data into Big Data systems. Apache Kafka serves the twin purpose of:

1) migrating data between systems/applications in real time through streaming data pipelines, and
2) processing streams of data in real time through applications

Apacha Kafka uses the Publish Subscribe model of messaging pattern. In the Publish Subscribe model, publishers are applications that are senders of  messages and subscribers are applications are recipients of messages. Publishers publish messages without explicitly specifying recipients or having knowledge of intended recipients. Publishers do not program the messages to be sent to any particular subscriber. Instead, the publishers publish messages to topics. Subscribers that evince an interest in a particular topic can subscribe to it to receive all the messages that are published to that topic by the publishers. Note that all subscribers subscribing to the same topic will receive the same messages related to that topic. In this sense, a loosely coupled architecture between the publishers and the subscribers is achieved and either of them do not have any knowledge of the other and can operate independently of the other.

Apache Kafka terminology consists of:

1) Producers: publish data to any number of topics of their choice. The producer is responsible for choosing which record to assign to which partition within that topic. This assignment of a record to a partition can be done in a round-robin fashion to balance load or it can be done according to a custom partition function

2) Consumers: are consumer instances grouped under a consumer group name. For every record that is published by a Producer under a topic, that message is delivered to one consumer instance that is part of a subscribing consumer group

3) Topics: are categories or feed names to which records are published by Producers. Topics in Kafka are always multi-subscriber based in that a topic can have zero, one, or many consumers that subscribe to the data written to it. Topics are split into one or more partitions. For each topic, a minimum of one partition exists.

4) Partitions: are ordered, immutable sequence of records that is continually appended to by records being published by producers. A sequential id number called the offset that uniquely identifies each record within the partition is assigned to each record within the partition. The Kafka cluster retains all published records within a partition, regardless of their having been consumed by a consumer, using a configurable retention period

5) Records: consists of an optional key, a value, and a timestamp. Producers publish records to a partition under a topic based on the record key. If the record has a key, then, the default partitioner for Java uses a hash of the record key to choose the partition, else, uses a round-robin strategy if the record has no key





















The four core Kafka APIs (Refer above figure) are:

1) Producer API: allows an application to publish a stream of records to one or more Kafka topics
2) Consumer API: allows an application to subscribe to one or more topics and process the stream of records produced to them
3) Streams API: allows an application to act as a stream processor, consuming an input stream from one or more topics and producing an output stream to one or more output topics, effectively transforming the input streams to output streams
4) Connector API: allows building and running reusable producers or consumers that connect Kafka topics to existing applications or data systems

Apache Kafka has the following prerequisites:

1) Java Runtime Environment
2) Memory - Sufficient memory for all Kafka related configurations
3) Disk Space - Sufficient disk space for all Kafka related configurations
4) Directory Permissions - Read/Write permissions for directories for Kafka related configurations
5) Zookeeper

In the first part of the series, we will install Kafka on Windows.

Download latest Kafka binaries from this link. As of writing this post, 1.0.0 is the latest release. The current stable version is 1.0.0. The link to the binary is:

https://www.apache.org/dyn/closer.cgi?path=/kafka/1.0.0/kafka_2.12-1.0.0.tgz

Click on sha512 to see this:

kafka_2.12-1.0.0.tgz: 1B647B7F 392148AA 2B9D4755 0A1502E5 0BE4B005 C70C82DA
                                E03065B8 9484E664 00528BE4 0CA2D54F 35EB2C0E 70F35C88
                                A04777C2 B625DAA5 D5546CAA B4ED6818


Move the downloaded binary to a drive, F drive in this case. Now, let us use the utility mentioned in this post to ensure completeness of the downloaded binary:

F:\>CertUtil -hashfile kafka_2.12-1.0.0.tgz SHA512
SHA512 hash of kafka_2.12-1.0.0.tgz:
1b647b7f392148aa2b9d47550a1502e50be4b005c70c82dae03065b89484e66400528be40ca2d54f35eb2c0e70f35c88a04777c2b625daa5d5546caab4ed6818
CertUtil: -hashfile command completed successfully.


The values are the same. Move the file to a folder created under F drive called kafka_2.12-1.0.0. We will use 7-Zip Manager to unzip this file. Open 7-Zip File Manager and point it to this file:







Click on Extract and enter F:\kafka_2.12-1.0.0\ in Extract to. Then, click OK:
















Select newly created file, kafka_2.12-1.0.0.tar. Click on Extract again and enter F:\ in Extract to. Then, click OK:























The final extracted files are shown below:










On the command line, navigate to kafka folder as follows:

F:\>
F:\>cd kafka_2.12-1.0.0\bin\windows
F:\kafka_2.12-1.0.0\bin\windows>


To see zookeeper files, enter below command:

F:\kafka_2.12-1.0.0\bin\windows>dir zookeeper*

Output is shown below: 

 Directory of F:\kafka_2.12-1.0.0\bin\windows

10/27/2017  09:26 PM             1,192 zookeeper-server-start.bat
10/27/2017  09:26 PM               905 zookeeper-server-stop.bat
10/27/2017  09:26 PM               977 zookeeper-shell.bat
               3 File(s)          3,074 bytes


To see kafka files, enter below command:

F:\kafka_2.12-1.0.0\bin\windows>dir kafka*

Output is shown below:

  Directory of F:\kafka_2.12-1.0.0\bin\windows

10/27/2017  09:26 PM               873 kafka-acls.bat
10/27/2017  09:26 PM               885 kafka-broker-api-versions.bat
10/27/2017  09:26 PM               876 kafka-configs.bat
10/27/2017  09:26 PM               925 kafka-console-consumer.bat
10/27/2017  09:26 PM               925 kafka-console-producer.bat
10/27/2017  09:26 PM               883 kafka-consumer-groups.bat
10/27/2017  09:26 PM               884 kafka-consumer-offset-checker.bat
10/27/2017  09:26 PM               938 kafka-consumer-perf-test.bat
10/27/2017  09:26 PM               874 kafka-mirror-maker.bat
10/27/2017  09:26 PM               900 kafka-preferred-replica-election.bat
10/27/2017  09:26 PM               940 kafka-producer-perf-test.bat
10/27/2017  09:26 PM               888 kafka-reassign-partitions.bat
10/27/2017  09:26 PM               880 kafka-replay-log-producer.bat
10/27/2017  09:26 PM               886 kafka-replica-verification.bat
10/27/2017  09:26 PM             5,276 kafka-run-class.bat
10/27/2017  09:26 PM             1,377 kafka-server-start.bat
10/27/2017  09:26 PM               997 kafka-server-stop.bat
10/27/2017  09:26 PM               882 kafka-simple-consumer-shell.bat
10/27/2017  09:26 PM               875 kafka-topics.bat
              19 File(s)         21,964 bytes


This concludes the first post on Apache Kafka ...

Sunday, 21 January 2018

Apache Flume - II

In the earlier post, we introduced Apache Flume that is useful for migrating logs into HDFS. In this post, we continue to share more details on Apache Flume. More details on Apache Flume can be found here. For all the work on Flume in this post, we will use the Cloudera sandbox, Cloudera QuickStart VM 5.12

We have already prepared the .conf file and it is located on Desktop. Click anywhere on Desktop in virtual machine, right click  and click on Open in Terminal to start the terminal window in the virtual machine and run the following command:

flume-ng version

This returns below results:

[cloudera@quickstart Desktop]$ flume-ng version
Flume 1.6.0-cdh5.12.0
Source code repository: https://git-wip-us.apache.org/repos/asf/flume.git
Revision: 4d37abdc65a53a0af1246de51bdcf1d8557669eb
Compiled by jenkins on Thu Jun 29 04:37:39 PDT 2017
From source with checksum af8d398eddf3e3b4ddbada14895722ac


To see help for flume, run below command:

flume-ng help

This returns below results:

[cloudera@quickstart Desktop]$ flume-ng help
Usage: /usr/lib/flume-ng/bin/flume-ng <command> [options]...

commands:
  help                      display this help text
  agent                     run a Flume agent
  avro-client               run an avro Flume client
  version                   show Flume version info

global options:
  --conf,-c <conf>          use configs in <conf> directory
  --classpath,-C <cp>       append to the classpath
  --dryrun,-d               do not actually start Flume, just print the command
  --plugins-path <dirs>     colon-separated list of plugins.d directories. See the
                            plugins.d section in the user guide for more details.
                            Default: $FLUME_HOME/plugins.d
  -Dproperty=value          sets a Java system property value
  -Xproperty=value          sets a Java -X option

agent options:
  --name,-n <name>          the name of this agent (required)
  --conf-file,-f <file>     specify a config file (required if -z missing)
  --zkConnString,-z <str>   specify the ZooKeeper connection to use (required if -f missing)
  --zkBasePath,-p <path>    specify the base path in ZooKeeper for agent configs
  --no-reload-conf          do not reload config file if changed
  --help,-h                 display help text

avro-client options:
  --rpcProps,-P <file>   RPC client properties file with server connection params
  --host,-H <host>       hostname to which events will be sent
  --port,-p <port>       port of the avro source
  --dirname <dir>        directory to stream to avro source
  --filename,-F <file>   text file to stream to avro source (default: std input)
  --headerFile,-R <file> File containing event headers as key/value pairs on each new line
  --help,-h              display help text

  Either --rpcProps or both --host and --port must be specified.

Note that if <conf> directory is specified, then it is always included first
in the classpath.


To invoke the Flume Agent in a dry run, let us run below command:

flume-ng agent -f Flume_Agent1.conf -n Flume_Agent1 -Dflume.root.logger=DEBUG,console -d

-f is a place holder for the file name
-n is name of Flume agent
-d indicates that this command is a dry run
-D is for setting Java system properties. Here, flume.root.logger is set to DEBUG and output directed to console

The output is not shown for the sake of brevity. But, it ends with the following lines:

apache.flume.node.Application -f Flume_Agent1.conf -n Flume_Agent1
+ exit 0


Now let us run the same command but without the -d:

flume-ng agent -f Flume_Agent1.conf -n Flume_Agent1 -Dflume.root.logger=DEBUG,console

The output is not shown for the sake of brevity. But, last few lines are shown below:

18/01/21 08:28:20 INFO node.AbstractConfigurationProvider: Creating channels
18/01/21 08:28:20 INFO channel.DefaultChannelFactory: Creating instance of channel memory_channel type memory
18/01/21 08:28:20 INFO node.AbstractConfigurationProvider: Created channel memory_channel
18/01/21 08:28:20 INFO source.DefaultSourceFactory: Creating instance of source netcat_source, type netcat
18/01/21 08:28:20 INFO sink.DefaultSinkFactory: Creating instance of sink: hdfs_sink, type: hdfs
18/01/21 08:28:20 INFO node.AbstractConfigurationProvider: Channel memory_channel connected to [netcat_source, hdfs_sink]
18/01/21 08:28:20 INFO node.Application: Starting new configuration:{ sourceRunners:{netcat_source=EventDrivenSourceRunner: { source:org.apache.flume.source.NetcatSource{name:netcat_source,state:IDLE} }} sinkRunners:{hdfs_sink=SinkRunner: { policy:org.apache.flume.sink.DefaultSinkProcessor@71060c3e counterGroup:{ name:null counters:{} } }} channels:{memory_channel=org.apache.flume.channel.MemoryChannel{name: memory_channel}} }
18/01/21 08:28:20 INFO node.Application: Starting Channel memory_channel
18/01/21 08:28:20 INFO instrumentation.MonitoredCounterGroup: Monitored counter group for type: CHANNEL, name: memory_channel: Successfully registered new MBean.
18/01/21 08:28:20 INFO instrumentation.MonitoredCounterGroup: Component type: CHANNEL, name: memory_channel started
18/01/21 08:28:20 INFO node.Application: Starting Sink hdfs_sink
18/01/21 08:28:20 INFO node.Application: Starting Source netcat_source
18/01/21 08:28:20 INFO source.NetcatSource: Source starting
18/01/21 08:28:20 INFO instrumentation.MonitoredCounterGroup: Monitored counter group for type: SINK, name: hdfs_sink: Successfully registered new MBean.
18/01/21 08:28:20 INFO instrumentation.MonitoredCounterGroup: Component type: SINK, name: hdfs_sink started
18/01/21 08:28:20 INFO source.NetcatSource: Created serverSocket:sun.nio.ch.ServerSocketChannelImpl[/127.0.0.1:55555]


Note that all Flume components have been created as per the .conf file and the agent is listening on 127.0.0.1:55555

Open a second terminal window and run below command:

echo 'Hello, Flume!' | nc localhost 55555

Netcat connects to port 55555 on localhost and sends the Hello string to it. It then prints the response

This returns below results:

[cloudera@quickstart Desktop]$ echo 'Hello, Flume!' | nc localhost 55555
OK


We see an update on the first terminal window and below lines have been added:

18/01/21 08:49:54 INFO hdfs.HDFSDataStream: Serializer = TEXT, UseRawLocalFileSystem = false
18/01/21 08:49:54 INFO hdfs.BucketWriter: Creating hdfs://localhost:8020/user/cloudera/flume/events/FlumeData.1516553394580.log


When we check the directory /user/cloudera/flume/events/ directory, we see the file that has been created:











Contents of the file is shown below:














Let us run below command:

echo -e '\n Apache Flume: \n\n\tHello, \n\tFlume!' | nc localhost 55555
 

This gets appended to the existing file:














Let us delete this file and  now pass data form a file called employees.csv that was created in earlier posts.

head -n 5 employees.csv | nc localhost 55555

This will transmit the first 5 lines of employees.csv to the port on which Flume is listening

The contents of the file is shown below:











Now, stop the agent on the first terminal by using CTRL+C. Update the Flume_Agent1.conf file to set two new properties as shown below:

# Below lines describe the sink properties
Flume_Agent1.sinks.hdfs_sink.type      = hdfs
Flume_Agent1.sinks.hdfs_sink.hdfs.path = hdfs://localhost:8020/user/cloudera/flume/events
Flume_Agent1.sinks.hdfs_sink.hdfs.inUseSuffix = .log
Flume_Agent1.sinks.hdfs_sink.hdfs.rollInterval = 0
Flume_Agent1.sinks.hdfs_sink.hdfs.rollSize = 1048576
Flume_Agent1.sinks.hdfs_sink.hdfs.rollCount = 200
Flume_Agent1.sinks.hdfs_sink.hdfs.writeFormat = Text
Flume_Agent1.sinks.hdfs_sink.hdfs.fileType = DataStream

hdfs.rollSize is the file size to trigger roll, in bytes. hdfs.rollCount is number of events written to file before it rolled. We can manipulate these properties to reduce number of files created in HDFS. In our case, setting these parameters will result only in one target file for the single source file, employees_file.json. Note that employees_file.json has been created in earlier posts

Now, start the Flume agent once again in the first terminal using below command:

flume-ng agent -f Flume_Agent1.conf -n Flume_Agent1 -Dflume.root.logger=DEBUG,console -d

In the second terminal, type the below command:

cat ./employees_file.json | nc localhost 55555

Then, check for the single file created in /user/cloudera/flume/events:

 


 







You may stop the Flume agent by using CTRL+C on the first terminal window.

This concludes the discussion on Apache Flume