From 07439410924704edfacb690a0713cdb4d860f1fa Mon Sep 17 00:00:00 2001
From: pabloconcepcion <noreply@pandorafms.org>
Date: Fri, 15 Jan 2010 10:35:47 +0000
Subject: [PATCH] =?UTF-8?q?2010-01-15=20=20Pablo=20de=20la=20Concepci?=
 =?UTF-8?q?=C3=B3n=20<pablo.concepcion@artica.es>?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

    * lib/PandoraFMS/Core.pm: Modified to have different functions for the
    creation and update of the agent when it has position information, also
    added some auxiliary functions to store and update this position information.

    * lib/PandoraFMS/DataServer.pm: Modified to use the new functions to create
    and update the agent data adding also the position information.

    * lib/PandoraFMS/PluginServer.pm, lib/PandoraFMS/PredictionServer.pm,
    lib/PandoraFMS/NetworkServer.pm, lib/PandoraFMS/WMIServer.pm: Modified to use
    again the old functions to create and update the angent as in this servers
    we don't have the position information.



git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@2272 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f
---
 pandora_server/ChangeLog                      |  14 +++
 pandora_server/lib/PandoraFMS/Core.pm         | 119 +++++++++++++++---
 pandora_server/lib/PandoraFMS/DataServer.pm   |  11 +-
 .../lib/PandoraFMS/NetworkServer.pm           |   2 +-
 pandora_server/lib/PandoraFMS/PluginServer.pm |   2 +-
 .../lib/PandoraFMS/PredictionServer.pm        |   2 +-
 pandora_server/lib/PandoraFMS/WMIServer.pm    |   2 +-
 7 files changed, 130 insertions(+), 22 deletions(-)

diff --git a/pandora_server/ChangeLog b/pandora_server/ChangeLog
index ee2c3feaf8..42bfa650b3 100644
--- a/pandora_server/ChangeLog
+++ b/pandora_server/ChangeLog
@@ -1,3 +1,17 @@
+2010-01-15	Pablo de la ConcepciĆ³n <pablo.concepcion@artica.es>
+
+	* lib/PandoraFMS/Core.pm: Modified to have different functions for the
+	creation and update of the agent when it has position information, also
+	added some auxiliary functions to store and update this position information.
+
+	* lib/PandoraFMS/DataServer.pm: Modified to use the new functions to create
+	and update the agent data adding also the position information.
+
+	* lib/PandoraFMS/PluginServer.pm, lib/PandoraFMS/PredictionServer.pm,
+	lib/PandoraFMS/NetworkServer.pm, lib/PandoraFMS/WMIServer.pm: Modified to use
+	again the old functions to create and update the angent as in this servers
+	we don't have the position information.
+
 2010-01-14  Miguel de Dios  <miguel.dedios@artica.es>
 	* DEBIAN/* : restore previus version, I had mistake with this directory in
 	Eclipse aplication between Enterprise and Open.
diff --git a/pandora_server/lib/PandoraFMS/Core.pm b/pandora_server/lib/PandoraFMS/Core.pm
index ef57e2b1a0..9b31584feb 100644
--- a/pandora_server/lib/PandoraFMS/Core.pm
+++ b/pandora_server/lib/PandoraFMS/Core.pm
@@ -38,6 +38,7 @@ our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
 our @EXPORT = qw( 	
 	pandora_audit
 	pandora_create_agent
+	pandora_create_agent_gis
 	pandora_create_incident
 	pandora_create_module
 	pandora_evaluate_alert
@@ -59,9 +60,9 @@ our @EXPORT = qw(
 	pandora_reset_server
 	pandora_server_keep_alive
 	pandora_update_agent
+	pandora_update_agent_gis
 	pandora_update_module_on_error
 	pandora_update_server
-	pandora_update_position
 
 	@ServerTypes
 	);
@@ -711,25 +712,81 @@ sub pandora_update_server ($$$$$;$$) {
 ##########################################################################
 # Update last contact field in agent table
 ##########################################################################
-sub pandora_update_agent ($$$$$$$$) {
+sub pandora_update_agent ($$$$$$$) {
 	my ($pa_config, $agent_timestamp, $agent_id, $os_version,
-		$agent_version, $agent_interval, $timezone_offset, $dbh) = @_;
+		$agent_version, $agent_interval, $dbh) = @_;
 
 	my $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime());
 	
 	pandora_access_update ($pa_config, $agent_id, $dbh);
 
-	# No update for interval nor timezone field (some old agents don't support it
+	# No update for interval field (some old agents don't support it)
 	if ($agent_interval == -1){
 		db_do($dbh, 'UPDATE tagente SET agent_version = ?, ultimo_contacto_remoto = ?, ultimo_contacto = ?, os_version = ?, WHERE id_agente = ?',
 		$agent_version, $agent_timestamp, $timestamp, $os_version, $agent_id);
 		return;
 	}
 	
-	db_do ($dbh, 'UPDATE tagente SET intervalo = ?, agent_version = ?, ultimo_contacto_remoto = ?, ultimo_contacto = ?, os_version = ?, timezone_offset = ?  WHERE id_agente = ?',
-		$agent_interval, $agent_version, $agent_timestamp, $timestamp, $os_version, $timezone_offset, $agent_id);
+	db_do ($dbh, 'UPDATE tagente SET intervalo = ?, agent_version = ?, ultimo_contacto_remoto = ?, ultimo_contacto = ?, os_version = ?, WHERE id_agente = ?',
+		$agent_interval, $agent_version, $agent_timestamp, $timestamp, $os_version, $agent_id);
 }
 
+##########################################################################
+# Update last contact, timezone and position fields in agent table
+##########################################################################
+sub pandora_update_agent_gis ($$$$$$$$$$$) {
+    my ($pa_config, $agent_timestamp, $agent_id, $os_version,
+        $agent_version, $agent_interval, $timezone_offset,
+		$longitude, $latitude, $altitude, $dbh) = @_;
+
+    my $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime());
+
+    pandora_access_update ($pa_config, $agent_id, $dbh);
+
+    # No update for interval, timezone and position fields (some old agents don't support it)
+    if ($agent_interval == -1){
+        db_do($dbh, 'UPDATE tagente SET agent_version = ?, ultimo_contacto_remoto = ?, ultimo_contacto = ?, os_version = ?, WHERE id_agente = ?',
+        $agent_version, $agent_timestamp, $timestamp, $os_version, $agent_id);
+        return;
+    }
+
+	logger($pa_config, "Agent id $agent_id",10);
+	# Get the last position to see if it has moved.
+	my $last_agent_info= get_db_single_row ($dbh, 'SELECT * FROM tagente WHERE id_agente = ?', $agent_id);
+
+	logger($pa_config, "Old Agent data: last-latitude = ". $last_agent_info->{'last_longitude'}. " ID: $agent_id ", 10);
+
+	# If the agent has moved outside the range stablised as 
+	if (distance_moved($last_agent_info->{'last_latitude'}, $last_agent_info->{'last_longitude'},$last_agent_info->{'last_altitude'}, $latitude, $longitude, $altitude) > 10 ){
+		# Save the agent data in the agent table
+		save_agent_position($pa_config, $timestamp, $last_agent_info->{'last_latitude'}, $last_agent_info->{'last_longitude'},$last_agent_info->{'last_altitude'}, $agent_id, $dbh);
+	}	
+	else {
+		# Update the end timestamp for the agent
+		update_agent_position($pa_config, $timestamp, $agent_id, $dbh);
+	}
+
+    db_do ($dbh, 'UPDATE tagente SET intervalo = ?, agent_version = ?, ultimo_contacto_remoto = ?, ultimo_contacto = ?, os_version = ?, timezone_offset = ?,
+		    last_longitude = ?, last_latitude =?, last_altitude = ? WHERE id_agente = ?',
+		$agent_interval, $agent_version, $agent_timestamp, $timestamp, $os_version, $timezone_offset, $last_agent_info->{'last_latitude'}, $last_agent_info->{'last_longitude'},
+		$last_agent_info->{'last_altitude'}, $agent_id);
+}
+
+
+sub distance_moved ($$$$$$) {
+	my ($last_latitude, $last_longitude, $last_altiude, $latitude, $longitude, $altitude) = @_;
+
+	# Quick and dirty function to check if the point has moved.
+	# $prec_factor = 1000000;
+	# if (int ($last_latitude * $prec_factor) == int ($latitude * $prec_factor) &&
+	#	 int ($last_longitude * $prec_factor) == int ($longitude * $prec_factor) &&
+	#	 int ($last_altitude * $prec_factor) == int ($altitude * $prec_factor) ) { return false } else { return true}
+
+	# TODO: Replace with a valid calculation of the distance
+	return rand(12);
+}
+
+
 ##########################################################################
 # Updates the keep_alive module for the given agent.
 ##########################################################################
@@ -818,6 +875,27 @@ sub pandora_create_agent ($$$$$$$$$$$) {
 	pandora_event ($pa_config, "Agent [$agent_name] created by $server_name", $pa_config->{'autocreate_group'}, $agent_id, 2, 0, 0, 'new_agent', $dbh);
 	return $agent_id;
 }
+##########################################################################
+# Create a new entry in tagente with position information
+##########################################################################
+sub pandora_create_agent_gis ($$$$$$$$$$$$$$$) {
+	my ($pa_config, $server_name, $agent_name, $address,
+		$address_id, $group_id, $parent_id, $os_id,
+		$description, $interval, $timezone_offset,
+		$longitude, $latitude, $altitude, $dbh) = @_;
+
+	logger ($pa_config, "Server '$server_name' creating agent '$agent_name' address '$address'.", 10);
+
+	$description = "Created by $server_name" unless ($description ne '');
+
+	my $agent_id = db_insert ($dbh, 'INSERT INTO tagente (`nombre`, `direccion`, `comentarios`, `id_grupo`, `id_os`, `server_name`, `intervalo`, `id_parent`, 
+				`timezone_offset`, `last_longitude`, `last_latitude`, `last_altitude`,`modo` ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)', $agent_name, $address, 
+				 $description, $group_id, $os_id, $server_name, $interval, $parent_id, $timezone_offset, $longitude, $latitude, $altitude);
+
+	logger ($pa_config, "Server '$server_name' CREATED agent '$agent_name' address '$address'.", 10);
+	pandora_event ($pa_config, "Agent [$agent_name] created by $server_name", $pa_config->{'autocreate_group'}, $agent_id, 2, 0, 0, 'new_agent', $dbh);
+	return $agent_id;
+}
 
 ##########################################################################
 # Generate an event.
@@ -1274,20 +1352,33 @@ sub pandora_inhibit_alerts ($$$) {
 	return 0;
 }
 
+##########################################################################
+# Updates the end_timestamp of an agent in the tgis_data table
+##########################################################################
+sub update_agent_position($$$$) {
+	my ($pa_config, $timestamp, $agent_id, $dbh) = @_;
+
+    logger($pa_config, "Updating agent position: end_timestamp=$timestamp agent_id=$agent_id", 10);
+
+	# Find the last data from the received agent
+	my $agent_position = get_db_single_row ($dbh, 'SELECT * FROM tgis_data WHERE tagente_id_agente  = ? ORDER BY start_timestamp DESC LIMIT 1', $agent_id );
+ 	return unless (defined ($agent_position));
+
+	# Upadate the timestap of the received agent
+	db_do ($dbh, 'UPDATE tgis_data SET end_timestamp = ? WHERE id_tgis_data = ?', $timestamp, $agent_position->{'id_tgis_data'});
+
+}
 
 ##########################################################################
-# Sets the new position of an agent in the tgis_data table
+# Saves the last position of an agent in the tgis_data table
 ##########################################################################
-sub pandora_update_position($$$$$$) {
-	my ($pa_config, $agent_id, $latitude, $longitude, $altitude, $dbh) = @_;
-	
-	my $utimestamp = time ();
-	my $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime($utimestamp));
-	
+sub save_agent_position($$$$$$$) {
+    my ($pa_config, $timestamp, $longitude,$latitude, $altitude, $agent_id, $dbh) = @_;
+
     logger($pa_config, "Updating agent position: timestamp=$timestamp latitude=$latitude longitude=$longitude altitude=$altitude", 10);
 
 	db_insert($dbh, 'INSERT INTO tgis_data (`longitude`, `latitude`, `altitude`, `tagente_id_agente`, `start_timestamp`, `end_timestamp`) VALUES (?, ?, ?, ?, ?, ?)', 
-		  "".$longitude, "".$latitude, $altitude, $agent_id, $timestamp, $timestamp);
+		  $longitude, $latitude, $altitude, $agent_id, $timestamp, $timestamp);
 
 }
 
diff --git a/pandora_server/lib/PandoraFMS/DataServer.pm b/pandora_server/lib/PandoraFMS/DataServer.pm
index 98185779e4..e96c39301d 100644
--- a/pandora_server/lib/PandoraFMS/DataServer.pm
+++ b/pandora_server/lib/PandoraFMS/DataServer.pm
@@ -215,7 +215,9 @@ sub process_xml_data ($$$$$) {
 		$description = $data->{'description'} if (defined ($data->{'description'}));
 
 		# Create the agent
-		$agent_id = pandora_create_agent ($pa_config, $pa_config->{'servername'}, $agent_name, '', 0, $group_id, 0, $os, $description, $interval, $dbh);
+		logger($pa_config, "Creating agent $agent_name at long: $longitude lat: $latitude alt: $altitude", 5);
+		$agent_id = pandora_create_agent_gis ($pa_config, $pa_config->{'servername'}, $agent_name, '', 0, $group_id, 0, $os, $description, $interval, $timezone_offset, 
+					$longitude, $latitude, $altitude, $dbh);
 		if (! defined ($agent_id)) {
 			$AgentSem->up ();
 			return;
@@ -223,9 +225,10 @@ sub process_xml_data ($$$$$) {
 	}
   	$AgentSem->up ();
 
-	pandora_update_agent ($pa_config, $timestamp, $agent_id, $os_version, $agent_version, $interval, $timezone_offset, $dbh);
-	# TODO: Check if it's needed to update the position
-	pandora_update_position($pa_config, $agent_id, $latitude, $longitude, $altitude, $dbh);
+    logger($pa_config, "Updating agent $agent_name at long: $longitude lat: $latitude alt: $altitude", 5);
+	# Update agent information including position information
+	pandora_update_agent_gis ($pa_config, $timestamp, $agent_id, $os_version, $agent_version, $interval, $timezone_offset, $latitude, $longitude, $altitude, $dbh);
+
 	pandora_module_keep_alive ($pa_config, $agent_id, $agent_name, $server_id, $dbh);
 
 	# Process modules
diff --git a/pandora_server/lib/PandoraFMS/NetworkServer.pm b/pandora_server/lib/PandoraFMS/NetworkServer.pm
index 1bd8bc94d3..5e2e36e567 100644
--- a/pandora_server/lib/PandoraFMS/NetworkServer.pm
+++ b/pandora_server/lib/PandoraFMS/NetworkServer.pm
@@ -379,7 +379,7 @@ sub exec_network_module ($$$$) {
 		pandora_process_module ($pa_config, $module_data, undef, $module, undef, $timestamp, $utimestamp, $server_id, $dbh);
 
 		# Update agent last contact using Pandora version as agent version
-		pandora_update_agent ($pa_config, $timestamp, $id_agente, $pa_config->{'servername'}.'_Net', $pa_config->{'version'}, -1, 0, $dbh);
+		pandora_update_agent ($pa_config, $timestamp, $id_agente, $pa_config->{'servername'}.'_Net', $pa_config->{'version'}, -1, $dbh);
 	
     } else {
 		# Modules who cannot connect or something go bad, update last_execution_try field
diff --git a/pandora_server/lib/PandoraFMS/PluginServer.pm b/pandora_server/lib/PandoraFMS/PluginServer.pm
index e32409c39e..b1e818927c 100644
--- a/pandora_server/lib/PandoraFMS/PluginServer.pm
+++ b/pandora_server/lib/PandoraFMS/PluginServer.pm
@@ -207,7 +207,7 @@ sub data_consumer ($$) {
 	my $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime($utimestamp));
 
 	pandora_process_module ($pa_config, $module_data, undef, $module, undef, $timestamp, $utimestamp, $self->getServerID (), $dbh);
-	pandora_update_agent ($pa_config, $timestamp, $module->{'id_agente'}, $pa_config->{'servername'}.'_Plugin', $pa_config->{'version'}, -1, 0, $dbh);
+	pandora_update_agent ($pa_config, $timestamp, $module->{'id_agente'}, $pa_config->{'servername'}.'_Plugin', $pa_config->{'version'}, -1, $dbh);
 }
 
 1;
diff --git a/pandora_server/lib/PandoraFMS/PredictionServer.pm b/pandora_server/lib/PandoraFMS/PredictionServer.pm
index 8e8d156128..373bbb06ce 100644
--- a/pandora_server/lib/PandoraFMS/PredictionServer.pm
+++ b/pandora_server/lib/PandoraFMS/PredictionServer.pm
@@ -236,7 +236,7 @@ sub exec_prediction_module ($$$$) {
     }
 
 	pandora_process_module ($pa_config, $module_data, undef, $agent_module, undef, $timestamp, $utimestamp, $server_id, $dbh);
-	pandora_update_agent ($pa_config, $timestamp, $agent_module->{'id_agente'}, $pa_config->{'servername'}.'_Prediction', $pa_config->{'version'}, -1,  0,$dbh);
+	pandora_update_agent ($pa_config, $timestamp, $agent_module->{'id_agente'}, $pa_config->{'servername'}.'_Prediction', $pa_config->{'version'}, -1, $dbh);
 }
 
 1;
diff --git a/pandora_server/lib/PandoraFMS/WMIServer.pm b/pandora_server/lib/PandoraFMS/WMIServer.pm
index c4e3ba8c96..b5234d9aab 100644
--- a/pandora_server/lib/PandoraFMS/WMIServer.pm
+++ b/pandora_server/lib/PandoraFMS/WMIServer.pm
@@ -193,7 +193,7 @@ sub data_consumer ($$) {
 	my $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime($utimestamp));
 
 	pandora_process_module ($pa_config, $module_data, undef, $module, undef, $timestamp, $utimestamp, $self->getServerID (), $dbh);
-	pandora_update_agent ($pa_config, $timestamp, $module->{'id_agente'},  $pa_config->{'servername'} . '_WMI', $pa_config->{'version'}, -1,  0,$dbh);
+	pandora_update_agent ($pa_config, $timestamp, $module->{'id_agente'},  $pa_config->{'servername'} . '_WMI', $pa_config->{'version'}, -1, $dbh);
 }
 
 1;