This file is indexed.

/usr/share/perl5/MMM/Monitor/Monitor.pm is in mysql-mmm-monitor 2.2.1-1.1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
package MMM::Monitor::Monitor;

use strict;
use warnings FATAL => 'all';
use threads;
use threads::shared;
use Algorithm::Diff;
use Data::Dumper;
use DBI;
use Errno qw(EINTR);
use Fcntl qw(F_SETFD F_GETFD FD_CLOEXEC);
use File::Temp;
use Log::Log4perl qw(:easy);
use Thread::Queue;
use MMM::Monitor::Agents;
use MMM::Monitor::Checker;
use MMM::Monitor::ChecksStatus;
use MMM::Monitor::Commands;
use MMM::Monitor::NetworkChecker;
use MMM::Monitor::Role;
use MMM::Monitor::Roles;
use MMM::Monitor::StartupStatus;

=head1 NAME

MMM::Monitor::Monitor - single instance class with monitor logic

=cut

our $VERSION = '0.01';

use constant MMM_MONITOR_MODE_PASSIVE => 0;
use constant MMM_MONITOR_MODE_ACTIVE  => 1;
use constant MMM_MONITOR_MODE_MANUAL  => 2;
use constant MMM_MONITOR_MODE_WAIT    => 3;

use Class::Struct;

sub instance() {
	return $main::monitor;
}

struct 'MMM::Monitor::Monitor' => {
	checker_queue		=> 'Thread::Queue',
	checks_status		=> 'MMM::Monitor::ChecksStatus',
	command_queue		=> 'Thread::Queue',
	result_queue		=> 'Thread::Queue',
	roles				=> 'MMM::Monitor::Roles',
	mode				=> '$',
	passive_info		=> '$',
	kill_host_bin		=> '$'
};



=head1 FUNCTIONS

=over 4

=item init

Init queues, single instance classes, ... and try to determine status.

=cut

sub init($) {
	my $self = shift;

	#___________________________________________________________________________
	#
	# Wait until network connection is available
	#___________________________________________________________________________

	INFO "Waiting for network connection...";
	unless (MMM::Monitor::NetworkChecker->wait_for_network()) {
		INFO "Received shutdown request while waiting for network connection.";
		return 0;
	}
	INFO "Network connection is available.";


	#___________________________________________________________________________
	#
	# Create thread queues and other stuff... 
	#___________________________________________________________________________

	my $agents = MMM::Monitor::Agents->instance();

	$self->checker_queue(new Thread::Queue::);
	$self->checks_status(MMM::Monitor::ChecksStatus->instance());
	$self->command_queue(new Thread::Queue::);
	$self->result_queue(new Thread::Queue::);
	$self->roles(MMM::Monitor::Roles->instance());
	$self->passive_info('');

	if ($main::config->{monitor}->{mode} eq 'active') {
		$self->mode(MMM_MONITOR_MODE_ACTIVE);
	}
	elsif ($main::config->{monitor}->{mode} eq 'manual') {
		$self->mode(MMM_MONITOR_MODE_MANUAL);
	}
	elsif ($main::config->{monitor}->{mode} eq 'wait') {
		$self->mode(MMM_MONITOR_MODE_WAIT);
	}
	elsif ($main::config->{monitor}->{mode} eq 'passive') {
		$self->mode(MMM_MONITOR_MODE_PASSIVE);
		$self->passive_info('Configured to start up in passive mode.');
	}
	else {
		LOGDIE "Something very, very strange just happend - dieing..."
	}


	#___________________________________________________________________________
	#
	# Check kill host binary
	#___________________________________________________________________________

	my $kill_host_bin = $main::config->{monitor}->{kill_host_bin};
	$kill_host_bin = $main::config->{monitor}->{bin_path} . "/monitor/$kill_host_bin" unless ($kill_host_bin =~ /^\/.*/);
	if (!-f $kill_host_bin) {
		WARN sprintf('No binary found for killing hosts (%s).', $kill_host_bin);
	}
	elsif (!-x _) {
		WARN sprintf('Binary for killing hosts (%s) is not executable.', $kill_host_bin);
	}
	else {
		$self->kill_host_bin($kill_host_bin);
	}


	my $checks	= $self->checks_status;

	
	#___________________________________________________________________________
	#
	# Check replication setup of master hosts
	#___________________________________________________________________________

	$self->check_master_configuration();


	#___________________________________________________________________________
	#
	# Fetch stored status, agent status and system status
	#___________________________________________________________________________

	$agents->load_status();	# load stored status


	my $startup_status	= new MMM::Monitor::StartupStatus; 

	my $res;

	foreach my $host (keys(%{$main::config->{host}})) {

		my $agent		= $agents->get($host);

		$startup_status->set_stored_status($host, $agent->state, $agent->roles);

		#_______________________________________________________________________
		#
		# Get AGENT status
		#_______________________________________________________________________

		$res = $agent->cmd_get_agent_status(2);

		if ($res =~ /^OK/) {
			my ($msg, $state, $roles_str, $master) = split('\|', $res);
			my @roles_str_arr = sort(split(/\,/, $roles_str));
			my @roles;

			foreach my $role_str (@roles_str_arr) {
				my $role = MMM::Monitor::Role->from_string($role_str);
				push(@roles, $role) if (defined($role));
			}

			$startup_status->set_agent_status($host, $state, \@roles, $master);
		}
		elsif ($agent->state ne 'ADMIN_OFFLINE') {
			if ($checks->ping($host) && $checks->mysql($host) && !$agent->agent_down()) {
				ERROR "Can't reach agent on host '$host'";
				$agent->agent_down(1);
			}
			ERROR "The status of the agent on host '$host' could not be determined (answer was: $res).";
		}
		

		#_______________________________________________________________________
		#
		# Get SYSTEM status
		#_______________________________________________________________________

		$res = $agent->cmd_get_system_status(2);

		if ($res =~ /^OK/) {
			my ($msg, $writable, $roles_str, $master_ip) = split('\|', $res);
			my @roles_str_arr = sort(split(/\,/, $roles_str));
			my @roles;

			foreach my $role_str (@roles_str_arr) {
				my $role = MMM::Monitor::Role->from_string($role_str);
				push(@roles, $role) if (defined($role));
			}

			my $master = '';
			if (defined($master_ip)) {
			    foreach my $a_host (keys(%{$main::config->{host}})) {
					$master = $a_host if ($main::config->{host}->{$a_host}->{ip} eq $master_ip);
				}
			}
			$startup_status->set_system_status($host, $writable, \@roles, $master);
		}
		elsif ($agent->state ne 'ADMIN_OFFLINE') {
			if ($checks->ping($host) && $checks->mysql($host) && !$agent->agent_down()) {
				ERROR "Can't reach agent on host '$host'";
				$agent->agent_down(1);
			}
			ERROR "The status of the system '$host' could not be determined (answer was: $res).";
		}
	}

	my $conflict = $startup_status->determine_status();

	DEBUG "STATE INFO\n", Data::Dumper->Dump([$startup_status], ['Startup status']);
	INFO $startup_status->to_string();

	foreach my $host (keys(%{$startup_status->{result}})) {
		my $agent = $agents->get($host);
		$agent->state($startup_status->{result}->{$host}->{state});
		foreach my $role (@{$startup_status->{result}->{$host}->{roles}}) {
			$self->roles->set_role($role->name, $role->ip, $host);
		}
	}

	if ($conflict && $main::config->{monitor}->{careful_startup}) {
		$self->set_passive();
		$self->passive_info("Conflicting roles during startup:\n\n" . $startup_status->to_string());
	}
	elsif (!$self->is_passive) {
		$self->cleanup_and_send_status();
	}
	
	INFO "Monitor started in active mode."  if ($self->mode == MMM_MONITOR_MODE_ACTIVE);
	INFO "Monitor started in manual mode."  if ($self->mode == MMM_MONITOR_MODE_MANUAL);
	INFO "Monitor started in wait mode."    if ($self->mode == MMM_MONITOR_MODE_WAIT);
	INFO "Monitor started in passive mode." if ($self->mode == MMM_MONITOR_MODE_PASSIVE);

	return 1;
}

sub check_master_configuration($) {
	my $self	= shift;

	# Get masters
	my @masters = $self->roles->get_role_hosts($main::config->{active_master_role});

	if (scalar(@masters) < 2) {
		WARN "Only one host configured which can handle the active master role. Skipping check of master-master configuration.";
		return;
	}
	if (scalar(@masters) > 2) {
		LOGDIE "There are more than two hosts configured which can handle the active master role.";
	}


	# Check status of masters
	my $checks	= $self->checks_status;
	foreach my $master (@masters) {
		next if ($checks->mysql($master));
		WARN "Check 'mysql' is in state 'failed' on host '$master'. Skipping check of master-master configuration.";
		return;
	}


	# Connect to masters
	my ($master1, $master2) = @masters;
	my $master1_info = $main::config->{host}->{$master1};
	my $master2_info = $main::config->{host}->{$master2};

	my $dsn1	= sprintf("DBI:mysql:host=%s;port=%s;mysql_connect_timeout=3", $master1_info->{ip}, $master1_info->{mysql_port});
	my $dsn2	= sprintf("DBI:mysql:host=%s;port=%s;mysql_connect_timeout=3", $master2_info->{ip}, $master2_info->{mysql_port});

	my $eintr	= EINTR;

	my $dbh1;
CONNECT1: {
	DEBUG "Connecting to master 1";
	$dbh1	= DBI->connect($dsn1, $master1_info->{monitor_user}, $master1_info->{monitor_password}, { PrintError => 0 });
	unless ($dbh1) {
		redo CONNECT1 if ($DBI::err == 2003 && $DBI::errstr =~ /\($eintr\)/);
		WARN "Couldn't connect to  '$master1'. Skipping check of master-master replication." . $DBI::err . " " . $DBI::errstr;
	}
}

	my $dbh2;
CONNECT2: {
	DEBUG "Connecting to master 2";
	$dbh2	= DBI->connect($dsn2, $master2_info->{monitor_user}, $master2_info->{monitor_password}, { PrintError => 0 });
	unless ($dbh2) {
		redo CONNECT2 if ($DBI::err == 2003 && $DBI::errstr =~ /\($eintr\)/);
		WARN "Couldn't connect to  '$master2'. Skipping check of master-master replication." . $DBI::err . " " . $DBI::errstr;
	}
}


	# Check replication peers
	my $slave_status1 = $dbh1->selectrow_hashref('SHOW SLAVE STATUS');
	my $slave_status2 = $dbh2->selectrow_hashref('SHOW SLAVE STATUS');

	WARN "$master1 is not replicating from $master2" if (!defined($slave_status1) || $slave_status1->{Master_Host} ne $master2_info->{ip});
	WARN "$master2 is not replicating from $master1" if (!defined($slave_status2) || $slave_status2->{Master_Host} ne $master1_info->{ip});


	# Check auto_increment_offset and auto_increment_increment
	my ($offset1, $increment1) = $dbh1->selectrow_array('select @@auto_increment_offset, @@auto_increment_increment');
	my ($offset2, $increment2) = $dbh2->selectrow_array('select @@auto_increment_offset, @@auto_increment_increment');

	unless (defined($offset1) && defined($increment1)) {
		WARN "Couldn't get value of auto_increment_offset/auto_increment_increment from host $master1. Skipping check of master-master replication.";
		return;
	}
	unless (defined($offset2) && defined($increment2)) {
		WARN "Couldn't get value of auto_increment_offset/auto_increment_increment from host $master2. Skipping check of master-master replication.";
		return;
	}
	
	WARN "auto_increment_increment should be identical on both masters ($master1: $increment1 , $master2: $increment2)" unless ($increment1 == $increment2);
	WARN "auto_increment_offset should be different on both masters ($master1: $offset1 , $master2: $offset2)" unless ($offset1 != $offset2);
	WARN "$master1: auto_increment_increment ($increment1) should be >= 2" unless ($increment1 >= 2);
	WARN "$master2: auto_increment_increment ($increment2) should be >= 2" unless ($increment2 >= 2);
	WARN "$master1: auto_increment_offset ($offset1) should not be greater than auto_increment_increment ($increment1)" unless ($offset1 <= $increment1);
	WARN "$master2: auto_increment_offset ($offset2) should not be greater than auto_increment_increment ($increment2)" unless ($offset2 <= $increment2);

}


=item main

Main thread

=cut

sub main($) {
	my $self	= shift;

	# Delay execution so we can reap all childs before spawning the checker threads.
	# This prevents a segfault if a SIGCHLD arrives during creation of a thread.
	# See perl bug #60724
	sleep(3);

	# Spawn checker threads
	my @checks	= keys(%{$main::config->{check}});
	my @threads;

	push(@threads, new threads(\&MMM::Monitor::NetworkChecker::main));
	push(@threads, new threads(\&MMM::Monitor::Commands::main, $self->result_queue, $self->command_queue));

	foreach my $check_name (@checks) {
		push(@threads, new threads(\&MMM::Monitor::Checker::main, $check_name, $self->checker_queue));
	}
	

	my $command_queue = $self->command_queue;

	while (!$main::shutdown) {
		$self->_process_check_results();
		$self->_check_host_states();
		$self->_process_commands();
		$self->_distribute_roles();
		$self->send_status_to_agents();

		# sleep 3 seconds, wake up if command queue gets filled
		lock($command_queue);
		cond_timedwait($command_queue, time() + 3); 
	}

	foreach my $thread (@threads) {
		$thread->join();
	}
}


=item _process_check_results

Process the results of the checker thread and change checks_status accordingly. Reads from check_queue.

=cut

sub _process_check_results($) {
	my $self = shift;

	my $cnt = 0;
	while (my $result = $self->checker_queue->dequeue_nb) {
		$cnt++ if $self->checks_status->handle_result($result);
	}
	return $cnt;
}


=item _check_host_states

Check states of hosts and change status/roles accordingly.

=cut

sub _check_host_states($) {
	my $self = shift;

	# Don't do anything if we have no network connection
	return if (!$main::have_net);

	my $checks	= $self->checks_status;
	my $agents	= MMM::Monitor::Agents->instance();

	my $active_master = $self->roles->get_active_master();

	foreach my $host (keys(%{$main::config->{host}})) {

		$agents->save_status() unless ($self->is_passive);

		my $agent		= $agents->get($host);
		my $state		= $agent->state;
		my $ping		= $checks->ping($host);
		my $mysql		= $checks->mysql($host);
		my $rep_backlog	= $checks->rep_backlog($host);
		my $rep_threads	= $checks->rep_threads($host);

		my $peer	= $main::config->{host}->{$host}->{peer};
		if (!$peer && $agent->mode eq 'slave') {
			$peer	= $active_master
		}

		my $peer_state = '';
		my $peer_online_since = 0;
		if ($peer) {
			$peer_state			= $agents->state($peer);
			$peer_online_since	= $agents->online_since($peer);
		}

		# Simply skip this host. It is offlined by admin
		next if ($state eq 'ADMIN_OFFLINE');

		########################################################################

		if ($state eq 'ONLINE') {

			# ONLINE -> HARD_OFFLINE
			unless ($ping && $mysql) {
				FATAL sprintf("State of host '%s' changed from %s to HARD_OFFLINE (ping: %s, mysql: %s)", $host, $state, ($ping? 'OK' : 'not OK'), ($mysql? 'OK' : 'not OK'));
				$agent->state('HARD_OFFLINE');
				next if ($self->is_manual);
				$self->roles->clear_roles($host);
				if (!$self->send_agent_status($host)) {
					ERROR sprintf("Can't send offline status notification to '%s' - killing it!", $host);
					$self->_kill_host($host, $checks->ping($host));
				}
				next;
			}

			# replication failure on active master is irrelevant.
			next if ($host eq $active_master);

			# ignore replication failure, if peer got online recently (60 seconds, default value of master-connect-retry)
			next if ($peer_state eq 'ONLINE' && $peer_online_since >= time() - 60);

			# ONLINE -> REPLICATION_FAIL
			if ($ping && $mysql && !$rep_threads && $peer_state eq 'ONLINE' && $checks->ping($peer) && $checks->mysql($peer)) {
				FATAL "State of host '$host' changed from $state to REPLICATION_FAIL";
				$agent->state('REPLICATION_FAIL');
				next if ($self->is_manual);
				$self->roles->clear_roles($host);
				if (!$self->send_agent_status($host)) {
					ERROR sprintf("Can't send offline status notification to '%s' - killing it!", $host);
					$self->_kill_host($host, $checks->ping($host));
				}
				next;
			}

			# ONLINE -> REPLICATION_DELAY
			if ($ping && $mysql && !$rep_backlog && $rep_threads && $peer_state eq 'ONLINE' && $checks->ping($peer) && $checks->mysql($peer)) {
				FATAL "State of host '$host' changed from $state to REPLICATION_DELAY";
				$agent->state('REPLICATION_DELAY');
				next if ($self->is_manual);
				$self->roles->clear_roles($host);
				if (!$self->send_agent_status($host)) {
					ERROR sprintf("Can't send offline status notification to '%s' - killing it!", $host);
					$self->_kill_host($host, $checks->ping($host));
				}
				next;
			}
			next;
		}

		########################################################################

		if ($state eq 'AWAITING_RECOVERY') {

			# AWAITING_RECOVERY -> HARD_OFFLINE
			unless ($ping && $mysql) {
				FATAL "State of host '$host' changed from $state to HARD_OFFLINE";
				$agent->state('HARD_OFFLINE');
				next;
			}

			# AWAITING_RECOVERY -> ONLINE (if host was offline for a short period)
			if ($ping && $mysql && $rep_backlog && $rep_threads) {
				my $state_diff  = time() - $agent->last_state_change;

				if ($agent->flapping) {
					my $check_state_diff  = time() - $checks->last_change($host);
					# set flapping host ONLINE because of auto_set_online
					next unless (defined($main::config->{monitor}->{auto_set_online}) && $main::config->{monitor}->{auto_set_online} > 0);
					next if ($check_state_diff < $main::config->{monitor}->{flap_duration});
					FATAL sprintf(
						"State of flapping host '%s' changed from %s to ONLINE because of auto_set_online and flap_duration(%d) seconds passed without another failure. It was in state AWAITING_RECOVERY for %d seconds",
						$host,
						$state,
						$main::config->{monitor}->{flap_duration},
						$state_diff
					);
					$agent->state('ONLINE');
					$self->send_agent_status($host);
					next;
				}

				my $uptime_diff = $agent->uptime - $agent->last_uptime;

				# set ONLINE because of small downtime
				if ($agent->last_uptime > 0 && $uptime_diff > 0 && $uptime_diff < 60) {
					FATAL sprintf("State of host '%s' changed from %s to ONLINE because it was down for only %d seconds", $host, $state, $uptime_diff);
					$agent->state('ONLINE');
					$self->send_agent_status($host);
					next;
				}
				# set ONLINE because of auto_set_online
				if (defined($main::config->{monitor}->{auto_set_online}) && $main::config->{monitor}->{auto_set_online} > 0 && $main::config->{monitor}->{auto_set_online} <= $state_diff) {
					FATAL sprintf("State of host '%s' changed from %s to ONLINE because of auto_set_online(%d seconds). It was in state AWAITING_RECOVERY for %d seconds", $host, $state, $main::config->{monitor}->{auto_set_online}, $state_diff);
					$agent->state('ONLINE');
					$self->send_agent_status($host);
					next;
				}
			}
			next;
		}

		########################################################################

		if ($state eq 'HARD_OFFLINE') {

			if ($ping && $mysql) {

				# only if we have an active master or the host can't be the active master 
				if ($active_master ne '' || !$self->roles->can_handle($main::config->{active_master_role}, $host)) {

					# HARD_OFFLINE -> REPLICATION_FAIL
					if (!$rep_threads) {
						FATAL "State of host '$host' changed from $state to REPLICATION_FAIL";
						$agent->state('REPLICATION_FAIL');
						$self->send_agent_status($host);
						next;
					}
	
					# HARD_OFFLINE -> REPLICATION_DELAY
					if (!$rep_backlog) {
						FATAL "State of host '$host' changed from $state to REPLICATION_DELAY";
						$agent->state('REPLICATION_DELAY');
						$self->send_agent_status($host);
						next;
					}
				}

				# HARD_OFFLINE -> AWAITING_RECOVERY
				FATAL "State of host '$host' changed from $state to AWAITING_RECOVERY";
				$agent->state('AWAITING_RECOVERY');
				$self->send_agent_status($host);
				next;
			}
		}

		########################################################################

		if ($state eq 'REPLICATION_FAIL') {
			# REPLICATION_FAIL -> REPLICATION_DELAY
			if ($ping && $mysql && !$rep_backlog && $rep_threads) {
				FATAL "State of host '$host' changed from $state to REPLICATION_DELAY";
				$agent->state('REPLICATION_DELAY');
				next;
			}
		}
		if ($state eq 'REPLICATION_DELAY') {
			# REPLICATION_DELAY -> REPLICATION_FAIL
			if ($ping && $mysql && !$rep_threads) {
				FATAL "State of host '$host' changed from $state to REPLICATION_FAIL";
				$agent->state('REPLICATION_FAIL');
				next;
			}
		}

		########################################################################

		if ($state eq 'REPLICATION_DELAY' || $state eq 'REPLICATION_FAIL') {
			if ($ping && $mysql && (($rep_backlog && $rep_threads) || $peer_state ne 'ONLINE')) {

				# REPLICATION_DELAY || REPLICATION_FAIL -> AWAITING_RECOVERY
				if ($agent->flapping) {
					FATAL "State of host '$host' changed from $state to AWAITING_RECOVERY (because it's flapping)";
					$agent->state('AWAITING_RECOVERY');
					$self->send_agent_status($host);
					next;
				}

				# REPLICATION_DELAY || REPLICATION_FAIL -> ONLINE
				FATAL "State of host '$host' changed from $state to ONLINE";
				$agent->state('ONLINE');
				$self->send_agent_status($host);
				next;
			}

			# REPLICATION_DELAY || REPLICATION_FAIL -> HARD_OFFLINE
			unless ($ping && $mysql) {
				FATAL sprintf("State of host '%s' changed from %s to HARD_OFFLINE (ping: %s, mysql: %s)", $host, $state, ($ping? 'OK' : 'not OK'), ($mysql? 'OK' : 'not OK'));
				$agent->state('HARD_OFFLINE');
				if (!$self->send_agent_status($host)) {
					ERROR sprintf("Can't send offline status notification to '%s' - killing it!", $host);
					$self->_kill_host($host, $checks->ping($host));
				}
				next;
			}
			next;
		}
	}

	if ($self->mode == MMM_MONITOR_MODE_WAIT) {
		my $master_one	= $self->roles->get_first_master();
		my $master_two	= $self->roles->get_second_master();
		my $state_one	= $agents->state($master_one);
		my $state_two	= $agents->state($master_two);

		if ($state_one eq 'ONLINE' && $state_two eq 'ONLINE') {
			INFO "Nodes $master_one and $master_two are ONLINE, switching from mode 'WAIT' to 'ACTIVE'.";
			$self->set_active();
		}
		elsif ($main::config->{monitor}->{wait_for_other_master} > 0 && ($state_one eq 'ONLINE' || $state_two eq 'ONLINE')) {
			my $living_master = $state_one eq 'ONLINE' ? $master_one : $master_two;
			my $dead_master   = $state_one eq 'ONLINE' ? $master_two : $master_one;

			if ($main::config->{monitor}->{wait_for_other_master} <= time() - $agents->online_since($living_master)) {
				$self->set_active();
				WARN sprintf("Master $dead_master did not come online for %d(wait_for_other_master) seconds. Switching from mode 'WAIT' to 'ACTIVE'", $main::config->{monitor}->{wait_for_other_master});
			}

		}
		if ($self->is_active) {
			# cleanup
			foreach my $host (keys(%{$main::config->{host}})) {
				my $host_state = $agents->state($host);
				next if ($host_state eq 'ONLINE' || $self->roles->get_host_roles($host) == 0); 
				my $agent = $agents->get($host); 
				$self->roles->clear_roles($host); 
				my $ret = $self->send_agent_status($host); 
#   			next if ($host_state eq 'REPLICATION_FAIL'); 
#   			next if ($host_state eq 'REPLICATION_DELAY'); 
				# NOTE host_state should never be ADMIN_OFFLINE at this point 
				if (!$ret) { 
					ERROR sprintf("Can't send offline status notification to '%s' - killing it!", $host); 
					$self->_kill_host($host, $checks->ping($host)); 
				} 
			}
		}
	}

	$agents->save_status() unless ($self->is_passive);
}


=item _distribute_roles

Distribute roles among the hosts.

=cut

sub _distribute_roles($) {
	my $self = shift;

	# Never change roles if we are in PASSIVE mode
	return if ($self->is_passive);

	my $old_active_master = $self->roles->get_active_master();
	
	# Process orphaned roles
	$self->roles->process_orphans('exclusive');
	$self->roles->process_orphans('balanced');

	# obey preferences
	$self->roles->obey_preferences() if ($self->is_active);

	# Balance roles
	$self->roles->balance();

	my $new_active_master = $self->roles->get_active_master();

	# notify slaves first, if master host has changed
	unless ($new_active_master eq $old_active_master) {
		$self->send_agent_status($old_active_master, $new_active_master) if ($old_active_master);
		$self->notify_slaves($new_active_master);
	}
}


=item cleanup_and_send_status()

Send status information to all agents and clean up old roles.

=cut
sub cleanup_and_send_status($) {
	my $self	= shift;

	my $agents = MMM::Monitor::Agents->instance();
	my $roles = MMM::Monitor::Roles->instance();

	my $active_master  = $roles->get_active_master();
	my $passive_master = $roles->get_passive_master();

	# Notify passive master first
	if ($passive_master ne '') {
		my $host = $passive_master;
		$self->send_agent_status($host);
		my $agent = $agents->get($host);
		$agent->cmd_clear_bad_roles(); # TODO check result
	}

	# Notify all slave hosts
	foreach my $host (keys(%{$main::config->{host}})) {
		next if ($self->roles->is_master($host));
		$self->send_agent_status($host);
		my $agent = $agents->get($host);
		$agent->cmd_clear_bad_roles(); # TODO check result
	}

	# Notify active master at the end
	if ($active_master ne '') {
		my $host = $active_master;
		$self->send_agent_status($host);
		my $agent = $agents->get($host);
		$agent->cmd_clear_bad_roles(); # TODO check result
	}
}


=item send_status_to_agents

Send status information to all agents.

=cut

sub send_status_to_agents($) {
	my $self	= shift;

	# Send status to all hosts
	my $master	= $self->roles->get_active_master();
	foreach my $host (keys(%{$main::config->{host}})) {
		$self->send_agent_status($host, $master);
	}
}


=item notify_slaves

Notify all slave hosts (used when master changes).

=cut

sub notify_slaves($$) {
	my $self		= shift;
	my $new_master	= shift;

	# Send status to all hosts with mode = 'slave'
	foreach my $host (keys(%{$main::config->{host}})) {
		next unless ($main::config->{host}->{$host}->{mode} eq 'slave');
		$self->send_agent_status($host, $new_master);
	}
}


=item send_agent_status($host[, $master])

Send status information to agent on host $host.

=cut

sub send_agent_status($$$) {
	my $self	= shift;
	my $host	= shift;
	my $master	= shift;

	# Never send anything to agents if we are in PASSIVE mode
	# Never send anything to agents if we have no network connection
	return if ($self->is_passive || !$main::have_net);

	# Determine active master if it was not passed
	$master = $self->roles->get_active_master() unless (defined($master));

	my $agent = MMM::Monitor::Agents->instance()->get($host);

	# Determine and set roles
	my @roles = sort($self->roles->get_host_roles($host));
	$agent->roles(\@roles);

	# Finally send command
	my $ret = $agent->cmd_set_status($master);

	unless ($ret) {
		# If ping is down, nothing will be send to agent. So this doesn't indicate that the agent is down.
		my $checks	= $self->checks_status;
		if ($checks->ping($host) && !$agent->agent_down()) {
			FATAL "Can't reach agent on host '$host'";
			$agent->agent_down(1);
		}
	}
	elsif ($agent->agent_down) {
		FATAL "Agent on host '$host' is reachable again";
		$agent->agent_down(0);
	}
	return $ret;
}


=item _kill_host

Process commands received from the command thread.

=cut

sub _kill_host($$$) {
	my $self		= shift;
	my $host		= shift;
	my $ping		= shift;

	if (!defined($self->kill_host_bin)) {
		FATAL sprintf("Could not kill host '%s' - there may be some duplicate ips now! (There's no binary configured for killing hosts.)", $host);
		return;
	}

	# Executing the kill_host_bin and capturing its output _and_ return code is a bit complicated.
	# We can't use backticks - $? (also called $CHILD_ERROR) will always be undefined because 
	# mmm_mond installs a custom signal handler for SIGCHLD.
	# So we use "system" instead of backticks and redirect the output to a temporary file.
	# To prevent race conditions we use tempfile instead of tmpname, clear the close-on-exec flag
	# and redirect the output of system to '/dev/fd/' . fileno(fh).
	my $fh = File::Temp::tempfile();
	my $flags = fcntl($fh, F_GETFD, 0);
	$flags &= ~FD_CLOEXEC;
	fcntl($fh, F_SETFD, $flags);

	my $command	= sprintf("%s %s %s", $self->kill_host_bin, $host, $ping);
	INFO sprintf("Killing host using command '%s'", $command);
	my $ret = system($command . sprintf(' >/dev/fd/%s 2>&1', fileno($fh)));
	# signal information in the lower 8 bits, exit code above that
	$ret = $ret >> 8;

	my $output = '';
	seek($fh, 0, 0);
	local $/;
	$output = <$fh>;
	close $fh;

	if ($ret == 0) {
		INFO sprintf("Output of kill host command was: %s", $output) if ($output ne "");
		return;
	}

	FATAL sprintf("Could not kill host '%s' - there may be some duplicate ips now! kill_host binary exited with '%s'. Output was: %s ", $host, $ret, $output);
	return;
}

=item _process_commands

Process commands received from the command thread.

=cut

sub _process_commands($) {
	my $self		= shift;

	# Handle all queued commands
	while (my $cmdline = $self->command_queue->dequeue_nb) {

		# Parse command
		my @args	= split(/\s+/, $cmdline);
		my $command	= shift @args;
		my $arg_cnt	= scalar(@args);
		my $res;

		# Execute command
		if    ($command eq 'help'			&& $arg_cnt == 0) { $res = MMM::Monitor::Commands::help();							}
		elsif ($command eq 'ping'			&& $arg_cnt == 0) { $res = MMM::Monitor::Commands::ping();							}
		elsif ($command eq 'show'			&& $arg_cnt == 0) { $res = MMM::Monitor::Commands::show();							}
		elsif ($command eq 'checks'			&& $arg_cnt == 0) { $res = MMM::Monitor::Commands::checks();						}
		elsif ($command eq 'checks'			&& $arg_cnt == 1) { $res = MMM::Monitor::Commands::checks($args[0]);				}
		elsif ($command eq 'checks'			&& $arg_cnt == 2) { $res = MMM::Monitor::Commands::checks($args[0], $args[1]);		}
		elsif ($command eq 'mode'			&& $arg_cnt == 0) { $res = MMM::Monitor::Commands::mode();							}
		elsif ($command eq 'set_active'		&& $arg_cnt == 0) { $res = MMM::Monitor::Commands::set_active();					}
		elsif ($command eq 'set_passive'	&& $arg_cnt == 0) { $res = MMM::Monitor::Commands::set_passive();					}
		elsif ($command eq 'set_manual'		&& $arg_cnt == 0) { $res = MMM::Monitor::Commands::set_manual();					}
		elsif ($command eq 'set_online'		&& $arg_cnt == 1) { $res = MMM::Monitor::Commands::set_online ($args[0]);			}
		elsif ($command eq 'set_offline'	&& $arg_cnt == 1) { $res = MMM::Monitor::Commands::set_offline($args[0]);			}
		elsif ($command eq 'move_role'		&& $arg_cnt == 2) { $res = MMM::Monitor::Commands::move_role($args[0], $args[1]);	}
		elsif ($command eq 'move_role'		&& $arg_cnt == 3 && $args[0] eq "--force") {
			$res = MMM::Monitor::Commands::forced_move_role($args[1], $args[2]);
		}
		elsif ($command eq 'set_ip'			&& $arg_cnt == 2) { $res = MMM::Monitor::Commands::set_ip($args[0], $args[1]);		}
		else { $res = "Invalid command '$cmdline'\n\n" . MMM::Monitor::Commands::help(); }

		# Enqueue result
		$self->result_queue->enqueue($res);
	}
}


=item is_active()

Check if monitor is in active mode

=cut

sub is_active($$) {
	my $self	= shift;
	return ($self->mode == MMM_MONITOR_MODE_ACTIVE);
}


=item is_manual()

Check if monitor is in manual mode

=cut

sub is_manual($$) {
	my $self	= shift;
	return ($self->mode == MMM_MONITOR_MODE_MANUAL || $self->mode == MMM_MONITOR_MODE_WAIT);
}


=item is_passive()

Check if monitor is in passive mode

=cut

sub is_passive($$) {
	my $self	= shift;
	return ($self->mode == MMM_MONITOR_MODE_PASSIVE);
}


=item set_active()

Set mode to active

=cut

sub set_active($$) {
	my $self	= shift;
	$self->mode(MMM_MONITOR_MODE_ACTIVE);
}


=item set_manual()

Set mode to manual

=cut

sub set_manual($$) {
	my $self	= shift;
	$self->mode(MMM_MONITOR_MODE_MANUAL);
}


=item set_passive()

Set mode to passive

=cut

sub set_passive($$) {
	my $self	= shift;
	$self->mode(MMM_MONITOR_MODE_PASSIVE);
}


=item get_mode_string()

Get string representation of current mode

=cut

sub get_mode_string($) {
	my $self	= shift;
	return 'ACTIVE'  if ($self->mode == MMM_MONITOR_MODE_ACTIVE);
	return 'MANUAL'  if ($self->mode == MMM_MONITOR_MODE_MANUAL);
	return 'WAIT'    if ($self->mode == MMM_MONITOR_MODE_WAIT);
	return 'PASSIVE' if ($self->mode == MMM_MONITOR_MODE_PASSIVE);
	return 'UNKNOWN'; # should never happen
}

1;