Archive for the ‘linux’ Category

Installing and configuring vsftpd

To perform ftp file transaction it is required to install a ftp server and configure it appropriately. The vsftpd server is used in this scenario.

First install the vsftpd server – sudo apt-get install vsftpd

Configure the vsftpd server by editing the /etc/vsftpd.conf file

listen=YES

anonymous_enable=NO

local_enable=YES

write_enable=YES

anon_mkdir_write_enable=NO

dirmessage_enable=YES

use_localtime=YES

xferlog_enable=YES

secure_chroot_dir=/var/run/vsftpd/empty

pam_service_name=vsftpd

rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem

rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key

pasv_enable=YES

pasv_min_port=11810

pasv_max_port=11819

pasv_address=<public external ip address of the machined where vsftpd is installed>

 

Open the port ranges 20-21 and 11810-11819 of the machine

Finally restart the vsftp server – sudo service vsftpd restart.

 

FTP user accounts

I created  two user accounts to send and receive files with login disabled (This is not required)

sudo adduser ftpuser1 –disabled-login

sudo adduser ftpuser2 –disabled-login

 

Create the following directory structure

/home/ftpuser1/files/in      /home/ftpuser1/files/out

/home/ftpuser2/files/in      /home/ftpuser2/files/out

 

Change the change file owner to respective users

chown -R ftpuser1 /home/ftpuser1/files

chown -R ftpuser2 /home/ftpuser2/files

Advertisements

Configure Apache2 and NginX as Content based router

Content based routing is to send received request to particular destination depending on the request content. The configuration bellow will be using a custom HTTP header as the content to decide the destination

Apache2

Create a file named a2cbr in /etc/apache2/sites-available, and copy the following content to a file named a2cbr

<VirtualHost *:10000>
    ServerName localhost
    ProxyRequests Off
    RewriteEngine On

    <Directory>
        AllowOverride All
        <Limit GET HEAD POST PUT DELETE OPTIONS>
        Order Allow,Deny
        Allow from all
        </Limit>
    </Directory>

    RewriteCond %{HTTP:routing} xadmin
    RewriteRule ^/a2cbr(.*) http://localhost:9000/service/EchoService [P]
</VirtualHost>

NginX

Create a file named nginxcbr in /etc/nginx/sites-available, and copy the following content to a file named nginxcbr

server {
   listen *:15000;
   server_name localhost;

   location  / {
       if ($http_routing ~ 'xadmin') {
          rewrite ^/nginxcbr(.*) /service/EchoService;
           proxy_pass http://localhost:9000;
       }
    }
}
<pre>

JMX tips

I’m hoping to continuously update this post as I come across important facts while developing JMX applications. So here we go…..

  1.  Do not pass complex structures to the JMX connection. JMX finds it difficult to render complex objects.
    e.g: Last week I was trying to pass a hash map which stored several other hash maps as its values, using MXBeans (The purpose was to add custom statistic support to UlraESB). 

    HashMap<String, HashMap<String, Integer>> statisticMap  = new HashMap<String, HashMap<String, Integer>>();
    

    The  statisticMap  was directly passed to the JMX connection. However the beans were created and visible through  the jconsole, but data wasn’t rendered. Then I tried out the following

    List<HashMap<String, Integer>> statisticList  = new ArrayList<HashMap<String, Integer>>();
    

    The list was directly passed to the connection and it worked like magic. Data were properly rendered. The only difference between these is that first design is “Maps in a Map” and the second is “Maps in a List”. I cannot explain why this happens… Please share your thoughts on this

  2. The objects which are passes to the JMX connection should be Serializable. If a static object is passed then the JMX connection would not be able to expose the data of that static object, since  static objects are not serializable. (Serialization can be only applied to objects and static variables does not belong to individual instances, they are class variables)

How TO KILL an ANT

Well this is nothing related my tech attempts, but I found this story really funny and thought of re-posting it on my blog . Also reminded me of my school days, where we  invented new formulas and theories just to get 15 marks 😀  The moral of this story is nothing but the absolute truth.

So here we go “How to kILL an ant” 😉
Q: How to Kill an Ant?
Asked in exam for 15 marks..
Student’s Answer:
Mix Chilli Powder with Sugar & keep it outside the Ant’s Hole.
After eating, Ant will search for some water near a water tank.
Push ant in to it. Now ant will go to dry itself near fire.
When it reaches fire, put a bomb into the fire.
Then admit wounded ant in ICU.
Remove oxygen mask from its mouth and kill the ant.

MORAL: Don’t play with students they can do anything for 15 marks.

Writing sample configurations for Apache ServiceMix

ServiceMix is an open source ESB by Apache Software Foundtion. This post will provide a brief description on creating new sample configurations and running them with ServiceMix

I have created sample configurations for five different scenarios.

The Direct Proxy

This is a basic scenario where a client issues a POST request and the ESB sends request to a specified service without any changes to the original message.
This cofiguration needs a http-consumer and a http-provider.

Steps to create the project

  • Create a folder and name it “direct-proxy”
  • Add a pom.xml file to the folder with following configuration
<?xml version="1.0" encoding="utf-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>org.apache.servicemix.http.proxy</groupId>
        <artifactId>parent</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>pom</packaging>
        <name>SMX-HTTP :: DirectProxy</name>
        <url>http://servicemix.apache.org</url>
     </project>
  • cd direct-proxy
  • Create a comsumer service unit
mvn archetype:create -DarchetypeArtifactId=servicemix-http-consumer-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=proxy-consumer-su
  • Create a provider service unit
mvn archetype:create -DarchetypeArtifactId=servicemix-http-provider-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=proxy-provider-su
  • Create the Service Assembly
mvn archetype:create -DarchetypeArtifactId=servicemix-service-assembly -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=proxy-sa

After executing the above commands you will find three folders created in the ‘direct-proxy’ folder.

  • Navigate to the ‘proxy-sa’ folder and add the created service units as dependencies to the pom.xml file.

e.g ;

<dependencies>
    <dependency>
         <groupId>org.apache.servicemix.http.proxy</groupId>
         <artifactId>proxy-provider-su</artifactId>
         <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.apache.servicemix.http.proxy</groupId>
        <artifactId>proxy-consumer-su</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>
  • Then navigate to ‘proxy-consumer-su’ and ‘proxy-provider-su’ and check if the generated pom.xml files have specified the componentName. If not specify the component name as follows.
<properties>
    <componentName>servicemix-http</componentName>
</properties>

Now you are ready to deploy the configuration.

  • Do the necessary changes to the xbean files in ‘proxy-consumer-su’ and ‘proxy-provider-su’.

{source}

  • Start servicemix –
    1. cd <servicemix-home>/bin
    2. ./servicemix
  • Build the project
    1. cd direct-proxy
    2. mvn clean install

The project should build without any errors

  • Navigate to direct-proxy/proxy-sa/target. Copy the zip file and paste it to <servicemix-home>/deploy folder.

The Content Based Router

The content based router will evaluate the POST request issued by the client. If the evaluation passes the request is sent to a specified service.
This configuration evaluates the request using xpath. Apache Camel is used to define routes and to perform the xpath evaluation.

Steps to create the project

  •  Create a folder and name it as “router”
  • Add a pom.xml file to the folder with following configuration
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.apache.servicemix.cbr.camel</groupId>
    <artifactId>parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>SMX-CAMEL :: CBRProxy</name>
    <url>http://servicemix.apache.org</url>
</project>
  •  cd router
  • create the ServiceMix Camel service unit
mvn archetype:create -DarchetypeArtifactId=servicemix-camel-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=cbr-camel-su
  • Create a comsumer service unit
mvn archetype:create -DarchetypeArtifactId=servicemix-http-consumer-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=cbr-consumer-su
  • Create a provider service unit
mvn archetype:create -DarchetypeArtifactId=servicemix-http-provider-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=cbr-provider-su
  • Create the Service assembly
mvn archetype:create -DarchetypeArtifactId=servicemix-service-assembly -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=cbr-sa

There will be four folders created inside the ‘router’ folder

  •  Navigate to the ‘cbr-sa’ folder and add the created service units as dependencies to the pom.xml file.(refer the direct proxy)
  • Then navigate to ‘cbr-consumer-su’ and ‘cbr-provider-su’ and check if the generated pom.xml files have specified the componentName. If not, specify the  component name as follows.
<properties>
    <componentName>servicemix-http</componentName>
</properties>

Also check the pom generated in ‘cbr-camel-su’. If the componenName is not specified, if not specify it as follows

<properties>
    <componentName>servicemix-camel</componentName>
</properties>

To get this configuration working I had to replace the following of the pom.xml in cbr-camel-su

<dependency>
    <groupId>org.apache.servicemix</groupId>
    <artifactId>servicemix-camel</artifactId>
    <scope>provided</scope>
</dependency>

with

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-core</artifactId>
    <version>2.8.0</version>
</dependency>

Before this replacement I could not deploy the project due to “Error creating bean with name ‘camel’: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.apache.servicemix.cbr.camel.MyRouteBuilder.from”

Now you are ready to deploy the configuration.

  • Do the necessary changes to the xbean files, camel contex and MyRouteBuilder.

{source}

  • Start servicemix – cd <servicemix-home>/bin

./servicemix

  • Build the project

cd router
mvn clean install
The project should build without any errors

  • Navigate to direct-proxy/proxy-sa/target. Copy the zip file and paste it to <servicemix-home>/deploy folder.

XSLT Transformation

This configuration transforms POST request using a XSLT stylesheet in the ESB, then sends the transformed request to an echo service. The echo service echo backs the received request. The echoed back transformed request is again transformed back to the original state, using another XSLT style sheet and sent back to the client. The Camel pipeline pattern is used for this.

  • Create a folder and name it as “xslt”
  •  add a pom.xml file to the folder with following configuration
 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.adroitlogic.com</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>SMX-CAMEL :: XSLT</name>
<url>http://servicemix.apache.org</url>
</project>

  • cd xslt
  • create the camel service unit
mvn archetype:create -DarchetypeArtifactId=servicemix-camel-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=transform-camel-su
  • create transform-back-xslt-su
mvn archetype:create -DarchetypeArtifactId=servicemix-saxon-xslt-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=transform-back-xslt-su
  • creat transform-xslt-su
mvn archetype:create -DarchetypeArtifactId=servicemix-saxon-xslt-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=transform-xslt-su
  • create transform-xslt-comsumer-su
mvn archetype:create -DarchetypeArtifactId=servicemix-http-consumer-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=transform-xslt-consumer-su
  • create transform-xslt-provider-su
mvn archetype:create -DarchetypeArtifactId=servicemix-http-provider-service-unit -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=transform-xslt-provider-su
  • create the SA
mvn archetype:create -DarchetypeArtifactId=servicemix-service-assembly -DarchetypeGroupId=org.apache.servicemix.tooling -DartifactId=transform-sa

There will be four folders vreated inside the ‘router’ folder

  • Navigate to the ‘cbr-sa’ folder and add the created service units as dependencies to the pom.xml file.

        org.apache.servicemix.xslt.transform
        transform-back-xslt-su
        1.0-SNAPSHOT

        org.apache.servicemix.xslt.transform
        transform-camel-su
        1.0-SNAPSHOT

        org.apache.servicemix.xslt.transform
        transform-xslt-consumer-su
        1.0-SNAPSHOT

        org.apache.servicemix.xslt.transform
        transform-xslt-provider-su
        1.0-SNAPSHOT

        org.apache.servicemix.xslt.transform
        transform-xslt-su
        1.0-SNAPSHOT

  •  Then navigate to ‘transform-xslt-consumer-su’ and ‘transform-xslt-provider-su’ and check if the generated pom.xml files have specified the componentName. If not, specify the component name as follows.
servicemix-http

Check the pom generated in ‘transform-camel-su’. If the componenName is not specified, if not specify it as follows


     servicemix-camel

Check the pom generated in ‘transform-back-xslt-su’ and ‘transform-xslt-su’. If the componenName is not specified, if not specify it as follows


     servicemix-saxon

  • Do the necessary changes to the xbean files, camel contex and MyRouteBuilder.
  • Start servicemix – cd <servicemix-home>/bin

./servicemix

  • Build the project

cd router
mvn clean install
The project should build without any errors

  •  Navigate to direct-proxy/proxy-sa/target. Copy the zip file and paste it to <servicemix-home>/deploy folder.

So this is how you create, build and deploy samples in ServiceMix. However I think the overhead is too much. It is needed to build a project each time a new sample is deployed, unlike in most other ESBs where deployin a new sample is just a matter of creating a sample configuration file and you are up and running 🙂

Zabbix Monitoring via API

A few weeks ago I was asked to implement a feature for the Uconsole, to monitor “UltraESB” artifacts exposed to JMX connection. In today’s post I’ll be explaining the approach that I followed to achieve this task.

You can get an idea how the API works here.

The “item” is the basic element that should be configured to start Zabbix Monitoring. A graph is created with relevance to an item. Each item is uniquely identified by the name given and most importantly by its key. It describes the object to be monitored by the item.

This post will mainly focus on how to work with the zabbix api and how to interact with it. To get a further understanding, refer this link. It also describes how to specify the Zabbix item key for a JMX artifact.

Creating an item via the GUI is pretty easy, but the GUI is not very helpful always. Specially when several number of items and graphs need to be created at one shot. My requirement was the latter one.

Other third party JARs used

Apache Http Client
Jackson Java JSON-processor

The Design

If you went through the zabbix api it is made clear that first a user should get an authentication token to  register  items, graphs and triggers. So first we’ll get authorized.

public String authenticate(String username, String password, String url) {
    this.password = password;
    this.userName = username;
    zabbixApiUrl = url;

    StringBuilder uiConnectMessage = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    sb.append("{\"jsonrpc\":\"2.0\"").
    append(",\"params\":{").
    append("\"user\":\"").append(username).
    append("\",\"password\":\"").append(password).
    append("\"},").
    append("\"method\":\"user.authenticate\",").
    append("\"id\":\"2\"}");

    try {
        HttpResponse response = postAndGet(sb.toString());
        HttpEntity entity = response.getEntity();

        HashMap untyped = mapper.readValue(EntityUtils.toString(entity), HashMap.class);
        auth = untyped.get("result");

        if (auth == null) {
            throw new IllegalArgumentException("Authorization failed to : " + url + ", using username : "               + username);
        }
        uiConnectMessage.append("Successfully connected to the server\n");

    } catch (IOException e) {
        uiConnectMessage.append("Could not connect to the Zabbix Server at : ").
        append(url).append(" Exception : ").append(e.getMessage()).append("\n");
    }
    return uiConnectMessage.toString();
}
    private HttpResponse postAndGet(String request) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(zabbixApiUrl);
        httpPost.setEntity(new StringEntity(request));
        httpPost.addHeader("Content-Type", "application/json-rpc");
        return client.execute(httpPost);
    }

The above method will authenticate you to the zabbix server when the zabbix api url, user name and the password is given.
The received authentication token is stored in the “auth” varible which is declared globally for later uses.  Bellow is a screenshot of the web management console of the UltraESB which invokes the above methods


If you are successfully authenticated to the server, a list of hosts and a list of applications defined for each hosts are  presented. It is important to choose a host and a relevant application to register items. Defining an application is optional, but if you don’t latest data for an item will not be shown on the Zabbix GUI.

These two methods are used to retrieve hosts and applications defined to each hosts. When a host is selected from the drop down menu, the application drop down will show only the applications defined for the selected host.

    private Map<String, String> hostMap = new HashMap<String, String>();
    private Map<String, Map<String, String>> appMap = new HashMap<String, Map<String, String>>();

    private void getHosts() throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("{\"jsonrpc\":\"2.0\",");
        sb.append("\"method\":\"host.get\",");
        sb.append("\"params\":{");
        sb.append("\"output\":\"extend\"},");
        sb.append(" \"auth\":\"").append(auth).append("\",");
        sb.append("  \"id\":2}");

        HttpResponse response = postAndGet(sb.toString());
        HttpEntity entity = response.getEntity();

        JsonNode rootNode = mapper.readValue(EntityUtils.toString(entity), JsonNode.class);
        JsonNode resultNode = rootNode.path("result");
        Iterator hostList = resultNode.getElements();
        while (hostList.hasNext()) {
            JsonNode element = hostList.next();
            hostMap.put(element.findValue("hostid").toString().replaceAll("(\\[|\\]|\")", ""), element.findValue("host")
                .toString().replaceAll("(\\[|\\]|\")", ""));
        }
    }

    private void getApps() throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("{\"jsonrpc\":\"2.0\",");
        sb.append("\"method\":\"application.get\",");
        sb.append("\"params\":{");
        sb.append("\"output\":\"extend\"},");
        sb.append(" \"auth\":\"").append(auth).append("\",");
        sb.append("  \"id\":2}");

        HttpResponse response = postAndGet(sb.toString());
        HttpEntity entity = response.getEntity();

        JsonNode rootNode = mapper.readValue(EntityUtils.toString(entity), JsonNode.class);
        JsonNode resultNode = rootNode.path("result");
        Iterator appList = resultNode.getElements();
        while (appList.hasNext()) {
            JsonNode element = appList.next();
            JsonNode hosts = element.path("hosts");
            Iterator hostList = hosts.getElements();
            while (hostList.hasNext()) {
                JsonNode hostElement = hostList.next();
                String hostID = hostElement.findValue("hostid").toString().replaceAll("(\\[|\\]|\")", "");
                if (hostMap.containsKey(hostID)) {
                    if (appMap.containsKey(hostID)) {
                        appMap.get(hostElement.findValue("hostid").toString().replaceAll("(\\[|\\]|\")", "")).put(element.
                            findValue("name").toString().replaceAll("(\\[|\\]|\")", ""), element.findValue("applicationid").
                            toString().replaceAll("(\\[|\\]|\")", ""));

                    } else {
                        Map apps = new HashMap();
                        apps.put(element.findValue("name").toString().replaceAll("(\\[|\\]|\")", ""), element.
                            findValue("applicationid").toString().replaceAll("(\\[|\\]|\")", ""));
                        appMap.put(hostID, apps);
                    }
                }
            }
        }
    }

Finally when the user chooses the host and the application, the available artifacts are displayed. The user have the will of choosing which artifact is to be monitored.

Several items, graphs and triggers can be created for one type of artifact. For an example, some of the attributes exposed by the JMX connection of an Endpoint will be active address count, failed sending messages, ready address count etc. This program facilitates registration of many attributes for particular endpoint (not only endpoints other artifacts as well).

So how is this done?
I have defined a directory structure as shown in the image bellow

If a user needs to monitor a particular attribute, all what he have to do is to drop in json template file to the relevant folder, and the program will create items or graphs or triggers by reading the template files.
Following is a sample json file stored in the items directory of endpoints

NOTE : If a user checks an artifact and clicks the register button, the program will create items, graphs and triggers for all the json templates saved in the relevant artifact directory. (the Uconsole also provides with the facility of disabling a particular template).

{
"jsonrpc":"2.0",
"method":"item.create",
"params":{
      "description": "$filename$-$id$",
      "key_": "jmx[org.adroitlogic.ultraesb.detail:Type=Endpoints,Name=$id$][Details.activeAddressCount]",
      "hostid": "$hostid$",
      "value_type": 3 ,
      "data_type" : 0,
      "status": 0,
      "applications": ["$app$"]
},
"auth":"$auth$",
"id":2
}

The following method will list all the availble json files in specified artifact directory and loops through each file for manipulation.

     /**
     * Registers configuration elements at the zabbix server.
     *
     * @param category    - the type of the items
     * @param items       - name of the item to be registered
     * @param delExisting - the parameter to determine if the user need to delete the existing items
     * @return String - A String containing information about all unsuccessful operations
     */
public void registerConfigurationElements(String category, String[] items, boolean delExisting) {

    deleteExisting = delExisting;
    final String basePath = "conf" + File.separator + "zabbix" + File.separator;

    // Finding the path to Item templates
    File dirItemPath = new File(basePath + category + File.separator + "items");
    if (!dirItemPath.exists()) {
        throw new IllegalArgumentException("Item template directory for type : " + category + " does not exists");
    }

    File dirItems = new File(dirItemPath.getAbsolutePath());
    for (File file : dirItems.listFiles()) {
        int index = file.getName().lastIndexOf(".");
        String extension = file.getName().substring(index + 1);
        if ("json".equals(extension)) {
            processFile(file.getAbsolutePath(), items,
                file.getName().replaceAll(".json", ""), true);
        }
    }

    //find the path to Trigger templates
    File dirTriggerPath = new File(basePath + category + File.separator + "triggers");
    if (!dirTriggerPath.exists()) {
        throw new IllegalArgumentException("Trigger templates for type: " + category + " does not exists");
    }

    File dirTriggers = new File(dirTriggerPath.getAbsolutePath());
    for (File file : dirTriggers.listFiles()) {
        int index = file.getName().lastIndexOf(".");
        String extension = file.getName().substring(index + 1);
        if ("json".equals(extension)) {
            processFile(file.getAbsolutePath(), items,
                file.getName().replaceAll(".json", ""), false);
        }
     }

    // Finding the path to Graph templates
    File dirGraphPath = new File(basePath + category + File.separator + "graphs");
    if (!dirGraphPath.exists()) {
        throw new IllegalArgumentException("Graph templates directory for type : " + category + " does not exists");
    }

    File dirGraphs = new File(dirGraphPath.getAbsolutePath());
    for (File file : dirGraphs.listFiles()) {
        int index = file.getName().lastIndexOf(".");
        String extension = file.getName().substring(index + 1);
        if ("json".equals(extension)) {
            createGraph(file.getAbsolutePath(), items,
                file.getName().replaceAll(".json", ""));
        }
    }
}

If you carefully went through the json template above json template you would have probably noticed some variables wrapped in dollar ($) sign. These variable are replaced by the program.

Bellow is the createGraph method which is used for creating graphs at the zabbix server, but the method for creating items and triggers is not given as functionality is very much the same. Also I have omitted code lines which re-authenticate a if the zabbix session times out, solely for the purpose of maintaining the simplicity of the post.

    private void createGraph(String path, String items[], String fileName) {

        for (String item : items) {
            String request = readFile(path);
            request = request.replace("$filename$", fileName);
            request = request.replace("$id$", item);
            request = request.replace("$auth$", auth);

            try {
                HashMap requestNode = mapper.readValue(request, HashMap.class);
                ArrayList params = (ArrayList) requestNode.get("params");
                HashMap graphItems = (HashMap) params.get(0);
                ArrayList graphItemsList = (ArrayList) graphItems.get("gitems");
                HashMap itemId = (HashMap) graphItemsList.get(0);
                String itemIdList = (String) itemId.get("itemid");
                itemId.remove("itemid");
                itemId.put("itemid", map.get(itemIdList));
                String reqMssg = mapper.writeValueAsString(requestNode);
                postAndGet(reqMssg);

            } catch (EOFException e) {
                logger.warn("Empty json file at : {} - Exception : {}", path, e);
                uiRegisterElemMessage.append("Empty json file at ").append(path).append(" ").append(e).append("\n");

            } catch (IOException e) {
                logger.warn("Could not create graph for item : {} at path : {}", item, path);
                uiRegisterElemMessage.append("Could not create graph for item ").append(item).append(" at path ").
                    append(path).append("\n");
            }
        }
    }

As you can see working with Zabbix api is not difficult. The tedious part is sending requests to the server and processing received responses.

Running the Zabbix Server

The Zabbix server should be invoked by executing this command “/etc/init.d/zabbix-server start” before you start monitoring . You can check whether the Zabbix server is running from the front end GUI.

How ever if the GUI says “NO” have a look at the zabbix server log file at /var/log/zabbix-server/zabbix_server.log. If the log message some what similar to “Access denied for user ‘zabbix’@’localhost’ (using password: YES)”, there is a conflict between the zabbix database password and the passwords saved in following files.

/etc/zabbix/dbconfig.php

/etc/zabbix/zabbix_server.conf

Make sure that all three passwords are the same. The password for the zabbix database can reset by typing “set password for ‘zabbix’@’localhost’ = PASSWORD(‘yourPassword’); ” on the mysql prompt.

Installing Java manually on Ubuntu

Hello everyone!!!!! This is my very first blog post. Also today marks  a very special day in my academic life. It is the first day of  my  intern ship period  at AdroitLogic, where I was inspired to write this blog 🙂

So I thought of starting off with a very very basic thing. Of course most of you people might have already  done this several times, but still there may be few guys out there struggling to do this, just like I did today 😀

Java can be installed on ubuntu easily using the apt -get install command , but here I’ll be explaining how to install java with  the tarball compressed file (jdk-7u7-linux-x64.tar.gz)file, which can be downloaded from here.

1. Open a terminal and log in as he super user and change the current directory to tmp (this is because all in tmp will be erased in the next system reboot, we will be extracting the bin file into the tmp folder)

sudo su
cd /tmp

2. Change the permission type of the tarball to executable by the owner

chmod +x /home/amindri/Downloads/jdk-7u7-linux-x64.tar.gz

3. Unpack the tar ball file.

tar -zxvf  /home/amindri/Downloads/jdk-7u7-linux-x64.tar.gz

Do a ls -l to see if the bin file is properly extracted

4. Move the extracted file to the desired installation folder. In my case it will be opt

sudo mv jdk1.7.0_07 /opt

5.  Go in to the opt folder and add a symbolic link to the jdk folder.

cd /opt
ln -s jdk1.7.0_07 jdk

6. The .bashrc file should be edited to set the environmental variables. The .bashrc file  can be edited via the vi editor, if you are not very familiar with it just gedit it.

cd or cd ~ (you need to be in here to open the .bashrc file via command line)
gedit .bashrc

7. The file will be displayed. Append these two lines to  the very end of the file

export PATH=/opt/jdk/bin
export JAVA_HOME=/opt/jdk

8. Set the class path –  again gedit the /etc/environment and set the path as follows

export JDK_HOME=”/opt/jdk”

Rather than using apt -get install, this manual installation provides you with the flexibility of choosing the installation folder and  I think it’s quite an exiting procedure.

P.S: The advantage of adding a symbolic link is, when you update the java version, it is not necessary to update all the environmental and path variables. All the variables hold value “jdk”, it is quite sufficient to add just a new symbolic link to the jdk .

So have fun with installing java manually on Ubuntu…….