Friday, October 14, 2011

Installing the mrtg and the auto analyzer script

I want to explain the mrtg installation on Debian from scratch. It might be boring for expert users but anyway this article is said to be effective for beginners. Expert users may jump on text.

Download the last version of Debian for from the URL "http://cdimage.debian.org/debian-cd/6.0.2.1/i386/iso-cd/" and "debian-6.0.2.1-i386-netinst.iso" images. This version is the minimum in size. I selected that version, because I want to see/show all required packages and applications. I have Ubuntu 11.04 and VirtualBox 4.0.4 in my computer. I installed that Debian into the virtual host at VirtualBox with the default (only selected ssh server while installation) installation settings.


apt-get install mrtg


Mrtg is a perl script so the Perl interpreter is required. I'm checking the Perl interpreter:



a) I will need a http server to publish web pages that are generated by the Mrtg script.
b) I will need a php interpreter to analyze html outputs of mrtg script.
c) I will need a mysql database to save some options and data about auto alert generating.

I'm installing apache2, php5 and mysql-server5 for All that requirements;

apt-get install apache2 php5 mysql-server




After than installation, you can see used ports on your linux to check the status of Apache and Mysql services like following image:




You can check the Apache & Php status using the code below:

<?php phpinfo(); ?>


If the file name is "test.php" and path of the directory is "/var/www/", the phpinfo() function should send an output on your browser when you enter the http://youraddress/test.php address. The next step is to test the mysql server and to make a connection between php and mysql servers. You can use the following php script:

<?php
$link = mysql_connect("localhost","root","youPasswordOnPicture")
or die("Error: Can not establish connection to MySQL Server");
?>


If the file name is "testMySQL.php" and path of the directory is "/var/www/", you should not to see nothing on your browser when you enter the http://youraddress/testMySQL.php address. Having a message "Error: Can not establish connection to MySQL Server" means the database server connection is unsuccessful.

If have reached this line without any error/problem, we can jump to mrtg part again: The mrtg script queries your active network devices (routers, switches, firewalls etc.) via SNMP protocol. So you have to configure the snmp settings on your active network devices. I will add a basic snmp setup for some mostly used devices.

You can use following command to generate a mrtg configuration file.

cfgmaker CommunityString@deviceA.of.Ip.Address --output deviceA.cfg


This command creates a file with name "deviceA.cfg". We have to edit some lines in this file like following:

# Created by 
# /usr/bin/cfgmaker CmmntyString@172.28.201.10


### Global Config Options

# for UNIX
WorkDir: /var/www/html/mrtgGraphics/relatedDevice/

# or for NT
# WorkDir: c:\mrtgdata

### Global Defaults

# to get bits instead of bytes and graphs growing to the right
Options[_]: growright, bits

EnableIPv6: no
...
...
..


If you use MS Windows Operation System, simply uncomment the line "WorkDir: c:\mrtgdata" and put a '#' char to comment the line "WorkDir: /var/www/html/mrtgGraphics/relatedDevice/". We are capable to define directions of graphics and unit types of data. Possible choices for bit and byte for unit and frowright and growleft for direction. (Bunun frowright olduğuna emin misin? flowright olabilir mi?)

Each single interface is defined in this configuration file like following:

Target[3661-fasteth00-systemsegment]: 2:CmmntyString@172.28.201.10:
SetEnv[3661-fasteth00-systemsegment]: MRTG_INT_IP="172.28.201.10" MRTG_INT_DESCR="FastEthernet0/0"
MaxBytes[3661-fasteth00-systemsegment]: 12500000
Title[3661-fasteth00-systemsegment]: Traffic Analysis for 3661-FastEthernet0/0 SystemSegment
PageTop[3661-fasteth00-systemsegment]: <h1>Traffic Analysis for 3661-FastEthernet0/0 SystemSegment</h1>
<div id="sysdetails">
<table>
<tr>
<td>System:</td>
<td>UGC_Topkapi_3661 in </td>
</tr>
<tr>
<td>Maintainer:</td>
<td>Name of The Responsible Person</td>
</tr>
<tr>
<td>Description:</td>
<td>FastEthernet0/0 Connection to SYSTEM Segment </td>
</tr>
<tr>
<td>ifType:</td>
<td>ethernetCsmacd (6)</td>
</tr>
<tr>
<td>ifName:</td>
<td>Fa0/0</td>
</tr>
<tr>
<td>Max Speed:</td>
<td>12.5 MBytes/s</td>
</tr>
<tr>
<td>Ip:</td>
<td>172.28.201.10 ()</td>
</tr>
</table>
</div>


"3661-fasteth00-systemsegment" is the filename of generated html file in path "/var/www/html/mrtgGraphics/relatedDevice/". Each interface has got a different filename like "3661-fasteth00-systemsegment". We have to keep " 2:CmmntyString@172.28.201.10:" part in that configuration file but we can change the other parts such as title, pagetop, and other expressions between html tags.

When we finish editing the configuration file, we have to execute mrtg command with this configuration file as below:

/bin/env LANG=C /usr/bin/mrtg /etc/mrtg/cfg-files/3661.cfg


But the problem is, this command should be re-executed every 5 minutes to get statistics continuously. We can use crontab for this goal. The crontab line is like following for this sample,

*/5 * * * * /bin/env LANG=C /usr/bin/mrtg /etc/mrtg/cfg-files/3661.cfg >/dev/null 2<&1


My MRTG server has got a lot of cfg files and I prepared crontab lines are like this,

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/env LANG=C /usr/bin/mrtg /etc/mrtg/cfg-files/3661.cfg >/dev/null 2<&1
1,6,11,16,21,26,31,36,41,46,51,56 * * * * /bin/env LANG=C /usr/bin/mrtg /etc/mrtg/cfg-files/otherfile.cfg >/dev/null 2<&1
2,7,12,17,22,27,32,37,42,47,52,57 * * * * /bin/env LANG=C /usr/bin/mrtg /etc/mrtg/cfg-files/anotherfile.cfg >/dev/null 2<&1


At this point, our MRTG structure is ready for use. The generated html files are located in path "/var/www/html/mrtgGraphics/relatedDevice/".

[root@mrtg relatedDevice]# ls -l | grep 3661-fasteth00-systemsegment
-rw-r--r-- 1 root root 4649 2011-10-13 16:45 3661-fasteth00-systemsegment-day.png
-rw-r--r-- 1 root root 6951 2011-10-13 16:45 3661-fasteth00-systemsegment.html
-rw-r--r-- 1 root root 98062 2011-10-13 16:45 3661-fasteth00-systemsegment.log
-rw-r--r-- 1 root root 4548 2011-10-13 15:30 3661-fasteth00-systemsegment-month.png
-rw-r--r-- 1 root root 98062 2011-10-13 16:40 3661-fasteth00-systemsegment.old
-rw-r--r-- 1 root root 4337 2011-10-13 16:35 3661-fasteth00-systemsegment-week.png
-rw-r--r-- 1 root root 4756 2011-10-13 04:40 3661-fasteth00-systemsegment-year.png
[root@mrtg relatedDevice]#


If mrtg cfg file has got a lot of interface parts, so lots of html files will be generated. We will need an index page for this situation. We can use following command to generate an index page for our statistics pages.

indexmaker deviceA.cfg > index.html


This command will generate a file with name index.html. We have to move this file to "/var/www/html/mrtgGraphics/relatedDevice/" directory. 3661-fasteth00-systemsegment.html file has got a part like following:

<!-- Begin `Daily' Graph (5 Minute -->
<div class="graph">
<h2>`Daily' Graph (5 Minute Average)</h2>
<img src="3661-fasteth00-systemsegment-day.png" title="day" alt="day" />
<table>
<tr>
<th></th>
<th scope="col">Max</th>
<th scope="col">Average</th>
<th scope="col">Current</th>
</tr>
<tr class="in">
<th scope="row">In</th>
<td>9117.6 kb/s (9.1%)</td>
<td>3139.1 kb/s (3.1%) </td>
<td>5966.2 kb/s (6.0%) </td>
</tr>
<tr class="out">
<th scope="row">Out</th>
<td>9144.2 kb/s (9.1%) </td>
<td>3159.9 kb/s (3.2%) </td>
<td>6001.8 kb/s (6.0%) </td>
</tr>
</table>
</div>
<!-- End `Daily' Graph (5 Minute -->



This part contains numeric values of usage of related interface. We can capture these values every 5 minutes and write to mysql table. Also we can define some limits about that line and compare actual value and limit value. If actual value reaches limit value, the script will be able to generate an alert message. This article is only about the installation of MRTG, Apache http server, php5 and Mysql-Server. The next article will about "how to auto analyze mrtg results with php scripts".

Wednesday, October 12, 2011

Making a Simple Form Module on Drupal 7.8

We have created a simple module before, that is here. But if you build a web site, you'll need to use forms. For that reason, i'll show you about making a simple form module in this article. Let's remember which files we've got when we create module on drupal.

Mymodule (folder)
  • mymodule.info
  • mymodule.module
  • mymodule.inc
"mymodule.info" file is for settings of the module, that's why we don't use it for this article. Other ones also are so important now.

If you check this article out, can remember what the system of drupal's work. When we code, we call the function which will use. Well, then code your mymodule.inc and mymodule.module pages:


mymodule.module page
function honda_menu() {
  $items['honda/hrv'] = array(
    'title' => 'Honda HR-V',
    'page callback' => 'honda_form',
    'access arguments' => array('access content'),
    'file' => 'honda.inc',
  );
  return $items;
}

As you see the bold row's got our function for the module with "page callback". honda_form() function is in;

mymodule.inc page


function honda_form() {
 return drupal_get_form('form_for_honda'); //This is the function that will use
}
function form_for_honda($form_state) {
 $form['text'] = array(
  '#type' => 'textfield', //Input type
  '#title' => t(Write something..'), Input label
 );
 $form['Okey'] = array(
  '#type' => 'submit', //Input type
  '#value' => 'I am Ok!', //Button value
 );
 return $form;
}

When we go to honda/hrv direction, we're going to see it like down here;

Output

Well done! Our form is ready to use. I've just added a textfield and submit button. If you want to add something else, you should add elements for array. For example;

'#type' => 'checkbox',
'#type' => 'fieldset',
'#type' => 'file',
'#type' => 'radios',

If you want to see more information about Drupal forms API, you can visit forms API.

We'll see you next article!

Wednesday, October 5, 2011

Using Taxonomy to Post Contents on Drupal

Some of us have no idea about taxonomy. Actually i didn't know either what taxonomy was. When i built my drupal project, i recognized that i had to use it. I think, taxonomy is one of the most important features of drupal. Because, all content of your site, can be available with terms, verbs and tags on taxonomy.

So, imagine that you've just added content to your drupal site. If this content is a special of you, you'll want people to find it easly, right? Yes! Well, you need to use taxonomy now!

Step 1 : Select the content type you'll add a new field to.
Step 2 : You go manage fields and add a field on it for taxonomy.
Step 3 : Create a new verbs and add tags on it.
Step 4 : Your vocabulary is ready to use now! Add a new content and select tags from vocabulary!

Step 1

My choice is Basic Page content type. You need to click this path :
Click to the manage fields
After clicking; Step 2


As you see it up here, site is waiting for us to add a new field for our taxonomy. Adding is so easy. Just type like;

Label : "tax" //tax is my choice. You can change it
Field name : "field_"tax" //This name is for machine, generally select it like your label name
Type of data to store : "Term reference"
Form element to edit the data : "Autocomplete term widget (tagging)" //If you select it like this, you can add tag multiple, so this would be better?

And click Save button.

Selecting Vocabulary
Step 3

Well done! We create a new field for our tags. But the system asks us to select a vocabulary. Don't do anything on this page and open a new tab on your browser. Because of this, we are going to create a new vocabulary. The direction you'll go to is, "admin/structure/taxonomy/add".

add a new vocabulary for the field

Name : "Testing" //You can change it.
Description : "This is very important!"

And click Save button.


Click the add terms link.

When adding term

Type "php" for "Name" textfield and click the save button. And after that add: "ajax", "sql", "mysql", "dom", "c", "java", etc.
Now, turn back to the page we have to select a vocabulary for new field(tax) and refresh!

Select testing and Click Save Field Setting button.

For testing this vocabulary, add a new content. For that, use this path : "node/add/page".




Like you see, when i type something for tags, ready with Autocomplete term widget.


We'll see you next article!

Form Validation Using AJAX and PHP

In this article, we'll show you something about form validation, namely form control solutions using AJAX and PHP. As you know, we can submit a form without refreshing page with Ajax. So, we should use this tech.

NOTE : Ajax is not one technology, but a group of technologies. Ajax uses HTML, JavaScript, CSS, XML etc.

This example, shows the relationship between getting data of form and checking:

Step 1 is, users type something or not!

Step 2 is, the system checks what the data is or, is there any typed data?

Well, let's do our pages. For that we create three files,
  1. example.html
  2. kitchen.php
  3. lib.ajax.js
lib.ajax.js
// JavaScript Document
	//What does JaX stand for? is the function we use for ajax object
function JaX() {
	var httpObject = null;
	var httpBrowser = navigator.appName;
	
	if(httpBrowser == "Microsoft Internet Explorer") {
		httpObject = new ActiveXObject("Microsoft.XMLHTTP");	
	} else {
		httpObject = new XMLHttpRequest();	
	}
	return httpObject;
}

function UJaX(subject, method, path, more, func, statu) {
	//subject is object of ajax
	//method is the method of getting variables
	//path is the path of file
	//func is the function you use on it
	//statu can be true or false
	ajaxObject = JaX();
	
	if(method == 'POST') {
		if(ajaxObject != null) {
			ajaxObject.onreadystatechange = func;
			ajaxObject.open('POST', path, statu);
			header = "application/x-www-form-urlencoded";
			ajaxObject.setRequestHeader("Content-Type", header);
			ajaxObject.send(more);
		} else {
			alert("Error(1)->The System Cannot Be Opened!");	
		}
	} else {
		if(ajaxObject != null) {
			ajaxObject.onreadystatechange = func;
			ajaxObject.open('GET', path+'?'+more, statu);
			ajaxObject.send(null);
		} else {
			alert("Error(2)->The System Cannot Be Opened!");	
		}
	}
}


example.html

var ajaxObject;

function CheckItOut() {
	subject = ajaxObject;
	method = 'GET';
	path = 'kitchen.php';
	func = sonuc;
	dataMore = document.getElementById("data").value;
	more = 'data=' + dataMore;
	statu = "true";
	
	UJaX(subject, method, path, more, func, statu);
}

function sonuc() {
	if(ajaxObject.readyState == 4) {
		if(ajaxObject.status == 200) {
			DM = ajaxObject.responseText;
			//DM = document.form1.data.value;
			if(DM == "You must write something!")
				document.getElementById("MyButton").disabled = true;	
			else
				document.getElementById("MyButton").disabled = false;	
		} else
			DM = "Error = Nu/1";	
	} else
		DM = "Loading...";	
		document.getElementById("MyLabel").innerHTML = DM;
}

< form name="form1" method="GET">
< input name="data" type="text" id="data" onChange="CheckItOut();">
< input name="MyButton" type="button" id="MyButton" value="I'm Ok!">
< /form>

Preview example.html page

And php page, kitchen.php


$DataOfForm = $_REQUEST["data"];
if(!$DataOfForm == 1) {
	print "You must write something!";
} else {
	print "You said:".$DataOfForm."";	
}

And yes! We just finished our script! go to example.html page and write something;

When you typing

If we don't type anything on this, we'll see like down here:

When you type none.

Like you see, "Button" is disabled when you type none. Because of it is DM variable of javascript.

If you want to see this project, you can click Demo!

We'll see you next article!


hook_help() function on Drupal: 'helping menu' for Our Module

We've learnt how to create a new module on Drupal before, here is How to create a new module! We'll been added new features on it after this article.

As first, we should explain what our module is. For that reason, can put a helping menu. We'd said there were so much functions on Drupal library, hook_help() is just one of'em. If we want to realize what this article says, must implements hook_help() function.

mymodule.module


* Implements hook_help().
*/
function honda_help($path, $arg) {
 if($path == 'admin/help#honda') { //The direction
  return t('<a href=honda/hrv>CLICK FAQ</a> for HONDA HR-V.'); //We help here!
 }
}
When checked t() function out, can see that able to use HTML tags, here is <a href=honda/hrv>CLICK FAQ</a>.


Click the "help?"!

We'll see you next article!