docker run hello-world

Virtualization is the latest Trend and it’s happening everywhere. We started with virtualising hardware and soon realised its over-kill. Realisation is the starting of change. It resulted in a light weight version of virtualization: Linux-Containers or LXC . They are getting adopted Industry wide.

LXC is the solution but what is the tool!!!

One of the most accepted tool is Docker

LXC makes use of the kernel functionalities of cgroup and kernel-namespace. It virtualises at the operating system level and makes it less costlier than its predecessor.

So let’s try setting-up docker and run hello-world, our very old custom..

fyi: Docker makes use of virtualbox. For OSX you may download the package (.pkg) from boot2docker/osx-installer and double-clicking it installs both virtualbox and docker. For other OS/platforms, you may follow instructions from docker-installation-guide.

Once the installation is complete, use splotligt (⌘-Space bar) to open boot2docker.

It opens terminal and runs the initialisation steps and generates encryption keys.

Screen Shot 2015-07-15 at 10.21.51 pm

The terminal is left to you after that.

Lets spin up the VM now.

boot2docker start

Display the docker environment variables to see if the certificate path are set right.

boot2docker shellinit

`To set the environment variables displayed with the above command, run the above command with ‘eval’

eval "$(boot2docker shellinit)" 
or 
$(boot2docker shellinit)

We are ready for the final run..

boot2docker run hello-world

You should now be seeing the output of hello-world.

Screen Shot 2015-07-15 at 10.45.51 pm

 

If things didn’t go well and you want to start again deleting the current vm, run the below set of commands in order.

boot2docker delete
boot2docker init
boot2docker start
$(boot2docker shellinit)
boot2docker run hello-world

apachectl status – How to solve lynx: command not found

apachectl status” will not work if you don’t have lynx ; text-based web browser.

You realize that when you get below message while using the command.

Error
bin/apachectl: line 95: lynx: command not found

Install the lynx and tell it to Apache httpd, he will surely understand.

Download the lynx from here. Change your working directory to the extracted folder and run the command:

./configure --prefix=<path-to-install-lynx>
make
make install

During lynx installation, it may stop with an error:

configure: error: No curses header-files found

Run the below command before proceeding:

sudo yum search ncurses-devel

Now it’s time to tell httpd about lynx.

In apachectl file (either in bin or conf directory), change the line starting with LYNX=”lynx -dump” to LYNX=”<lynx-installed-path>/lynx -dump”

apachectl status will start working..

Shared folder for Fedora VM in VirtualBox

Hi,

I found a little hard to setup a shared folder for my VMs. So thought of sharing it..

So, assuming you already have your host machine, VirtualBox installed on it and a VM running Fedora (any linux), there we go..

Highlight your VM in VirtualBox window.

Screen Shot 2015-03-17 at 3.40.41 pmYes, it is powered off. Bring up the settings window for the VM clicking the below icon.

Screen Shot 2015-03-17 at 3.41.02 pmChoose the “Shared Folders” tab and you will see the list of folders shared with VM.Screen Shot 2015-03-17 at 3.41.22 pmClick on the plus sign you see on the left side and you get another window like the one below.

Screen Shot 2015-03-17 at 3.41.44 pmYou may choose the folder of the host machine you want to share and tick the “Auto-mount” option. Click OK.

Screen Shot 2015-03-17 at 4.12.42 pm

The folder you chose to share is now visible and we are done with the VirtualBox settings. Click OK to come out of it.

Screen Shot 2015-03-17 at 4.13.05 pm

Now boot up the VM. We need to install a few packages in Fedora for this. You may use below command to install the same.

Screen Shot 2015-03-17 at 5.11.50 pmThis will install latest gcc and kernel-devel packages. Guest addition may get arrogant, at times and gives error that it can’t find a particular version of kernel-devel. I will explain how to solve that later.

Now we can install “Guest Addition”

Click on the “Devices” menu and select the below highlighted option.Screen Shot 2015-03-17 at 4.15.35 pmSome OS automatically run the autorun script from CD. Otherwise open a file-browser and open the CD contents. You will see “autorun.sh” file there. Drag and drop it to Terminal. It will first authenticate you and start installing “Guest Addition”.

Screen Shot 2015-03-17 at 4.59.33 pmScreen Shot 2015-03-17 at 4.53.26 pm

You will get below output 99% of the times and that means just a reboot and you have a host-folder available in VM.

Screen Shot 2015-03-17 at 5.26.14 pm

The shared folder will be auto-mounted in /media.

Screen Shot 2015-03-17 at 5.30.02 pmThe 1% I left earlier is the case when “Guest Addition” fails to install with an error about the kernel-devel version. You may get below screen in such cases.

Screen Shot 2015-03-17 at 4.54.16 pmIn such cases you get a command from the above output.

yum install kernel-devel-3.17.4-301.fc21.x86_64

Just run the below part out of it and do the “Guest Addition” installation again and you are good to go..

yum install kernel-devel-3.17.4

Now let me take you through another issue you may face. Your folder will get listed in /media. But you may not have permission to open it. In my case, “Shared” is the shared-folder. /media/sf_Shared is the path in VM where it is mounted.

ls /media/sf_Shared

The above command will give an output like this:Screen Shot 2015-03-18 at 9.48.20 pm

This is because of the difference of UID in host and VM machines.

Screen Shot 2015-03-18 at 9.24.30 pm

The easiest way to sort this out is to add the user account to vboxsf.

usermod -a -G vboxsf

I went for a reboot (of VM) after that and things worked well.

May be you want to do this too.

Create a link in your home directory to access the shared directory mounted in /media. Make sure your home directory does not have “Shared” folder already.

ln -s /media/sf_Shared ~/Shared

So now you may use ~/Shared as your window to the host-machine..

Regular Expression in Python: Greedy match

When you use re.findall(“(.*):” to get the strings ending with full-colon(:), you may not always get the expected result if your string has multiple full-colons. Lets run the command before we talk.

Concentrate on the commands put inside single colon. (You can neglect the rest as it is part of my effort to avoid creating a python file for running this code)

Screen Shot 2014-10-15 at 6.12.15 PMOutput:Screen Shot 2014-10-15 at 6.12.21 PM

What happened here is python did a greedy search and found maximum string ending with a full-colon. If that is what you desired, stop reading further.. 🙂

If you expected a list of all the strings ending with full-colon, change your command to re.findall(“(.*?):”

As you can see, I added a question mark which will force python to avoid greedy approach.

Before we part, lets make sure python is ok with this change..

 

Screen Shot 2014-10-15 at 6.11.40 PM

Output:

Screen Shot 2014-10-15 at 6.12.00 PMLOVE YOU PYTHON…

C++ build tool: boost bjam intro

Reference Material : HERE

Source code (hello_sree.cc):

Screen Shot 2014-02-26 at 2.56.26 PM

build file (jamroot.jam or Jamroot): Screen Shot 2014-02-26 at 7.00.22 PM

Now in terminal, change the present working directory to the folder where the code and build-file resides. Run any of the below commands:

Screen Shot 2014-02-26 at 7.01.05 PMORScreen Shot 2014-02-26 at 7.00.45 PMORScreen Shot 2014-02-26 at 7.01.52 PMORScreen Shot 2014-02-26 at 7.03.09 PM

Ensure you have a space between “hello_sree.cc” and “;” in the build file. Otherwise you will get the below error:Screen Shot 2014-02-26 at 7.03.23 PM

Screen Shot 2014-02-26 at 7.03.33 PM

You will get this message at the successful run:Screen Shot 2014-02-26 at 7.04.01 PMYou will see a bin folder with a hierarchy of folders and executable file created as part of successful build of our program

ActiveMQ Producer and Consumer in Java

Use this post as a reference for those who work with Apache ActiveMQ middle-ware.

You can download the needed ActiveMQ release from here.

Use this link to get through the installation, configuration and starting of ActiveMQ: Getting Started

You should have Java installed in your machine.I am using ActiveMQ 5.9.0.

Once you bring up the ActiveMQ instance, provided you left all the configurations as default,ActiveMQ will support TCP connections at port 61616. We are going to make use of this port to make our Producer and Consumer classes connect to ActiveMQ.

Disclaimer: ActiveMQ instance and Producer and Consumer programs run on the same machine. Therefore programs can use the URL tcp://localhost:61616 to connect to the ActiveMQ instance.

Producer Class is nothing but a java class which will connect to ActiveMQ and send a message to it specifying the queue to which the message should be en-queued.

Consumer Class is the one which connects to ActiveMQ to retrieve a message from a particular queue.

Lets get to the code now. I used Eclipse IDE to create this java project.
Producer Class(AMQProducer):

import java.sql.Timestamp;
import java.util.Date;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;

public class AMQProducer implements Runnable{
    // Use the same factory for all the producer threads.
    static ActiveMQConnectionFactory activeMQConnectionFactory = 
            new ActiveMQConnectionFactory("tcp://localhost:61616");
    @Override
    public void run() {
        try {
            // Create a JMS connection from the ActiveMQ server
            Connection connection = activeMQConnectionFactory.createConnection();
            connection.start();

            // Create a session to send message
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // destination represents the message queue to which the message is en-queued
            Destination destination = session.createQueue("HelloMoto");

            // MessageProducer is used to send messages
            // Refer http://docs.oracle.com/javaee/1.4/api/javax/jms/MessageProducer.html for more
            MessageProducer messageProducer = session.createProducer(destination);

            // Sets the producer's default delivery mode. 
            messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            // Message defines the message header and the acknowledge method used for all JMS messages
            String text = "Hello Motorola from producer " + Thread.currentThread().hashCode() + "..."
            + new Timestamp((new Date()).getTime());
            Message message = session.createTextMessage(text);

            messageProducer.send(message);

            System.out.println("Producer Thread("+Thread.currentThread().hashCode()+
                    ") : Sent \'" + text + "\'");

            // Clean up 
            messageProducer.close();
            session.close();    
            connection.close();

        }
        catch (Exception e) {
            System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+") Exception occured.");
        }
    }    
}

Consumer Class(AMQConsumer.java):

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;
public class AMQConsumer implements Runnable, ExceptionListener  {
	// Use the same factory for all the consumer threads.
	static ActiveMQConnectionFactory activeMQConnectionFactory = 
			new ActiveMQConnectionFactory("tcp://localhost:61616");

	@Override
	public void run() {
		try {
			// Create a JMS connection from the ActiveMQ server
			Connection connection = activeMQConnectionFactory.createConnection();
			connection.setExceptionListener(this); // override "void onException(JMSException arg0)" method
			connection.start();

			// Create a session to receive message
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			Destination destination = session.createQueue("HelloMoto");

			// MessageConsumer is used to receive messages
			// Refer http://docs.oracle.com/javaee/1.4/api/javax/jms/MessageConsumer.html for more
			MessageConsumer messageConsumer = session.createConsumer(destination);

			System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+") : Waiting");

			// receive(long timeout) - Receives the next message that arrives within the specified
			// timeout interval
			Message message = messageConsumer.receive(10000);

			// if the received message is text message, display it on console
			if (message instanceof TextMessage ) {
				TextMessage textMessage = (TextMessage)message;
				System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+ 
						") : Recieved \'" + textMessage.getText() + "\'");
			} else {
				System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+
						") : Dont have any message to display");
			}

			// Clean up
			messageConsumer.close();
			session.close();
			connection.close();

		} catch (Exception e) {
			System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+") Exception occured.");
		}		
	}

	// If a JMS provider detects a serious problem with a connection, it informs the connection's
	// ExceptionListener,
	@Override
	public void onException(JMSException arg0) {
		System.out.println("Consumer Thread("+Thread.currentThread().hashCode()+") JMS Exception occured.  "
				+ "Shutting down client.");
	}
}

Main Class(AMQMain):

import org.sree.activemqeg.AMQConsumer;
import org.sree.activemqeg.AMQProducer;

public class AMQMain {

	public static void main(String[] args) throws InterruptedException {
		(new Thread(new AMQProducer())).start();
		(new Thread(new AMQConsumer())).start();
		(new Thread(new AMQConsumer())).start();
		(new Thread(new AMQConsumer())).start();
		Thread.sleep(1000);
		(new Thread(new AMQProducer())).start();
		(new Thread(new AMQProducer())).start();
	}
}

Output:

Apache ActiveMQ Java Producer Client OutputNeglect the log4j warnings for the time being…

You can analyze the statistics of the various queues of ActiveMQ from a browser with the URL http://localhost:8161 (replace ‘localhost’ with the IP of the machine if ActiveMQ is in a different system). Have a look at the queue we created with our program.

ActiveMQ queue screenshot

Meet you in my next post “ActiveMQ Producer and Client in Java using Spring Framework” which will make things more configurable and professional. 😉

Pythonize : Classes in Python

This series of articles, “Pythonize” will serve as an aid for python beginners. In this chapter I will try to explain all about python classes. In this series I will let python code talk to you more than me.

A few interesting things about python for you: Internet giants, Google and Yahoo, maintain a large code-base in python and promotes python to a large extent. Google apps can now be developed in python using the python APIs provided by Google. Python is famous for more functionality in less time being a scripting language and at the same time enabling OOP(Object Oriented Programming). It’s rich with libraries and online help. You can access

 

Python Class:

Class is a template or prototype that defines the fields and methods common to all objects created with this class. Classes in python starts with the keyword ‘class’ followed by the class name and then an optional set of classes separated with comma inside parenthesis, which will be inherited into your class depth-first and left-to-right order. It is then ended with a full-colon and all the indented block of statements just after that forms the body of the class. Note: Python keywords are case-sensitive. Stick with small letters. Below code won’t compile.

E.g.

Image FYI: pass is the keyword used to avoid error and it represents an empty block here. Variables: Data type of python variables is set based on the value assigned to it. Some valid variable assigning:
E.g.

Image

Hope you noted that I have reassigned ‘variable1’ from number to string without any extra code and the program worked fine. That is the extent of freedom python gives you. There is no keyword to define the scope of variables in class and all your usual variables declared inside class will be publicly accessible. Let try this with an example.

E.g.

6a Output: 6 Recent python versions came up with a solution to declare private variables. You just need to precede your variables with two underscores (__) and magic: it became private. Such private attributes are declared outside __init__ function for data hiding. Lets experiment this with a few lines of code.

E.g.

7a Output:

7

You may doubt that this is because I tried to print the variable ‘name’ where the class variable is “__name”. Lets clear your doubt.

E.g.

8a Output: 8

Here we tried to print the same variable name. Since preceding class-variables with two underscores make it private, we got an ‘AttributeError’. Python protects such private members internally by altering its name to contain the class name and we can access such members by following the template:

<objectName>._<className>__<attributeName>

Here our object name is prs, class name is Person and the variable is __name, so as per our assumption we should get the variable value by printing ‘prs._Person__name’

E.g.

8-1a Output: Note: Use “self.” with variable names to refer to instance variables and class-name followed by period (.) and then variable name to refer to class variables. Otherwise python will consider it as a global name and raise an error or give unpredictable outputs if a global variable with similar name exists. Lets have one example of class variables and then go to next topic:

E.g.

Image Output: 10 Here, you can see that by changing company name of emp2, it got reflected in emp1 as well i.e. emp1 and emp2 points to a single memory and such variables are technically called as class variables; one single memory for all the classes.

 

Class functions:

Functions of class decide the behavior of the class. They act as an interface to the outside world. Take a look at a sample class with a function ‘print_emp_details’.

E.g.

9a

Output: 4

Constructor:

Object Oriented Programmers might already know the role of constructor in a class. For those who don’t, let me explain. Constructor is the function that gets automatically invoked at the time of object-creation which is usually made use of for resource allocation. Python differs a bit from other OOP languages like java or C++ in constructor-name and it’s invocation. In python,

  • constructor of parent classes will not get invoked at the class of object creation of child class.
  • constructor function in python is always __init__().

E.g.

Image

You might be wondering about ‘self’ in __init__ function. In python, you will see this variable as the first argument in all the class functions without which the execution will fail. ‘self’ is not a keyword but instance of a class. You can use any other name for this parameter but it’s part of coding standard, which makes your code readable and easy to understand for other programmers. Lets stick to that standard.

E.g.

Image

Output: 1

A blank parameter list will raise a TypeError:

E.g. Image Output:

3

We have seen only constructors that don’t take any parameters so far. Now lets take a peek into parameterized constructors. As you guessed, the parameters of the constructor follow ‘self’.

E.g. 4a

Here name and hobby are the arguments and during object-creation we passed the arguments string “Sreejith” and “programming” as name and hobby to the constructor. One thing to note is that, with this class you won’t be able to create an object without any parameters. You will get the following error:

E.g.

4b

Output:

4c

Lets see a work around for that. Here we will assign a default value for the constructor variables and thereby the constructor assumes the default value if not explicitly specified at the time of object creation.

E.g.

4d Output: 4e

 

Destructor:

E.g.

11

Output: 11

 

Other base methods you can overload in your class:

  • __repr__(self)
    • To represent the object in evaluatable string
    • E.g.: repr(obj)
  • __str__(self)
    • To represent the object in string
    • E.g.: str(obj)
  • __cmp__(self, obj1)
    • For comparing with another object
    • E.g.: cmp(obj, obj1)

Inheritance:

Lets straight away get into a python code that successfully uses inheritance to reuse code and at the same time overrides needed functions.

E.g.

Image Output: 12 Here we override the print_name() function in Child and GrandChild class but uses the same smile() function as such. Functions are searched in the following hierarchy:

  1. Derived class
  2. Base class in the order of depth first and then left-to-right.

There are two functions which comes handy with class inheritance:

  • issubclass()
    • Returns a boolean value based on if the first parameter is a sub-class of the second parameter.
    • E.g.: issubclass( subclass1, superclass1 )
  • isinstance
    • Returns a boolean value based on if the first parameter is an object of second parameter.
    • E.g.: isinstance( object1, class1 )

Thus we have come to the end of this chapter. Lets recall what we have learned from this chapter. We learned

  1. Basic syntax of class
  2. Variables; How to make variables private; Class variables and Instance variables
  3. Class Functions/Methods
  4. Inheritance; Function overriding

Meet you next time..