Code

Avoiding a race condition during server-server registration process.
[gosa.git] / gosa-si / server / events / server_server_com.pm
1 package server_server_com;
2 use Exporter;
3 @ISA = qw(Exporter);
4 my @events = (
5     'information_sharing',
6     'new_server',
7     'confirm_new_server',
8     'new_foreign_client',
9     'trigger_wake',
10     'foreign_job_updates',
11     'confirm_usr_msg',
12     );
13 @EXPORT = @events;
15 use strict;
16 use warnings;
17 use Data::Dumper;
18 use GOSA::GosaSupportDaemon;
19 use Time::HiRes qw( usleep);
20 use Socket;
23 BEGIN {}
25 END {}
27 ### Start ######################################################################
29 sub get_events {
30     return \@events;
31 }
34 sub information_sharing {
35     my ($msg, $msg_hash, $session_id) = @_ ;
36     my $header = @{$msg_hash->{'header'}}[0];
37     my $source = @{$msg_hash->{'source'}}[0];
38     my $target = @{$msg_hash->{'target'}}[0];
40     # Handling of msg tag 'new_user'
41     if (exists $msg_hash->{'new_user'}) {
42         my $new_user_list = $msg_hash->{'new_user'};
44         # Sanity check of new_user_list
45         if (ref($new_user_list) eq 'HASH') {
46             &main::daemon_log("$session_id ERROR: 'new_user'-tag in incoming msg has no content!", 1);
48         } else {
49             # Add each user to login_users_db
50             foreach my $new_user_info (@$new_user_list) {
51                 my ($client, $user) = split(/;/, $new_user_info);
52                 &main::daemon_log("$session_id INFO: server '$source' reports user '$user' is logged in at client '$client'", 5);
53                 my %add_hash = ( table=>$main::login_users_tn, 
54                         primkey=> ['client', 'user'],
55                         client=>$client,
56                         user=>$user,
57                         timestamp=>&get_time,
58                         regserver=>$source,
59                         ); 
60                 my ($res, $error_str) = $main::login_users_db->add_dbentry( \%add_hash );
61                 if ($res != 0)  {
62                     &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $error_str", 1);
63                 }
64             }
65         }
66     }
68     # Handling of msg tag 'user_db'
69     if (exists $msg_hash->{'user_db'}) {
70         my $user_db_list = $msg_hash->{'user_db'};
72         # Sanity check of user_db_list
73         if (ref($user_db_list) eq 'HASH') {
74             &main::daemon_log("$session_id ERROR: 'user_db'-tag in incoming msg has no content!", 1);
76         } else {
77             # Delete all old login information
78             my $sql = "DELETE FROM $main::login_users_tn WHERE regserver='$source'"; 
79             my $res = $main::login_users_db->exec_statement($sql);
81             # Add each user to login_users_db
82             foreach my $user_db_info (@$user_db_list) {
83                 my ($client, $user) = split(/;/, $user_db_info);
84                 &main::daemon_log("$session_id INFO: server '$source' reports user '$user' is logged in at client '$client'", 5);
85                 my %add_hash = ( table=>$main::login_users_tn, 
86                         primkey=> ['client', 'user'],
87                         client=>$client,
88                         user=>$user,
89                         timestamp=>&get_time,
90                         regserver=>$source,
91                         ); 
92                 my ($res, $error_str) = $main::login_users_db->add_dbentry( \%add_hash );
93                 if ($res != 0)  {
94                     &main::daemon_log("$session_id ERROR: cannot add entry to known_clients: $error_str", 1);
95                 }
96             }
97         }
98     }
100     return;
103 sub foreign_job_updates {
104     my ($msg, $msg_hash, $session_id) = @_ ;
105     my $header = @{$msg_hash->{'header'}}[0];
106     my $source = @{$msg_hash->{'source'}}[0];
107     my $target = @{$msg_hash->{'target'}}[0];
108     
109     my @act_keys = keys %$msg_hash;
110     my @jobs;
111     foreach my $key (@act_keys) {
112         if ($key =~ /answer\d+/ ) { push(@jobs, $key); }
113     }
115     foreach my $foreign_job (@jobs) {
117         # add job to job queue
118         my $func_dic = {table=>$main::job_queue_tn,
119             primkey=>['macaddress', 'headertag'],
120             timestamp=>@{@{$msg_hash->{$foreign_job}}[0]->{'timestamp'}}[0],
121             status=>@{@{$msg_hash->{$foreign_job}}[0]->{'status'}}[0],
122             result=>@{@{$msg_hash->{$foreign_job}}[0]->{'result'}}[0],
123             progress=>@{@{$msg_hash->{$foreign_job}}[0]->{'progress'}}[0],
124             headertag=>@{@{$msg_hash->{$foreign_job}}[0]->{'headertag'}}[0],
125             targettag=>@{@{$msg_hash->{$foreign_job}}[0]->{'targettag'}}[0],
126             xmlmessage=>@{@{$msg_hash->{$foreign_job}}[0]->{'xmlmessage'}}[0],
127             macaddress=>@{@{$msg_hash->{$foreign_job}}[0]->{'macaddress'}}[0],
128             plainname=>@{@{$msg_hash->{$foreign_job}}[0]->{'plainname'}}[0],
129             siserver=>$source,
130             modified=>"0",
131         };
132         my $res = $main::job_db->add_dbentry($func_dic);
133         if (not $res == 0) {
134             &main::daemon_log("$session_id ERROR: ServerPackages: process_job_msg: $res", 1);
135         } else {
136             &main::daemon_log("$session_id INFO: ServerPackages: $header, job '".@{@{$msg_hash->{$foreign_job}}[0]->{'headertag'}}[0].
137                     "' successfully added to job queue", 5);
138         }
139     }
141     return;
145 sub new_server {
146     my ($msg, $msg_hash, $session_id) = @_ ;
147     my $header = @{$msg_hash->{'header'}}[0];
148     my $source = @{$msg_hash->{'source'}}[0];
149     my $target = @{$msg_hash->{'target'}}[0];
150     my $key = @{$msg_hash->{'key'}}[0];
151     my $mac = exists $msg_hash->{'macaddress'} ? @{$msg_hash->{'macaddress'}}[0] : "" ;
152     my @clients = exists $msg_hash->{'client'} ? @{$msg_hash->{'client'}} : qw();
153     my @loaded_modules = exists $msg_hash->{'loaded_modules'} ? @{$msg_hash->{'loaded_modules'}} : qw();
155         # Ignor message if I'm already within a registration process for server $source
156         my $check_statement = "SELECT * FROM $main::known_server_tn WHERE status='new_server' AND hostname='$source'"; 
157         &main::daemon_log("$session_id DEBUG $check_statement", 7);
158         my $check_res = $main::known_server_db->select_dbentry($check_statement);
159         my $blocking_process = keys(%$check_res);
160         if ($blocking_process)
161         {
162                 return;
163         }
165     # Sanity check
166     if (ref $key eq 'HASH') {
167         &main::daemon_log("$session_id ERROR: 'new_server'-message from host '$source' contains no key!", 1);
168         return;
169     }
170     # Add foreign server to known_server_db
171         my $new_update_time = &calc_timestamp(&get_time(), 'plus', $main::foreign_servers_register_delay);
172     my $func_dic = {table=>$main::known_server_tn,
173         primkey=>['hostname'],
174         hostname => $source,
175         macaddress => $mac,
176         status => "new_server",
177         hostkey => $key,
178         loaded_modules => join(',', @loaded_modules),
179         timestamp=>&get_time(),
180                 update_time=>$new_update_time,
181     };
182     my $res = $main::known_server_db->add_dbentry($func_dic);
183     if (not $res == 0) {
184         &main::daemon_log("$session_id ERROR: server_server_com.pm: cannot add server to known_server_db: $res", 1);
185     } else {
186         &main::daemon_log("$session_id INFO: server_server_com.pm: server '$source' successfully added to known_server_db", 5);
187     }
189     # delete all entries at foreign_clients_db coresponding to this server
190     my $del_sql = "DELETE FROM $main::foreign_clients_tn WHERE regserver='$source' ";
191     my $del_res = $main::foreign_clients_db->exec_statement($del_sql);
193     # add clients of foreign server to known_foreign_clients_db
194     my @sql_list;
195     foreach my $client (@clients) {
196         my @client_details = split(/,/, $client);
198         # workaround to avoid double entries in foreign_clients_db
199         my $del_sql = "DELETE FROM $main::foreign_clients_tn WHERE hostname='".$client_details[0]."'";
200         push(@sql_list, $del_sql);
202         my $sql = "INSERT INTO $main::foreign_clients_tn VALUES ("
203             ."'".$client_details[0]."',"   # hostname
204             ."'".$client_details[1]."',"   # macaddress
205             ."'".$source."',"              # regserver
206             ."'".&get_time()."')";         # timestamp
207         push(@sql_list, $sql);
208     }
209     if (@sql_list) {
210                 my $len = @sql_list;
211                 $len /= 2;
212         &main::daemon_log("$session_id DEBUG: Inserting ".$len." entries to foreign_clients_db", 8);
213         my $res = $main::foreign_clients_db->exec_statementlist(\@sql_list);
214     }
216     # fetch all registered clients
217     my $client_sql = "SELECT * FROM $main::known_clients_tn"; 
218     my $client_res = $main::known_clients_db->exec_statement($client_sql);
221     # add already connected clients to registration message 
222     my $myhash = &create_xml_hash('confirm_new_server', $main::server_address, $source);
223     &add_content2xml_hash($myhash, 'key', $key);
224     map(&add_content2xml_hash($myhash, 'client', @{$_}[0].",".@{$_}[4]), @$client_res);
226     # add locally loaded gosa-si modules to registration message
227     my $loaded_modules = {};
228     while (my ($package, $pck_info) = each %$main::known_modules) {
229         foreach my $act_module (keys(%{@$pck_info[2]})) {
230             $loaded_modules->{$act_module} = ""; 
231         }
232     }
233     map(&add_content2xml_hash($myhash, "loaded_modules", $_), keys(%$loaded_modules));
235     # add macaddress to registration message
236     my ($host_ip, $host_port) = split(/:/, $source);
237     my $local_ip = &get_local_ip_for_remote_ip($host_ip);
238     my $network_interface= &get_interface_for_ip($local_ip);
239     my $host_mac = &get_mac_for_interface($network_interface);
240     &add_content2xml_hash($myhash, 'macaddress', $host_mac);
242     # build registration message and send it
243     my $out_msg = &create_xml_string($myhash);
244     my $error =  &main::send_msg_to_target($out_msg, $source, $main::ServerPackages_key, 'confirm_new_server', $session_id); 
246     return;
250 sub confirm_new_server {
251     my ($msg, $msg_hash, $session_id) = @_ ;
252     my $header = @{$msg_hash->{'header'}}[0];
253     my $source = @{$msg_hash->{'source'}}[0];
254     my $key = @{$msg_hash->{'key'}}[0];
255     my $mac = exists $msg_hash->{'macaddress'} ? @{$msg_hash->{'macaddress'}}[0] : "" ;
256     my @clients = exists $msg_hash->{'client'} ? @{$msg_hash->{'client'}} : qw();
257     my @loaded_modules = exists $msg_hash->{'loaded_modules'} ? @{$msg_hash->{'loaded_modules'}} : qw();
259         my $new_update_time = &calc_timestamp(&get_time(), 'plus', $main::foreign_servers_register_delay);
260     my $sql = "UPDATE $main::known_server_tn".
261         " SET status='$header', hostkey='$key', loaded_modules='".join(",",@loaded_modules)."', macaddress='$mac', update_time='$new_update_time'".
262         " WHERE hostname='$source'"; 
263     my $res = $main::known_server_db->update_dbentry($sql);
265     # add clients of foreign server to known_foreign_clients_db
266     my @sql_list;
267     foreach my $client (@clients) {
268         my @client_details = split(/,/, $client);
270         # workaround to avoid double entries in foreign_clients_db
271         my $del_sql = "DELETE FROM $main::foreign_clients_tn WHERE hostname='".$client_details[0]."'";
272         push(@sql_list, $del_sql);
274         my $sql = "INSERT INTO $main::foreign_clients_tn VALUES ("
275             ."'".$client_details[0]."',"        # hostname
276             ."'".$client_details[1]."',"        # macaddress
277             ."'".$source."',"                   # regserver
278             ."'".&get_time()."')";                      # timestamp
279         push(@sql_list, $sql);
280     }
281     if (@sql_list) {
282                 my $len = @sql_list;
283                 $len /= 2;
284         &main::daemon_log("$session_id DEBUG: Inserting ".$len." entries to foreign_clients_db", 8);
285         my $res = $main::foreign_clients_db->exec_statementlist(\@sql_list);
286     }
289     return;
293 sub new_foreign_client {
294     my ($msg, $msg_hash, $session_id) = @_ ;
295     my $header = @{$msg_hash->{'header'}}[0];
296     my $source = @{$msg_hash->{'source'}}[0];
297     my $hostname = @{$msg_hash->{'client'}}[0];
298     my $macaddress = @{$msg_hash->{'macaddress'}}[0];
299         # if new client is known in known_clients_db
300         my $check_sql = "SELECT * FROM $main::known_clients_tn WHERE (macaddress LIKE '$macaddress')"; 
301         my $check_res = $main::known_clients_db->select_dbentry($check_sql);
303         if( (keys(%$check_res) == 1) ) {
304                         my $host_key = $check_res->{1}->{'hostkey'};
306                         # check if new client is still alive
307                         my $client_hash = &create_xml_hash("ping", $main::server_address, $hostname);
308                         &add_content2xml_hash($client_hash, 'session_id', $session_id);
309                         my $client_msg = &create_xml_string($client_hash);
310                         my $error = &main::send_msg_to_target($client_msg, $hostname, $host_key, 'ping', $session_id);
311                         my $message_id;
312                         my $i = 0;
313                         while (1) {
314                                         $i++;
315                                         my $sql = "SELECT * FROM $main::incoming_tn WHERE headertag='answer_$session_id'";
316                                         my $res = $main::incoming_db->exec_statement($sql);
317                                         if (ref @$res[0] eq "ARRAY") {
318                                                         $message_id = @{@$res[0]}[0];
319                                                         last;
320                                         }
322                                         # do not run into a endless loop
323                                         if ($i > 50) { last; }
324                                         usleep(100000);
325                         }
327                         # client is alive
328                         # -> new_foreign_client will be ignored
329                         if (defined $message_id) {
330                                 &main::daemon_log("$session_id ERROR: At new_foreign_clients: host '$hostname' is reported as a new foreign client, ".
331                                                                 "but the host is still registered at this server. So, the new_foreign_client-msg will be ignored: $msg", 1);
332                         }
333         }
335         
336         # new client is not found in known_clients_db or
337         # new client is dead -> new_client-msg from foreign server is valid
338         # -> client will be deleted from known_clients_db 
339         # -> inserted to foreign_clients_db
340         
341         my $del_sql = "DELETE FROM $main::known_clients_tn WHERE (hostname='$hostname')";
342         my $del_res = $main::known_clients_db->exec_statement($del_sql);
343     my $func_dic = { table => $main::foreign_clients_tn,
344         primkey => ['hostname'],
345         hostname =>   $hostname,
346         macaddress => $macaddress,
347         regserver =>  $source,
348         timestamp =>  &get_time(),
349     };
350     my $res = $main::foreign_clients_db->add_dbentry($func_dic);
351     if (not $res == 0) {
352         &main::daemon_log("$session_id ERROR: server_server_com.pm: cannot add server to foreign_clients_db: $res", 1);
353     } else {
354         &main::daemon_log("$session_id INFO: server_server_com.pm: client '$hostname' successfully added to foreign_clients_db", 5);
355     }
357     return;
361 sub trigger_wake {
362     my ($msg, $msg_hash, $session_id) = @_ ;
364     foreach (@{$msg_hash->{'macaddress'}}){
365         &main::daemon_log("$session_id INFO: trigger wake for $_", 5);
366         my $host    = $_;
367         my $ipaddr  = '255.255.255.255';
368         my $port    = getservbyname('discard', 'udp');
369         if (not defined $port) {
370                 &main::daemon_log("$session_id ERROR: cannot determine port for wol $_: 'getservbyname('discard', 'udp')' failed!",1);
371                 next;
372         }
374         my ($raddr, $them, $proto);
375         my ($hwaddr, $hwaddr_re, $pkt);
377         # get the hardware address (ethernet address)
378         $hwaddr_re = join(':', ('[0-9A-Fa-f]{1,2}') x 6);
379         if ($host =~ m/^$hwaddr_re$/) {
380           $hwaddr = $host;
381         } else {
382           &main::daemon_log("$session_id ERROR: trigger_wake called with non mac address", 1);
383         }
385         # Generate magic sequence
386         foreach (split /:/, $hwaddr) {
387                 $pkt .= chr(hex($_));
388         }
389         $pkt = chr(0xFF) x 6 . $pkt x 16 . $main::wake_on_lan_passwd;
391         # Allocate socket and send packet
393         $raddr = gethostbyname($ipaddr);
394         if (not defined $raddr) {
395                 &main::daemon_log("$session_id ERROR: cannot determine raddr for wol $_: 'gethostbyname($ipaddr)' failed!", 1);
396                 next;
397         }
399         $them = pack_sockaddr_in($port, $raddr);
400         $proto = getprotobyname('udp');
402         socket(S, AF_INET, SOCK_DGRAM, $proto) or die "socket : $!";
403         setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1) or die "setsockopt : $!";
404         send(S, $pkt, 0, $them) or die "send : $!";
405         close S;
406     }
408     return;
412 sub confirm_usr_msg {
413     my ($msg, $msg_hash, $session_id) = @_ ;
414     &clMessages::confirm_usr_msg($msg, $msg_hash, $session_id);
415     return;
419 1;