mha4mysql-node-0.54/0000755000000000000000000000000012056326664013014 5ustar rootrootmha4mysql-node-0.54/t/0000755000000000000000000000000012056326664013257 5ustar rootrootmha4mysql-node-0.54/t/perlcriticrc0000644000000000000000000000012011770663665015667 0ustar rootroot# allow prototypes in soubroutines [-Subroutines::ProhibitSubroutinePrototypes] mha4mysql-node-0.54/t/99-perlcritic.t0000644000000000000000000000033111770663665016047 0ustar rootrootuse strict; use Test::More; eval { require Test::Perl::Critic; Test::Perl::Critic->import(-profile => "t/perlcriticrc") }; plan skip_all => "Test::Perl::Critic is not installed." if $@; all_critic_ok("bin", "lib"); mha4mysql-node-0.54/README0000644000000000000000000000044011770663665013701 0ustar rootrootmha4mysql-node - Master High Availability Manager and tools for MySQL (MHA) for automating master failover and fast master switch. This package contains utility scripts running on a MySQL server machine. See http://code.google.com/p/mysql-master-ha/wiki/TableOfContents?tm=6 for details. mha4mysql-node-0.54/debian/0000755000000000000000000000000012056326664014236 5ustar rootrootmha4mysql-node-0.54/debian/compat0000644000000000000000000000000211770663665015443 0ustar rootroot7 mha4mysql-node-0.54/debian/copyright0000644000000000000000000000060511770663665016201 0ustar rootrootIt was downloaded from http://code.google.com/p/mysql-master-ha/ Upstream Author(s): Yoshinori Matsunobu Copyright: Copyright (C) 2011 DeNA Co.,Ltd. License: GPLv2 See `cat /usr/share/common-licenses/GPL-2`. The Debian packaging is done by Yoshinori Matsunobu in 2011, and is licensed under the GPL v2 license. mha4mysql-node-0.54/debian/control0000644000000000000000000000071111770663665015647 0ustar rootrootSource: mha4mysql-node Section: perl Priority: optional Build-Depends: debhelper (>= 7.2.13) Build-Depends-Indep: perl Maintainer: Yoshinori Matsunobu Standards-Version: 3.9.1 Homepage: http://code.google.com/p/mysql-master-ha/ Package: mha4mysql-node Architecture: all Depends: ${misc:Depends}, ${perl:Depends}, libdbi-perl, libdbd-mysql-perl Description: Master High Availability Manager and Tools for MySQL, Node Package mha4mysql-node-0.54/debian/changelog0000644000000000000000000000107711770663665016124 0ustar rootrootmha4mysql-node (0.53) stable; urgency=low * (Note: All changelogs are written here: http://code.google.com/p/mysql-master-ha/wiki/ReleaseNotes ) * Version 0.53 -- Yoshinori Matsunobu Mon, 9 Jan 2012 00:00:00 +0000 mha4mysql-node (0.52) stable; urgency=low * Version 0.52 (0.51 was skipped) -- Yoshinori Matsunobu Fri, 16 Sep 2011 00:00:00 +0000 mha4mysql-node (0.50) stable; urgency=low * Version 0.50 -- Yoshinori Matsunobu Sat, 23 Jul 2011 00:00:00 +0000 mha4mysql-node-0.54/debian/rules0000755000000000000000000000003611770663665015324 0ustar rootroot#!/usr/bin/make -f %: dh $@ mha4mysql-node-0.54/inc/0000755000000000000000000000000012056326663013564 5ustar rootrootmha4mysql-node-0.54/inc/Module/0000755000000000000000000000000012056326663015011 5ustar rootrootmha4mysql-node-0.54/inc/Module/Install/0000755000000000000000000000000012056326664016420 5ustar rootrootmha4mysql-node-0.54/inc/Module/Install/Scripts.pm0000644000000000000000000000101112056326652020373 0ustar rootroot#line 1 package Module::Install::Scripts; use strict 'vars'; use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91'; @ISA = 'Module::Install::Base'; $ISCORE = 1; } sub install_script { my $self = shift; my $args = $self->makemaker_args; my $exe = $args->{EXE_FILES} ||= []; foreach ( @_ ) { if ( -f $_ ) { push @$exe, $_; } elsif ( -d 'script' and -f "script/$_" ) { push @$exe, "script/$_"; } else { die("Cannot find script '$_'"); } } } 1; mha4mysql-node-0.54/inc/Module/Install/Win32.pm0000644000000000000000000000340312056326653017656 0ustar rootroot#line 1 package Module::Install::Win32; use strict; use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91'; @ISA = 'Module::Install::Base'; $ISCORE = 1; } # determine if the user needs nmake, and download it if needed sub check_nmake { my $self = shift; $self->load('can_run'); $self->load('get_file'); require Config; return unless ( $^O eq 'MSWin32' and $Config::Config{make} and $Config::Config{make} =~ /^nmake\b/i and ! $self->can_run('nmake') ); print "The required 'nmake' executable not found, fetching it...\n"; require File::Basename; my $rv = $self->get_file( url => 'http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe', ftp_url => 'ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe', local_dir => File::Basename::dirname($^X), size => 51928, run => 'Nmake15.exe /o > nul', check_for => 'Nmake.exe', remove => 1, ); die <<'END_MESSAGE' unless $rv; ------------------------------------------------------------------------------- Since you are using Microsoft Windows, you will need the 'nmake' utility before installation. It's available at: http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe or ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe Please download the file manually, save it to a directory in %PATH% (e.g. C:\WINDOWS\COMMAND\), then launch the MS-DOS command line shell, "cd" to that directory, and run "Nmake15.exe" from there; that will create the 'nmake.exe' file needed by this module. You may then resume the installation process described in README. ------------------------------------------------------------------------------- END_MESSAGE } 1; mha4mysql-node-0.54/inc/Module/Install/Fetch.pm0000644000000000000000000000462712056326653020016 0ustar rootroot#line 1 package Module::Install::Fetch; use strict; use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91'; @ISA = 'Module::Install::Base'; $ISCORE = 1; } sub get_file { my ($self, %args) = @_; my ($scheme, $host, $path, $file) = $args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return; if ( $scheme eq 'http' and ! eval { require LWP::Simple; 1 } ) { $args{url} = $args{ftp_url} or (warn("LWP support unavailable!\n"), return); ($scheme, $host, $path, $file) = $args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return; } $|++; print "Fetching '$file' from $host... "; unless (eval { require Socket; Socket::inet_aton($host) }) { warn "'$host' resolve failed!\n"; return; } return unless $scheme eq 'ftp' or $scheme eq 'http'; require Cwd; my $dir = Cwd::getcwd(); chdir $args{local_dir} or return if exists $args{local_dir}; if (eval { require LWP::Simple; 1 }) { LWP::Simple::mirror($args{url}, $file); } elsif (eval { require Net::FTP; 1 }) { eval { # use Net::FTP to get past firewall my $ftp = Net::FTP->new($host, Passive => 1, Timeout => 600); $ftp->login("anonymous", 'anonymous@example.com'); $ftp->cwd($path); $ftp->binary; $ftp->get($file) or (warn("$!\n"), return); $ftp->quit; } } elsif (my $ftp = $self->can_run('ftp')) { eval { # no Net::FTP, fallback to ftp.exe require FileHandle; my $fh = FileHandle->new; local $SIG{CHLD} = 'IGNORE'; unless ($fh->open("|$ftp -n")) { warn "Couldn't open ftp: $!\n"; chdir $dir; return; } my @dialog = split(/\n/, <<"END_FTP"); open $host user anonymous anonymous\@example.com cd $path binary get $file $file quit END_FTP foreach (@dialog) { $fh->print("$_\n") } $fh->close; } } else { warn "No working 'ftp' program available!\n"; chdir $dir; return; } unless (-f $file) { warn "Fetching failed: $@\n"; chdir $dir; return; } return if exists $args{size} and -s $file != $args{size}; system($args{run}) if exists $args{run}; unlink($file) if $args{remove}; print(((!exists $args{check_for} or -e $args{check_for}) ? "done!" : "failed! ($!)"), "\n"); chdir $dir; return !$?; } 1; mha4mysql-node-0.54/inc/Module/Install/WriteAll.pm0000644000000000000000000000222212056326653020475 0ustar rootroot#line 1 package Module::Install::WriteAll; use strict; use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91';; @ISA = qw{Module::Install::Base}; $ISCORE = 1; } sub WriteAll { my $self = shift; my %args = ( meta => 1, sign => 0, inline => 0, check_nmake => 1, @_, ); $self->sign(1) if $args{sign}; $self->admin->WriteAll(%args) if $self->is_admin; $self->check_nmake if $args{check_nmake}; unless ( $self->makemaker_args->{PL_FILES} ) { $self->makemaker_args( PL_FILES => {} ); } # Until ExtUtils::MakeMaker support MYMETA.yml, make sure # we clean it up properly ourself. $self->realclean_files('MYMETA.yml'); if ( $args{inline} ) { $self->Inline->write; } else { $self->Makefile->write; } # The Makefile write process adds a couple of dependencies, # so write the META.yml files after the Makefile. if ( $args{meta} ) { $self->Meta->write; } # Experimental support for MYMETA if ( $ENV{X_MYMETA} ) { if ( $ENV{X_MYMETA} eq 'JSON' ) { $self->Meta->write_mymeta_json; } else { $self->Meta->write_mymeta_yaml; } } return 1; } 1; mha4mysql-node-0.54/inc/Module/Install/Can.pm0000644000000000000000000000333312056326653017457 0ustar rootroot#line 1 package Module::Install::Can; use strict; use Config (); use File::Spec (); use ExtUtils::MakeMaker (); use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91'; @ISA = 'Module::Install::Base'; $ISCORE = 1; } # check if we can load some module ### Upgrade this to not have to load the module if possible sub can_use { my ($self, $mod, $ver) = @_; $mod =~ s{::|\\}{/}g; $mod .= '.pm' unless $mod =~ /\.pm$/i; my $pkg = $mod; $pkg =~ s{/}{::}g; $pkg =~ s{\.pm$}{}i; local $@; eval { require $mod; $pkg->VERSION($ver || 0); 1 }; } # check if we can run some command sub can_run { my ($self, $cmd) = @_; my $_cmd = $cmd; return $_cmd if (-x $_cmd or $_cmd = MM->maybe_command($_cmd)); for my $dir ((split /$Config::Config{path_sep}/, $ENV{PATH}), '.') { next if $dir eq ''; my $abs = File::Spec->catfile($dir, $_[1]); return $abs if (-x $abs or $abs = MM->maybe_command($abs)); } return; } # can we locate a (the) C compiler sub can_cc { my $self = shift; my @chunks = split(/ /, $Config::Config{cc}) or return; # $Config{cc} may contain args; try to find out the program part while (@chunks) { return $self->can_run("@chunks") || (pop(@chunks), next); } return; } # Fix Cygwin bug on maybe_command(); if ( $^O eq 'cygwin' ) { require ExtUtils::MM_Cygwin; require ExtUtils::MM_Win32; if ( ! defined(&ExtUtils::MM_Cygwin::maybe_command) ) { *ExtUtils::MM_Cygwin::maybe_command = sub { my ($self, $file) = @_; if ($file =~ m{^/cygdrive/}i and ExtUtils::MM_Win32->can('maybe_command')) { ExtUtils::MM_Win32->maybe_command($file); } else { ExtUtils::MM_Unix->maybe_command($file); } } } } 1; __END__ #line 156 mha4mysql-node-0.54/inc/Module/Install/Base.pm0000644000000000000000000000176612056326652017637 0ustar rootroot#line 1 package Module::Install::Base; use strict 'vars'; use vars qw{$VERSION}; BEGIN { $VERSION = '0.91'; } # Suspend handler for "redefined" warnings BEGIN { my $w = $SIG{__WARN__}; $SIG{__WARN__} = sub { $w }; } #line 42 sub new { my $class = shift; unless ( defined &{"${class}::call"} ) { *{"${class}::call"} = sub { shift->_top->call(@_) }; } unless ( defined &{"${class}::load"} ) { *{"${class}::load"} = sub { shift->_top->load(@_) }; } bless { @_ }, $class; } #line 61 sub AUTOLOAD { local $@; my $func = eval { shift->_top->autoload } or return; goto &$func; } #line 75 sub _top { $_[0]->{_top}; } #line 90 sub admin { $_[0]->_top->{admin} or Module::Install::Base::FakeAdmin->new; } #line 106 sub is_admin { $_[0]->admin->VERSION; } sub DESTROY {} package Module::Install::Base::FakeAdmin; my $fake; sub new { $fake ||= bless(\@_, $_[0]); } sub AUTOLOAD {} sub DESTROY {} # Restore warning handler BEGIN { $SIG{__WARN__} = $SIG{__WARN__}->(); } 1; #line 154 mha4mysql-node-0.54/inc/Module/Install/Makefile.pm0000644000000000000000000001600312056326652020470 0ustar rootroot#line 1 package Module::Install::Makefile; use strict 'vars'; use ExtUtils::MakeMaker (); use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91'; @ISA = 'Module::Install::Base'; $ISCORE = 1; } sub Makefile { $_[0] } my %seen = (); sub prompt { shift; # Infinite loop protection my @c = caller(); if ( ++$seen{"$c[1]|$c[2]|$_[0]"} > 3 ) { die "Caught an potential prompt infinite loop ($c[1]|$c[2]|$_[0])"; } # In automated testing, always use defaults if ( $ENV{AUTOMATED_TESTING} and ! $ENV{PERL_MM_USE_DEFAULT} ) { local $ENV{PERL_MM_USE_DEFAULT} = 1; goto &ExtUtils::MakeMaker::prompt; } else { goto &ExtUtils::MakeMaker::prompt; } } sub makemaker_args { my $self = shift; my $args = ( $self->{makemaker_args} ||= {} ); %$args = ( %$args, @_ ); return $args; } # For mm args that take multiple space-seperated args, # append an argument to the current list. sub makemaker_append { my $self = sShift; my $name = shift; my $args = $self->makemaker_args; $args->{name} = defined $args->{$name} ? join( ' ', $args->{name}, @_ ) : join( ' ', @_ ); } sub build_subdirs { my $self = shift; my $subdirs = $self->makemaker_args->{DIR} ||= []; for my $subdir (@_) { push @$subdirs, $subdir; } } sub clean_files { my $self = shift; my $clean = $self->makemaker_args->{clean} ||= {}; %$clean = ( %$clean, FILES => join ' ', grep { length $_ } ($clean->{FILES} || (), @_), ); } sub realclean_files { my $self = shift; my $realclean = $self->makemaker_args->{realclean} ||= {}; %$realclean = ( %$realclean, FILES => join ' ', grep { length $_ } ($realclean->{FILES} || (), @_), ); } sub libs { my $self = shift; my $libs = ref $_[0] ? shift : [ shift ]; $self->makemaker_args( LIBS => $libs ); } sub inc { my $self = shift; $self->makemaker_args( INC => shift ); } my %test_dir = (); sub _wanted_t { /\.t$/ and -f $_ and $test_dir{$File::Find::dir} = 1; } sub tests_recursive { my $self = shift; if ( $self->tests ) { die "tests_recursive will not work if tests are already defined"; } my $dir = shift || 't'; unless ( -d $dir ) { die "tests_recursive dir '$dir' does not exist"; } %test_dir = (); require File::Find; File::Find::find( \&_wanted_t, $dir ); $self->tests( join ' ', map { "$_/*.t" } sort keys %test_dir ); } sub write { my $self = shift; die "&Makefile->write() takes no arguments\n" if @_; # Check the current Perl version my $perl_version = $self->perl_version; if ( $perl_version ) { eval "use $perl_version; 1" or die "ERROR: perl: Version $] is installed, " . "but we need version >= $perl_version"; } # Make sure we have a new enough MakeMaker require ExtUtils::MakeMaker; if ( $perl_version and $self->_cmp($perl_version, '5.006') >= 0 ) { # MakeMaker can complain about module versions that include # an underscore, even though its own version may contain one! # Hence the funny regexp to get rid of it. See RT #35800 # for details. $self->build_requires( 'ExtUtils::MakeMaker' => $ExtUtils::MakeMaker::VERSION =~ /^(\d+\.\d+)/ ); $self->configure_requires( 'ExtUtils::MakeMaker' => $ExtUtils::MakeMaker::VERSION =~ /^(\d+\.\d+)/ ); } else { # Allow legacy-compatibility with 5.005 by depending on the # most recent EU:MM that supported 5.005. $self->build_requires( 'ExtUtils::MakeMaker' => 6.42 ); $self->configure_requires( 'ExtUtils::MakeMaker' => 6.42 ); } # Generate the MakeMaker params my $args = $self->makemaker_args; $args->{DISTNAME} = $self->name; $args->{NAME} = $self->module_name || $self->name; $args->{VERSION} = $self->version; $args->{NAME} =~ s/-/::/g; if ( $self->tests ) { $args->{test} = { TESTS => $self->tests }; } if ( $] >= 5.005 ) { $args->{ABSTRACT} = $self->abstract; $args->{AUTHOR} = $self->author; } if ( eval($ExtUtils::MakeMaker::VERSION) >= 6.10 ) { $args->{NO_META} = 1; } if ( eval($ExtUtils::MakeMaker::VERSION) > 6.17 and $self->sign ) { $args->{SIGN} = 1; } unless ( $self->is_admin ) { delete $args->{SIGN}; } # Merge both kinds of requires into prereq_pm my $prereq = ($args->{PREREQ_PM} ||= {}); %$prereq = ( %$prereq, map { @$_ } map { @$_ } grep $_, ($self->configure_requires, $self->build_requires, $self->requires) ); # Remove any reference to perl, PREREQ_PM doesn't support it delete $args->{PREREQ_PM}->{perl}; # merge both kinds of requires into prereq_pm my $subdirs = ($args->{DIR} ||= []); if ($self->bundles) { foreach my $bundle (@{ $self->bundles }) { my ($file, $dir) = @$bundle; push @$subdirs, $dir if -d $dir; delete $prereq->{$file}; } } if ( my $perl_version = $self->perl_version ) { eval "use $perl_version; 1" or die "ERROR: perl: Version $] is installed, " . "but we need version >= $perl_version"; } $args->{INSTALLDIRS} = $self->installdirs; my %args = map { ( $_ => $args->{$_} ) } grep {defined($args->{$_})} keys %$args; my $user_preop = delete $args{dist}->{PREOP}; if (my $preop = $self->admin->preop($user_preop)) { foreach my $key ( keys %$preop ) { $args{dist}->{$key} = $preop->{$key}; } } my $mm = ExtUtils::MakeMaker::WriteMakefile(%args); $self->fix_up_makefile($mm->{FIRST_MAKEFILE} || 'Makefile'); } sub fix_up_makefile { my $self = shift; my $makefile_name = shift; my $top_class = ref($self->_top) || ''; my $top_version = $self->_top->VERSION || ''; my $preamble = $self->preamble ? "# Preamble by $top_class $top_version\n" . $self->preamble : ''; my $postamble = "# Postamble by $top_class $top_version\n" . ($self->postamble || ''); local *MAKEFILE; open MAKEFILE, "< $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!"; my $makefile = do { local $/; }; close MAKEFILE or die $!; $makefile =~ s/\b(test_harness\(\$\(TEST_VERBOSE\), )/$1'inc', /; $makefile =~ s/( -I\$\(INST_ARCHLIB\))/ -Iinc$1/g; $makefile =~ s/( "-I\$\(INST_LIB\)")/ "-Iinc"$1/g; $makefile =~ s/^(FULLPERL = .*)/$1 "-Iinc"/m; $makefile =~ s/^(PERL = .*)/$1 "-Iinc"/m; # Module::Install will never be used to build the Core Perl # Sometimes PERL_LIB and PERL_ARCHLIB get written anyway, which breaks # PREFIX/PERL5LIB, and thus, install_share. Blank them if they exist $makefile =~ s/^PERL_LIB = .+/PERL_LIB =/m; #$makefile =~ s/^PERL_ARCHLIB = .+/PERL_ARCHLIB =/m; # Perl 5.005 mentions PERL_LIB explicitly, so we have to remove that as well. $makefile =~ s/(\"?)-I\$\(PERL_LIB\)\1//g; # XXX - This is currently unused; not sure if it breaks other MM-users # $makefile =~ s/^pm_to_blib\s+:\s+/pm_to_blib :: /mg; open MAKEFILE, "> $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!"; print MAKEFILE "$preamble$makefile$postamble" or die $!; close MAKEFILE or die $!; 1; } sub preamble { my ($self, $text) = @_; $self->{preamble} = $text . $self->{preamble} if defined $text; $self->{preamble}; } sub postamble { my ($self, $text) = @_; $self->{postamble} ||= $self->admin->postamble; $self->{postamble} .= $text if defined $text; $self->{postamble} } 1; __END__ #line 394 mha4mysql-node-0.54/inc/Module/Install/Metadata.pm0000644000000000000000000003530412056326652020500 0ustar rootroot#line 1 package Module::Install::Metadata; use strict 'vars'; use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91'; @ISA = 'Module::Install::Base'; $ISCORE = 1; } my @boolean_keys = qw{ sign }; my @scalar_keys = qw{ name module_name abstract author version distribution_type tests installdirs }; my @tuple_keys = qw{ configure_requires build_requires requires recommends bundles resources }; my @resource_keys = qw{ homepage bugtracker repository }; my @array_keys = qw{ keywords }; sub Meta { shift } sub Meta_BooleanKeys { @boolean_keys } sub Meta_ScalarKeys { @scalar_keys } sub Meta_TupleKeys { @tuple_keys } sub Meta_ResourceKeys { @resource_keys } sub Meta_ArrayKeys { @array_keys } foreach my $key ( @boolean_keys ) { *$key = sub { my $self = shift; if ( defined wantarray and not @_ ) { return $self->{values}->{$key}; } $self->{values}->{$key} = ( @_ ? $_[0] : 1 ); return $self; }; } foreach my $key ( @scalar_keys ) { *$key = sub { my $self = shift; return $self->{values}->{$key} if defined wantarray and !@_; $self->{values}->{$key} = shift; return $self; }; } foreach my $key ( @array_keys ) { *$key = sub { my $self = shift; return $self->{values}->{$key} if defined wantarray and !@_; $self->{values}->{$key} ||= []; push @{$self->{values}->{$key}}, @_; return $self; }; } foreach my $key ( @resource_keys ) { *$key = sub { my $self = shift; unless ( @_ ) { return () unless $self->{values}->{resources}; return map { $_->[1] } grep { $_->[0] eq $key } @{ $self->{values}->{resources} }; } return $self->{values}->{resources}->{$key} unless @_; my $uri = shift or die( "Did not provide a value to $key()" ); $self->resources( $key => $uri ); return 1; }; } foreach my $key ( grep { $_ ne "resources" } @tuple_keys) { *$key = sub { my $self = shift; return $self->{values}->{$key} unless @_; my @added; while ( @_ ) { my $module = shift or last; my $version = shift || 0; push @added, [ $module, $version ]; } push @{ $self->{values}->{$key} }, @added; return map {@$_} @added; }; } # Resource handling my %lc_resource = map { $_ => 1 } qw{ homepage license bugtracker repository }; sub resources { my $self = shift; while ( @_ ) { my $name = shift or last; my $value = shift or next; if ( $name eq lc $name and ! $lc_resource{$name} ) { die("Unsupported reserved lowercase resource '$name'"); } $self->{values}->{resources} ||= []; push @{ $self->{values}->{resources} }, [ $name, $value ]; } $self->{values}->{resources}; } # Aliases for build_requires that will have alternative # meanings in some future version of META.yml. sub test_requires { shift->build_requires(@_) } sub install_requires { shift->build_requires(@_) } # Aliases for installdirs options sub install_as_core { $_[0]->installdirs('perl') } sub install_as_cpan { $_[0]->installdirs('site') } sub install_as_site { $_[0]->installdirs('site') } sub install_as_vendor { $_[0]->installdirs('vendor') } sub dynamic_config { my $self = shift; unless ( @_ ) { warn "You MUST provide an explicit true/false value to dynamic_config\n"; return $self; } $self->{values}->{dynamic_config} = $_[0] ? 1 : 0; return 1; } sub perl_version { my $self = shift; return $self->{values}->{perl_version} unless @_; my $version = shift or die( "Did not provide a value to perl_version()" ); # Normalize the version $version = $self->_perl_version($version); # We don't support the reall old versions unless ( $version >= 5.005 ) { die "Module::Install only supports 5.005 or newer (use ExtUtils::MakeMaker)\n"; } $self->{values}->{perl_version} = $version; } #Stolen from M::B my %license_urls = ( perl => 'http://dev.perl.org/licenses/', apache => 'http://apache.org/licenses/LICENSE-2.0', artistic => 'http://opensource.org/licenses/artistic-license.php', artistic_2 => 'http://opensource.org/licenses/artistic-license-2.0.php', lgpl => 'http://opensource.org/licenses/lgpl-license.php', lgpl2 => 'http://opensource.org/licenses/lgpl-2.1.php', lgpl3 => 'http://opensource.org/licenses/lgpl-3.0.html', bsd => 'http://opensource.org/licenses/bsd-license.php', gpl => 'http://opensource.org/licenses/gpl-license.php', gpl2 => 'http://opensource.org/licenses/gpl-2.0.php', gpl3 => 'http://opensource.org/licenses/gpl-3.0.html', mit => 'http://opensource.org/licenses/mit-license.php', mozilla => 'http://opensource.org/licenses/mozilla1.1.php', open_source => undef, unrestricted => undef, restrictive => undef, unknown => undef, ); sub license { my $self = shift; return $self->{values}->{license} unless @_; my $license = shift or die( 'Did not provide a value to license()' ); $self->{values}->{license} = $license; # Automatically fill in license URLs if ( $license_urls{$license} ) { $self->resources( license => $license_urls{$license} ); } return 1; } sub all_from { my ( $self, $file ) = @_; unless ( defined($file) ) { my $name = $self->name or die( "all_from called with no args without setting name() first" ); $file = join('/', 'lib', split(/-/, $name)) . '.pm'; $file =~ s{.*/}{} unless -e $file; unless ( -e $file ) { die("all_from cannot find $file from $name"); } } unless ( -f $file ) { die("The path '$file' does not exist, or is not a file"); } # Some methods pull from POD instead of code. # If there is a matching .pod, use that instead my $pod = $file; $pod =~ s/\.pm$/.pod/i; $pod = $file unless -e $pod; # Pull the different values $self->name_from($file) unless $self->name; $self->version_from($file) unless $self->version; $self->perl_version_from($file) unless $self->perl_version; $self->author_from($pod) unless $self->author; $self->license_from($pod) unless $self->license; $self->abstract_from($pod) unless $self->abstract; return 1; } sub provides { my $self = shift; my $provides = ( $self->{values}->{provides} ||= {} ); %$provides = (%$provides, @_) if @_; return $provides; } sub auto_provides { my $self = shift; return $self unless $self->is_admin; unless (-e 'MANIFEST') { warn "Cannot deduce auto_provides without a MANIFEST, skipping\n"; return $self; } # Avoid spurious warnings as we are not checking manifest here. local $SIG{__WARN__} = sub {1}; require ExtUtils::Manifest; local *ExtUtils::Manifest::manicheck = sub { return }; require Module::Build; my $build = Module::Build->new( dist_name => $self->name, dist_version => $self->version, license => $self->license, ); $self->provides( %{ $build->find_dist_packages || {} } ); } sub feature { my $self = shift; my $name = shift; my $features = ( $self->{values}->{features} ||= [] ); my $mods; if ( @_ == 1 and ref( $_[0] ) ) { # The user used ->feature like ->features by passing in the second # argument as a reference. Accomodate for that. $mods = $_[0]; } else { $mods = \@_; } my $count = 0; push @$features, ( $name => [ map { ref($_) ? ( ref($_) eq 'HASH' ) ? %$_ : @$_ : $_ } @$mods ] ); return @$features; } sub features { my $self = shift; while ( my ( $name, $mods ) = splice( @_, 0, 2 ) ) { $self->feature( $name, @$mods ); } return $self->{values}->{features} ? @{ $self->{values}->{features} } : (); } sub no_index { my $self = shift; my $type = shift; push @{ $self->{values}->{no_index}->{$type} }, @_ if $type; return $self->{values}->{no_index}; } sub read { my $self = shift; $self->include_deps( 'YAML::Tiny', 0 ); require YAML::Tiny; my $data = YAML::Tiny::LoadFile('META.yml'); # Call methods explicitly in case user has already set some values. while ( my ( $key, $value ) = each %$data ) { next unless $self->can($key); if ( ref $value eq 'HASH' ) { while ( my ( $module, $version ) = each %$value ) { $self->can($key)->($self, $module => $version ); } } else { $self->can($key)->($self, $value); } } return $self; } sub write { my $self = shift; return $self unless $self->is_admin; $self->admin->write_meta; return $self; } sub version_from { require ExtUtils::MM_Unix; my ( $self, $file ) = @_; $self->version( ExtUtils::MM_Unix->parse_version($file) ); } sub abstract_from { require ExtUtils::MM_Unix; my ( $self, $file ) = @_; $self->abstract( bless( { DISTNAME => $self->name }, 'ExtUtils::MM_Unix' )->parse_abstract($file) ); } # Add both distribution and module name sub name_from { my ($self, $file) = @_; if ( Module::Install::_read($file) =~ m/ ^ \s* package \s* ([\w:]+) \s* ; /ixms ) { my ($name, $module_name) = ($1, $1); $name =~ s{::}{-}g; $self->name($name); unless ( $self->module_name ) { $self->module_name($module_name); } } else { die("Cannot determine name from $file\n"); } } sub perl_version_from { my $self = shift; if ( Module::Install::_read($_[0]) =~ m/ ^ (?:use|require) \s* v? ([\d_\.]+) \s* ; /ixms ) { my $perl_version = $1; $perl_version =~ s{_}{}g; $self->perl_version($perl_version); } else { warn "Cannot determine perl version info from $_[0]\n"; return; } } sub author_from { my $self = shift; my $content = Module::Install::_read($_[0]); if ($content =~ m/ =head \d \s+ (?:authors?)\b \s* ([^\n]*) | =head \d \s+ (?:licen[cs]e|licensing|copyright|legal)\b \s* .*? copyright .*? \d\d\d[\d.]+ \s* (?:\bby\b)? \s* ([^\n]*) /ixms) { my $author = $1 || $2; $author =~ s{E}{<}g; $author =~ s{E}{>}g; $self->author($author); } else { warn "Cannot determine author info from $_[0]\n"; } } sub license_from { my $self = shift; if ( Module::Install::_read($_[0]) =~ m/ ( =head \d \s+ (?:licen[cs]e|licensing|copyright|legal)\b .*? ) (=head\\d.*|=cut.*|) \z /ixms ) { my $license_text = $1; my @phrases = ( 'under the same (?:terms|license) as (?:perl|the perl programming language) itself' => 'perl', 1, 'GNU general public license' => 'gpl', 1, 'GNU public license' => 'gpl', 1, 'GNU lesser general public license' => 'lgpl', 1, 'GNU lesser public license' => 'lgpl', 1, 'GNU library general public license' => 'lgpl', 1, 'GNU library public license' => 'lgpl', 1, 'BSD license' => 'bsd', 1, 'Artistic license' => 'artistic', 1, 'GPL' => 'gpl', 1, 'LGPL' => 'lgpl', 1, 'BSD' => 'bsd', 1, 'Artistic' => 'artistic', 1, 'MIT' => 'mit', 1, 'proprietary' => 'proprietary', 0, ); while ( my ($pattern, $license, $osi) = splice(@phrases, 0, 3) ) { $pattern =~ s{\s+}{\\s+}g; if ( $license_text =~ /\b$pattern\b/i ) { $self->license($license); return 1; } } } warn "Cannot determine license info from $_[0]\n"; return 'unknown'; } sub _extract_bugtracker { my @links = $_[0] =~ m#L<(\Qhttp://rt.cpan.org/\E[^>]+)>#g; my %links; @links{@links}=(); @links=keys %links; return @links; } sub bugtracker_from { my $self = shift; my $content = Module::Install::_read($_[0]); my @links = _extract_bugtracker($content); unless ( @links ) { warn "Cannot determine bugtracker info from $_[0]\n"; return 0; } if ( @links > 1 ) { warn "Found more than on rt.cpan.org link in $_[0]\n"; return 0; } # Set the bugtracker bugtracker( $links[0] ); return 1; } sub requires_from { my $self = shift; my $content = Module::Install::_readperl($_[0]); my @requires = $content =~ m/^use\s+([^\W\d]\w*(?:::\w+)*)\s+([\d\.]+)/mg; while ( @requires ) { my $module = shift @requires; my $version = shift @requires; $self->requires( $module => $version ); } } sub test_requires_from { my $self = shift; my $content = Module::Install::_readperl($_[0]); my @requires = $content =~ m/^use\s+([^\W\d]\w*(?:::\w+)*)\s+([\d\.]+)/mg; while ( @requires ) { my $module = shift @requires; my $version = shift @requires; $self->test_requires( $module => $version ); } } # Convert triple-part versions (eg, 5.6.1 or 5.8.9) to # numbers (eg, 5.006001 or 5.008009). # Also, convert double-part versions (eg, 5.8) sub _perl_version { my $v = $_[-1]; $v =~ s/^([1-9])\.([1-9]\d?\d?)$/sprintf("%d.%03d",$1,$2)/e; $v =~ s/^([1-9])\.([1-9]\d?\d?)\.(0|[1-9]\d?\d?)$/sprintf("%d.%03d%03d",$1,$2,$3 || 0)/e; $v =~ s/(\.\d\d\d)000$/$1/; $v =~ s/_.+$//; if ( ref($v) ) { # Numify $v = $v + 0; } return $v; } ###################################################################### # MYMETA Support sub WriteMyMeta { die "WriteMyMeta has been deprecated"; } sub write_mymeta_yaml { my $self = shift; # We need YAML::Tiny to write the MYMETA.yml file unless ( eval { require YAML::Tiny; 1; } ) { return 1; } # Generate the data my $meta = $self->_write_mymeta_data or return 1; # Save as the MYMETA.yml file print "Writing MYMETA.yml\n"; YAML::Tiny::DumpFile('MYMETA.yml', $meta); } sub write_mymeta_json { my $self = shift; # We need JSON to write the MYMETA.json file unless ( eval { require JSON; 1; } ) { return 1; } # Generate the data my $meta = $self->_write_mymeta_data or return 1; # Save as the MYMETA.yml file print "Writing MYMETA.json\n"; Module::Install::_write( 'MYMETA.json', JSON->new->pretty(1)->canonical->encode($meta), ); } sub _write_mymeta_data { my $self = shift; # If there's no existing META.yml there is nothing we can do return undef unless -f 'META.yml'; # We need Parse::CPAN::Meta to load the file unless ( eval { require Parse::CPAN::Meta; 1; } ) { return undef; } # Merge the perl version into the dependencies my $val = $self->Meta->{values}; my $perl = delete $val->{perl_version}; if ( $perl ) { $val->{requires} ||= []; my $requires = $val->{requires}; # Canonize to three-dot version after Perl 5.6 if ( $perl >= 5.006 ) { $perl =~ s{^(\d+)\.(\d\d\d)(\d*)}{join('.', $1, int($2||0), int($3||0))}e } unshift @$requires, [ perl => $perl ]; } # Load the advisory META.yml file my @yaml = Parse::CPAN::Meta::LoadFile('META.yml'); my $meta = $yaml[0]; # Overwrite the non-configure dependency hashs delete $meta->{requires}; delete $meta->{build_requires}; delete $meta->{recommends}; if ( exists $val->{requires} ) { $meta->{requires} = { map { @$_ } @{ $val->{requires} } }; } if ( exists $val->{build_requires} ) { $meta->{build_requires} = { map { @$_ } @{ $val->{build_requires} } }; } return $meta; } 1; mha4mysql-node-0.54/inc/Module/Install/Include.pm0000644000000000000000000000101512056326652020333 0ustar rootroot#line 1 package Module::Install::Include; use strict; use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91'; @ISA = 'Module::Install::Base'; $ISCORE = 1; } sub include { shift()->admin->include(@_); } sub include_deps { shift()->admin->include_deps(@_); } sub auto_include { shift()->admin->auto_include(@_); } sub auto_include_deps { shift()->admin->auto_include_deps(@_); } sub auto_include_dependent_dists { shift()->admin->auto_include_dependent_dists(@_); } 1; mha4mysql-node-0.54/inc/Module/Install/AutoInstall.pm0000644000000000000000000000227312056326652021216 0ustar rootroot#line 1 package Module::Install::AutoInstall; use strict; use Module::Install::Base (); use vars qw{$VERSION @ISA $ISCORE}; BEGIN { $VERSION = '0.91'; @ISA = 'Module::Install::Base'; $ISCORE = 1; } sub AutoInstall { $_[0] } sub run { my $self = shift; $self->auto_install_now(@_); } sub write { my $self = shift; $self->auto_install(@_); } sub auto_install { my $self = shift; return if $self->{done}++; # Flatten array of arrays into a single array my @core = map @$_, map @$_, grep ref, $self->build_requires, $self->requires; my @config = @_; # We'll need Module::AutoInstall $self->include('Module::AutoInstall'); require Module::AutoInstall; Module::AutoInstall->import( (@config ? (-config => \@config) : ()), (@core ? (-core => \@core) : ()), $self->features, ); $self->makemaker_args( Module::AutoInstall::_make_args() ); my $class = ref($self); $self->postamble( "# --- $class section:\n" . Module::AutoInstall::postamble() ); } sub auto_install_now { my $self = shift; $self->auto_install(@_); Module::AutoInstall::do_install(); } 1; mha4mysql-node-0.54/inc/Module/Install.pm0000644000000000000000000002411412056326651016754 0ustar rootroot#line 1 package Module::Install; # For any maintainers: # The load order for Module::Install is a bit magic. # It goes something like this... # # IF ( host has Module::Install installed, creating author mode ) { # 1. Makefile.PL calls "use inc::Module::Install" # 2. $INC{inc/Module/Install.pm} set to installed version of inc::Module::Install # 3. The installed version of inc::Module::Install loads # 4. inc::Module::Install calls "require Module::Install" # 5. The ./inc/ version of Module::Install loads # } ELSE { # 1. Makefile.PL calls "use inc::Module::Install" # 2. $INC{inc/Module/Install.pm} set to ./inc/ version of Module::Install # 3. The ./inc/ version of Module::Install loads # } use 5.005; use strict 'vars'; use vars qw{$VERSION $MAIN}; BEGIN { # All Module::Install core packages now require synchronised versions. # This will be used to ensure we don't accidentally load old or # different versions of modules. # This is not enforced yet, but will be some time in the next few # releases once we can make sure it won't clash with custom # Module::Install extensions. $VERSION = '0.91'; # Storage for the pseudo-singleton $MAIN = undef; *inc::Module::Install::VERSION = *VERSION; @inc::Module::Install::ISA = __PACKAGE__; } # Whether or not inc::Module::Install is actually loaded, the # $INC{inc/Module/Install.pm} is what will still get set as long as # the caller loaded module this in the documented manner. # If not set, the caller may NOT have loaded the bundled version, and thus # they may not have a MI version that works with the Makefile.PL. This would # result in false errors or unexpected behaviour. And we don't want that. my $file = join( '/', 'inc', split /::/, __PACKAGE__ ) . '.pm'; unless ( $INC{$file} ) { die <<"END_DIE" } Please invoke ${\__PACKAGE__} with: use inc::${\__PACKAGE__}; not: use ${\__PACKAGE__}; END_DIE # If the script that is loading Module::Install is from the future, # then make will detect this and cause it to re-run over and over # again. This is bad. Rather than taking action to touch it (which # is unreliable on some platforms and requires write permissions) # for now we should catch this and refuse to run. if ( -f $0 ) { my $s = (stat($0))[9]; # If the modification time is only slightly in the future, # sleep briefly to remove the problem. my $a = $s - time; if ( $a > 0 and $a < 5 ) { sleep 5 } # Too far in the future, throw an error. my $t = time; if ( $s > $t ) { die <<"END_DIE" } Your installer $0 has a modification time in the future ($s > $t). This is known to create infinite loops in make. Please correct this, then run $0 again. END_DIE } # Build.PL was formerly supported, but no longer is due to excessive # difficulty in implementing every single feature twice. if ( $0 =~ /Build.PL$/i ) { die <<"END_DIE" } Module::Install no longer supports Build.PL. It was impossible to maintain duel backends, and has been deprecated. Please remove all Build.PL files and only use the Makefile.PL installer. END_DIE # To save some more typing in Module::Install installers, every... # use inc::Module::Install # ...also acts as an implicit use strict. $^H |= strict::bits(qw(refs subs vars)); use Cwd (); use File::Find (); use File::Path (); use FindBin; sub autoload { my $self = shift; my $who = $self->_caller; my $cwd = Cwd::cwd(); my $sym = "${who}::AUTOLOAD"; $sym->{$cwd} = sub { my $pwd = Cwd::cwd(); if ( my $code = $sym->{$pwd} ) { # Delegate back to parent dirs goto &$code unless $cwd eq $pwd; } $$sym =~ /([^:]+)$/ or die "Cannot autoload $who - $sym"; my $method = $1; if ( uc($method) eq $method ) { # Do nothing return; } elsif ( $method =~ /^_/ and $self->can($method) ) { # Dispatch to the root M:I class return $self->$method(@_); } # Dispatch to the appropriate plugin unshift @_, ( $self, $1 ); goto &{$self->can('call')}; }; } sub import { my $class = shift; my $self = $class->new(@_); my $who = $self->_caller; unless ( -f $self->{file} ) { require "$self->{path}/$self->{dispatch}.pm"; File::Path::mkpath("$self->{prefix}/$self->{author}"); $self->{admin} = "$self->{name}::$self->{dispatch}"->new( _top => $self ); $self->{admin}->init; @_ = ($class, _self => $self); goto &{"$self->{name}::import"}; } *{"${who}::AUTOLOAD"} = $self->autoload; $self->preload; # Unregister loader and worker packages so subdirs can use them again delete $INC{"$self->{file}"}; delete $INC{"$self->{path}.pm"}; # Save to the singleton $MAIN = $self; return 1; } sub preload { my $self = shift; unless ( $self->{extensions} ) { $self->load_extensions( "$self->{prefix}/$self->{path}", $self ); } my @exts = @{$self->{extensions}}; unless ( @exts ) { @exts = $self->{admin}->load_all_extensions; } my %seen; foreach my $obj ( @exts ) { while (my ($method, $glob) = each %{ref($obj) . '::'}) { next unless $obj->can($method); next if $method =~ /^_/; next if $method eq uc($method); $seen{$method}++; } } my $who = $self->_caller; foreach my $name ( sort keys %seen ) { *{"${who}::$name"} = sub { ${"${who}::AUTOLOAD"} = "${who}::$name"; goto &{"${who}::AUTOLOAD"}; }; } } sub new { my ($class, %args) = @_; # ignore the prefix on extension modules built from top level. my $base_path = Cwd::abs_path($FindBin::Bin); unless ( Cwd::abs_path(Cwd::cwd()) eq $base_path ) { delete $args{prefix}; } return $args{_self} if $args{_self}; $args{dispatch} ||= 'Admin'; $args{prefix} ||= 'inc'; $args{author} ||= ($^O eq 'VMS' ? '_author' : '.author'); $args{bundle} ||= 'inc/BUNDLES'; $args{base} ||= $base_path; $class =~ s/^\Q$args{prefix}\E:://; $args{name} ||= $class; $args{version} ||= $class->VERSION; unless ( $args{path} ) { $args{path} = $args{name}; $args{path} =~ s!::!/!g; } $args{file} ||= "$args{base}/$args{prefix}/$args{path}.pm"; $args{wrote} = 0; bless( \%args, $class ); } sub call { my ($self, $method) = @_; my $obj = $self->load($method) or return; splice(@_, 0, 2, $obj); goto &{$obj->can($method)}; } sub load { my ($self, $method) = @_; $self->load_extensions( "$self->{prefix}/$self->{path}", $self ) unless $self->{extensions}; foreach my $obj (@{$self->{extensions}}) { return $obj if $obj->can($method); } my $admin = $self->{admin} or die <<"END_DIE"; The '$method' method does not exist in the '$self->{prefix}' path! Please remove the '$self->{prefix}' directory and run $0 again to load it. END_DIE my $obj = $admin->load($method, 1); push @{$self->{extensions}}, $obj; $obj; } sub load_extensions { my ($self, $path, $top) = @_; unless ( grep { ! ref $_ and lc $_ eq lc $self->{prefix} } @INC ) { unshift @INC, $self->{prefix}; } foreach my $rv ( $self->find_extensions($path) ) { my ($file, $pkg) = @{$rv}; next if $self->{pathnames}{$pkg}; local $@; my $new = eval { require $file; $pkg->can('new') }; unless ( $new ) { warn $@ if $@; next; } $self->{pathnames}{$pkg} = delete $INC{$file}; push @{$self->{extensions}}, &{$new}($pkg, _top => $top ); } $self->{extensions} ||= []; } sub find_extensions { my ($self, $path) = @_; my @found; File::Find::find( sub { my $file = $File::Find::name; return unless $file =~ m!^\Q$path\E/(.+)\.pm\Z!is; my $subpath = $1; return if lc($subpath) eq lc($self->{dispatch}); $file = "$self->{path}/$subpath.pm"; my $pkg = "$self->{name}::$subpath"; $pkg =~ s!/!::!g; # If we have a mixed-case package name, assume case has been preserved # correctly. Otherwise, root through the file to locate the case-preserved # version of the package name. if ( $subpath eq lc($subpath) || $subpath eq uc($subpath) ) { my $content = Module::Install::_read($subpath . '.pm'); my $in_pod = 0; foreach ( split //, $content ) { $in_pod = 1 if /^=\w/; $in_pod = 0 if /^=cut/; next if ($in_pod || /^=cut/); # skip pod text next if /^\s*#/; # and comments if ( m/^\s*package\s+($pkg)\s*;/i ) { $pkg = $1; last; } } } push @found, [ $file, $pkg ]; }, $path ) if -d $path; @found; } ##################################################################### # Common Utility Functions sub _caller { my $depth = 0; my $call = caller($depth); while ( $call eq __PACKAGE__ ) { $depth++; $call = caller($depth); } return $call; } sub _read { local *FH; if ( $] >= 5.006 ) { open( FH, '<', $_[0] ) or die "open($_[0]): $!"; } else { open( FH, "< $_[0]" ) or die "open($_[0]): $!"; } my $string = do { local $/; }; close FH or die "close($_[0]): $!"; return $string; } sub _readperl { my $string = Module::Install::_read($_[0]); $string =~ s/(?:\015{1,2}\012|\015|\012)/\n/sg; $string =~ s/(\n)\n*__(?:DATA|END)__\b.*\z/$1/s; $string =~ s/\n\n=\w+.+?\n\n=cut\b.+?\n+/\n\n/sg; return $string; } sub _readpod { my $string = Module::Install::_read($_[0]); $string =~ s/(?:\015{1,2}\012|\015|\012)/\n/sg; return $string if $_[0] =~ /\.pod\z/; $string =~ s/(^|\n=cut\b.+?\n+)[^=\s].+?\n(\n=\w+|\z)/$1$2/sg; $string =~ s/\n*=pod\b[^\n]*\n+/\n\n/sg; $string =~ s/\n*=cut\b[^\n]*\n+/\n\n/sg; $string =~ s/^\n+//s; return $string; } sub _write { local *FH; if ( $] >= 5.006 ) { open( FH, '>', $_[0] ) or die "open($_[0]): $!"; } else { open( FH, "> $_[0]" ) or die "open($_[0]): $!"; } foreach ( 1 .. $#_ ) { print FH $_[$_] or die "print($_[0]): $!"; } close FH or die "close($_[0]): $!"; } # _version is for processing module versions (eg, 1.03_05) not # Perl versions (eg, 5.8.1). sub _version ($) { my $s = shift || 0; my $d =()= $s =~ /(\.)/g; if ( $d >= 2 ) { # Normalise multipart versions $s =~ s/(\.)(\d{1,3})/sprintf("$1%03d",$2)/eg; } $s =~ s/^(\d+)\.?//; my $l = $1 || 0; my @v = map { $_ . '0' x (3 - length $_) } $s =~ /(\d{1,3})\D?/g; $l = $l . '.' . join '', @v if @v; return $l + 0; } sub _cmp ($$) { _version($_[0]) <=> _version($_[1]); } # Cloned from Params::Util::_CLASS sub _CLASS ($) { ( defined $_[0] and ! ref $_[0] and $_[0] =~ m/^[^\W\d]\w*(?:::\w+)*\z/s ) ? $_[0] : undef; } 1; # Copyright 2008 - 2009 Adam Kennedy. mha4mysql-node-0.54/inc/Module/AutoInstall.pm0000644000000000000000000005330612056326652017613 0ustar rootroot#line 1 package Module::AutoInstall; use strict; use Cwd (); use ExtUtils::MakeMaker (); use vars qw{$VERSION}; BEGIN { $VERSION = '1.03'; } # special map on pre-defined feature sets my %FeatureMap = ( '' => 'Core Features', # XXX: deprecated '-core' => 'Core Features', ); # various lexical flags my ( @Missing, @Existing, %DisabledTests, $UnderCPAN, $HasCPANPLUS ); my ( $Config, $CheckOnly, $SkipInstall, $AcceptDefault, $TestOnly, $AllDeps ); my ( $PostambleActions, $PostambleUsed ); # See if it's a testing or non-interactive session _accept_default( $ENV{AUTOMATED_TESTING} or ! -t STDIN ); _init(); sub _accept_default { $AcceptDefault = shift; } sub missing_modules { return @Missing; } sub do_install { __PACKAGE__->install( [ $Config ? ( UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) : () ], @Missing, ); } # initialize various flags, and/or perform install sub _init { foreach my $arg ( @ARGV, split( /[\s\t]+/, $ENV{PERL_AUTOINSTALL} || $ENV{PERL_EXTUTILS_AUTOINSTALL} || '' ) ) { if ( $arg =~ /^--config=(.*)$/ ) { $Config = [ split( ',', $1 ) ]; } elsif ( $arg =~ /^--installdeps=(.*)$/ ) { __PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) ); exit 0; } elsif ( $arg =~ /^--default(?:deps)?$/ ) { $AcceptDefault = 1; } elsif ( $arg =~ /^--check(?:deps)?$/ ) { $CheckOnly = 1; } elsif ( $arg =~ /^--skip(?:deps)?$/ ) { $SkipInstall = 1; } elsif ( $arg =~ /^--test(?:only)?$/ ) { $TestOnly = 1; } elsif ( $arg =~ /^--all(?:deps)?$/ ) { $AllDeps = 1; } } } # overrides MakeMaker's prompt() to automatically accept the default choice sub _prompt { goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault; my ( $prompt, $default ) = @_; my $y = ( $default =~ /^[Yy]/ ); print $prompt, ' [', ( $y ? 'Y' : 'y' ), '/', ( $y ? 'n' : 'N' ), '] '; print "$default\n"; return $default; } # the workhorse sub import { my $class = shift; my @args = @_ or return; my $core_all; print "*** $class version " . $class->VERSION . "\n"; print "*** Checking for Perl dependencies...\n"; my $cwd = Cwd::cwd(); $Config = []; my $maxlen = length( ( sort { length($b) <=> length($a) } grep { /^[^\-]/ } map { ref($_) ? ( ( ref($_) eq 'HASH' ) ? keys(%$_) : @{$_} ) : '' } map { +{@args}->{$_} } grep { /^[^\-]/ or /^-core$/i } keys %{ +{@args} } )[0] ); # We want to know if we're under CPAN early to avoid prompting, but # if we aren't going to try and install anything anyway then skip the # check entirely since we don't want to have to load (and configure) # an old CPAN just for a cosmetic message $UnderCPAN = _check_lock(1) unless $SkipInstall; while ( my ( $feature, $modules ) = splice( @args, 0, 2 ) ) { my ( @required, @tests, @skiptests ); my $default = 1; my $conflict = 0; if ( $feature =~ m/^-(\w+)$/ ) { my $option = lc($1); # check for a newer version of myself _update_to( $modules, @_ ) and return if $option eq 'version'; # sets CPAN configuration options $Config = $modules if $option eq 'config'; # promote every features to core status $core_all = ( $modules =~ /^all$/i ) and next if $option eq 'core'; next unless $option eq 'core'; } print "[" . ( $FeatureMap{ lc($feature) } || $feature ) . "]\n"; $modules = [ %{$modules} ] if UNIVERSAL::isa( $modules, 'HASH' ); unshift @$modules, -default => &{ shift(@$modules) } if ( ref( $modules->[0] ) eq 'CODE' ); # XXX: bugward combatability while ( my ( $mod, $arg ) = splice( @$modules, 0, 2 ) ) { if ( $mod =~ m/^-(\w+)$/ ) { my $option = lc($1); $default = $arg if ( $option eq 'default' ); $conflict = $arg if ( $option eq 'conflict' ); @tests = @{$arg} if ( $option eq 'tests' ); @skiptests = @{$arg} if ( $option eq 'skiptests' ); next; } printf( "- %-${maxlen}s ...", $mod ); if ( $arg and $arg =~ /^\D/ ) { unshift @$modules, $arg; $arg = 0; } # XXX: check for conflicts and uninstalls(!) them. my $cur = _load($mod); if (_version_cmp ($cur, $arg) >= 0) { print "loaded. ($cur" . ( $arg ? " >= $arg" : '' ) . ")\n"; push @Existing, $mod => $arg; $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; } else { if (not defined $cur) # indeed missing { print "missing." . ( $arg ? " (would need $arg)" : '' ) . "\n"; } else { # no need to check $arg as _version_cmp ($cur, undef) would satisfy >= above print "too old. ($cur < $arg)\n"; } push @required, $mod => $arg; } } next unless @required; my $mandatory = ( $feature eq '-core' or $core_all ); if ( !$SkipInstall and ( $CheckOnly or ($mandatory and $UnderCPAN) or $AllDeps or _prompt( qq{==> Auto-install the } . ( @required / 2 ) . ( $mandatory ? ' mandatory' : ' optional' ) . qq{ module(s) from CPAN?}, $default ? 'y' : 'n', ) =~ /^[Yy]/ ) ) { push( @Missing, @required ); $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; } elsif ( !$SkipInstall and $default and $mandatory and _prompt( qq{==> The module(s) are mandatory! Really skip?}, 'n', ) =~ /^[Nn]/ ) { push( @Missing, @required ); $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; } else { $DisabledTests{$_} = 1 for map { glob($_) } @tests; } } if ( @Missing and not( $CheckOnly or $UnderCPAN ) ) { require Config; print "*** Dependencies will be installed the next time you type '$Config::Config{make}'.\n"; # make an educated guess of whether we'll need root permission. print " (You may need to do that as the 'root' user.)\n" if eval '$>'; } print "*** $class configuration finished.\n"; chdir $cwd; # import to main:: no strict 'refs'; *{'main::WriteMakefile'} = \&Write if caller(0) eq 'main'; } sub _running_under { my $thing = shift; print <<"END_MESSAGE"; *** Since we're running under ${thing}, I'll just let it take care of the dependency's installation later. END_MESSAGE return 1; } # Check to see if we are currently running under CPAN.pm and/or CPANPLUS; # if we are, then we simply let it taking care of our dependencies sub _check_lock { return unless @Missing or @_; my $cpan_env = $ENV{PERL5_CPAN_IS_RUNNING}; if ($ENV{PERL5_CPANPLUS_IS_RUNNING}) { return _running_under($cpan_env ? 'CPAN' : 'CPANPLUS'); } require CPAN; if ($CPAN::VERSION > '1.89') { if ($cpan_env) { return _running_under('CPAN'); } return; # CPAN.pm new enough, don't need to check further } # last ditch attempt, this -will- configure CPAN, very sorry _load_cpan(1); # force initialize even though it's already loaded # Find the CPAN lock-file my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" ); return unless -f $lock; # Check the lock local *LOCK; return unless open(LOCK, $lock); if ( ( $^O eq 'MSWin32' ? _under_cpan() : == getppid() ) and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore' ) { print <<'END_MESSAGE'; *** Since we're running under CPAN, I'll just let it take care of the dependency's installation later. END_MESSAGE return 1; } close LOCK; return; } sub install { my $class = shift; my $i; # used below to strip leading '-' from config keys my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } ); my ( @modules, @installed ); while ( my ( $pkg, $ver ) = splice( @_, 0, 2 ) ) { # grep out those already installed if ( _version_cmp( _load($pkg), $ver ) >= 0 ) { push @installed, $pkg; } else { push @modules, $pkg, $ver; } } return @installed unless @modules; # nothing to do return @installed if _check_lock(); # defer to the CPAN shell print "*** Installing dependencies...\n"; return unless _connected_to('cpan.org'); my %args = @config; my %failed; local *FAILED; if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) { while () { chomp; $failed{$_}++ } close FAILED; my @newmod; while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) { push @newmod, ( $k => $v ) unless $failed{$k}; } @modules = @newmod; } if ( _has_cpanplus() and not $ENV{PERL_AUTOINSTALL_PREFER_CPAN} ) { _install_cpanplus( \@modules, \@config ); } else { _install_cpan( \@modules, \@config ); } print "*** $class installation finished.\n"; # see if we have successfully installed them while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { if ( _version_cmp( _load($pkg), $ver ) >= 0 ) { push @installed, $pkg; } elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) { print FAILED "$pkg\n"; } } close FAILED if $args{do_once}; return @installed; } sub _install_cpanplus { my @modules = @{ +shift }; my @config = _cpanplus_config( @{ +shift } ); my $installed = 0; require CPANPLUS::Backend; my $cp = CPANPLUS::Backend->new; my $conf = $cp->configure_object; return unless $conf->can('conf') # 0.05x+ with "sudo" support or _can_write($conf->_get_build('base')); # 0.04x # if we're root, set UNINST=1 to avoid trouble unless user asked for it. my $makeflags = $conf->get_conf('makeflags') || ''; if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) { # 0.03+ uses a hashref here $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST}; } else { # 0.02 and below uses a scalar $makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' ) if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } ); } $conf->set_conf( makeflags => $makeflags ); $conf->set_conf( prereqs => 1 ); while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) { $conf->set_conf( $key, $val ); } my $modtree = $cp->module_tree; while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { print "*** Installing $pkg...\n"; MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall; my $success; my $obj = $modtree->{$pkg}; if ( $obj and _version_cmp( $obj->{version}, $ver ) >= 0 ) { my $pathname = $pkg; $pathname =~ s/::/\\W/; foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) { delete $INC{$inc}; } my $rv = $cp->install( modules => [ $obj->{module} ] ); if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) { print "*** $pkg successfully installed.\n"; $success = 1; } else { print "*** $pkg installation cancelled.\n"; $success = 0; } $installed += $success; } else { print << "."; *** Could not find a version $ver or above for $pkg; skipping. . } MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall; } return $installed; } sub _cpanplus_config { my @config = (); while ( @_ ) { my ($key, $value) = (shift(), shift()); if ( $key eq 'prerequisites_policy' ) { if ( $value eq 'follow' ) { $value = CPANPLUS::Internals::Constants::PREREQ_INSTALL(); } elsif ( $value eq 'ask' ) { $value = CPANPLUS::Internals::Constants::PREREQ_ASK(); } elsif ( $value eq 'ignore' ) { $value = CPANPLUS::Internals::Constants::PREREQ_IGNORE(); } else { die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n"; } } else { die "*** Cannot convert option $key to CPANPLUS version.\n"; } } return @config; } sub _install_cpan { my @modules = @{ +shift }; my @config = @{ +shift }; my $installed = 0; my %args; _load_cpan(); require Config; if (CPAN->VERSION < 1.80) { # no "sudo" support, probe for writableness return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) ) and _can_write( $Config::Config{sitelib} ); } # if we're root, set UNINST=1 to avoid trouble unless user asked for it. my $makeflags = $CPAN::Config->{make_install_arg} || ''; $CPAN::Config->{make_install_arg} = join( ' ', split( ' ', $makeflags ), 'UNINST=1' ) if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } ); # don't show start-up info $CPAN::Config->{inhibit_startup_message} = 1; # set additional options while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) { ( $args{$opt} = $arg, next ) if $opt =~ /^force$/; # pseudo-option $CPAN::Config->{$opt} = $arg; } local $CPAN::Config->{prerequisites_policy} = 'follow'; while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall; print "*** Installing $pkg...\n"; my $obj = CPAN::Shell->expand( Module => $pkg ); my $success = 0; if ( $obj and _version_cmp( $obj->cpan_version, $ver ) >= 0 ) { my $pathname = $pkg; $pathname =~ s/::/\\W/; foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) { delete $INC{$inc}; } my $rv = $args{force} ? CPAN::Shell->force( install => $pkg ) : CPAN::Shell->install($pkg); $rv ||= eval { $CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, ) ->{install} if $CPAN::META; }; if ( $rv eq 'YES' ) { print "*** $pkg successfully installed.\n"; $success = 1; } else { print "*** $pkg installation failed.\n"; $success = 0; } $installed += $success; } else { print << "."; *** Could not find a version $ver or above for $pkg; skipping. . } MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall; } return $installed; } sub _has_cpanplus { return ( $HasCPANPLUS = ( $INC{'CPANPLUS/Config.pm'} or _load('CPANPLUS::Shell::Default') ) ); } # make guesses on whether we're under the CPAN installation directory sub _under_cpan { require Cwd; require File::Spec; my $cwd = File::Spec->canonpath( Cwd::cwd() ); my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} ); return ( index( $cwd, $cpan ) > -1 ); } sub _update_to { my $class = __PACKAGE__; my $ver = shift; return if _version_cmp( _load($class), $ver ) >= 0; # no need to upgrade if ( _prompt( "==> A newer version of $class ($ver) is required. Install?", 'y' ) =~ /^[Nn]/ ) { die "*** Please install $class $ver manually.\n"; } print << "."; *** Trying to fetch it from CPAN... . # install ourselves _load($class) and return $class->import(@_) if $class->install( [], $class, $ver ); print << '.'; exit 1; *** Cannot bootstrap myself. :-( Installation terminated. . } # check if we're connected to some host, using inet_aton sub _connected_to { my $site = shift; return ( ( _load('Socket') and Socket::inet_aton($site) ) or _prompt( qq( *** Your host cannot resolve the domain name '$site', which probably means the Internet connections are unavailable. ==> Should we try to install the required module(s) anyway?), 'n' ) =~ /^[Yy]/ ); } # check if a directory is writable; may create it on demand sub _can_write { my $path = shift; mkdir( $path, 0755 ) unless -e $path; return 1 if -w $path; print << "."; *** You are not allowed to write to the directory '$path'; the installation may fail due to insufficient permissions. . if ( eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt( qq( ==> Should we try to re-execute the autoinstall process with 'sudo'?), ((-t STDIN) ? 'y' : 'n') ) =~ /^[Yy]/ ) { # try to bootstrap ourselves from sudo print << "."; *** Trying to re-execute the autoinstall process with 'sudo'... . my $missing = join( ',', @Missing ); my $config = join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) if $Config; return unless system( 'sudo', $^X, $0, "--config=$config", "--installdeps=$missing" ); print << "."; *** The 'sudo' command exited with error! Resuming... . } return _prompt( qq( ==> Should we try to install the required module(s) anyway?), 'n' ) =~ /^[Yy]/; } # load a module and return the version it reports sub _load { my $mod = pop; # class/instance doesn't matter my $file = $mod; $file =~ s|::|/|g; $file .= '.pm'; local $@; return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 ); } # Load CPAN.pm and it's configuration sub _load_cpan { return if $CPAN::VERSION and $CPAN::Config and not @_; require CPAN; if ( $CPAN::HandleConfig::VERSION ) { # Newer versions of CPAN have a HandleConfig module CPAN::HandleConfig->load; } else { # Older versions had the load method in Config directly CPAN::Config->load; } } # compare two versions, either use Sort::Versions or plain comparison # return values same as <=> sub _version_cmp { my ( $cur, $min ) = @_; return -1 unless defined $cur; # if 0 keep comparing return 1 unless $min; $cur =~ s/\s+$//; # check for version numbers that are not in decimal format if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) { if ( ( $version::VERSION or defined( _load('version') )) and version->can('new') ) { # use version.pm if it is installed. return version->new($cur) <=> version->new($min); } elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) ) { # use Sort::Versions as the sorting algorithm for a.b.c versions return Sort::Versions::versioncmp( $cur, $min ); } warn "Cannot reliably compare non-decimal formatted versions.\n" . "Please install version.pm or Sort::Versions.\n"; } # plain comparison local $^W = 0; # shuts off 'not numeric' bugs return $cur <=> $min; } # nothing; this usage is deprecated. sub main::PREREQ_PM { return {}; } sub _make_args { my %args = @_; $args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing } if $UnderCPAN or $TestOnly; if ( $args{EXE_FILES} and -e 'MANIFEST' ) { require ExtUtils::Manifest; my $manifest = ExtUtils::Manifest::maniread('MANIFEST'); $args{EXE_FILES} = [ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ]; } $args{test}{TESTS} ||= 't/*.t'; $args{test}{TESTS} = join( ' ', grep { !exists( $DisabledTests{$_} ) } map { glob($_) } split( /\s+/, $args{test}{TESTS} ) ); my $missing = join( ',', @Missing ); my $config = join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) if $Config; $PostambleActions = ( ($missing and not $UnderCPAN) ? "\$(PERL) $0 --config=$config --installdeps=$missing" : "\$(NOECHO) \$(NOOP)" ); return %args; } # a wrapper to ExtUtils::MakeMaker::WriteMakefile sub Write { require Carp; Carp::croak "WriteMakefile: Need even number of args" if @_ % 2; if ($CheckOnly) { print << "."; *** Makefile not written in check-only mode. . return; } my %args = _make_args(@_); no strict 'refs'; $PostambleUsed = 0; local *MY::postamble = \&postamble unless defined &MY::postamble; ExtUtils::MakeMaker::WriteMakefile(%args); print << "." unless $PostambleUsed; *** WARNING: Makefile written with customized MY::postamble() without including contents from Module::AutoInstall::postamble() -- auto installation features disabled. Please contact the author. . return 1; } sub postamble { $PostambleUsed = 1; return <<"END_MAKE"; config :: installdeps \t\$(NOECHO) \$(NOOP) checkdeps :: \t\$(PERL) $0 --checkdeps installdeps :: \t$PostambleActions END_MAKE } 1; __END__ #line 1056 mha4mysql-node-0.54/rpm/0000755000000000000000000000000012056326664013612 5ustar rootrootmha4mysql-node-0.54/rpm/masterha_node.spec0000644000000000000000000000362512056311242017267 0ustar rootrootSummary: Master High Availability Manager and Tools for MySQL, Node Package Name: mha4mysql-node Version: 0.54 Release: 0%{?dist} License: GPL v2 Vendor: DeNA Co.,Ltd. Group: Utilities URL: http://code.google.com/p/mysql-master-ha/ BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root BuildArch: noarch BuildRequires: perl(ExtUtils::MakeMaker) >= 6.30 Requires: perl(DBD::mysql) Requires: perl(DBI) Source0: mha4mysql-node-%{version}.tar.gz %description %{summary}. %prep %setup -q -n mha4mysql-node-%{version} %build CFLAGS="$RPM_OPT_FLAGS" %{__perl} Makefile.PL INSTALLDIRS="vendor" INSTALLVENDORLIB=%{?perl_install_vendor_lib} make %{?_smp_mflags} OPTIMIZE="$RPM_OPT_FLAGS" %install rm -rf $RPM_BUILD_ROOT make pure_install PERL_INSTALL_ROOT=$RPM_BUILD_ROOT find $RPM_BUILD_ROOT -type f -a \( -name perllocal.pod -o -name .packlist \ -o \( -name '*.bs' -a -empty \) \) -exec rm -f {} ';' find $RPM_BUILD_ROOT -type d -depth -exec rmdir {} 2>/dev/null ';' chmod -R u+w $RPM_BUILD_ROOT/* for brp in %{_prefix}/lib/rpm/%{_build_vendor}/brp-compress \ %{_prefix}/lib/rpm/brp-compress do [ -x $brp ] && $brp && break done find $RPM_BUILD_ROOT -type f \ | sed "s@^$RPM_BUILD_ROOT@@g" \ > %{name}-%{version}-%{release}-filelist if [ "$(cat %{name}-%{version}-%{release}-filelist)X" = "X" ] ; then echo "ERROR: EMPTY FILE LIST" exit 1 fi %clean rm -rf $RPM_BUILD_ROOT %files -f %{name}-%{version}-%{release}-filelist %defattr(-,root,root,-) %changelog * Sat Dec 1 2012 Yoshinori Matsunobu - (Note: All changelogs are written here: http://code.google.com/p/mysql-master-ha/wiki/ReleaseNotes ) - Version 0.54 * Mon Jan 9 2012 Yoshinori Matsunobu - Version 0.53 * Fri Sep 16 2011 Yoshinori Matsunobu - Version 0.52 (0.51 was skipped) * Sat Jul 23 2011 Yoshinori Matsunobu - Version 0.50 mha4mysql-node-0.54/Makefile.PL0000755000000000000000000000041011770663665014773 0ustar rootrootuse inc::Module::Install; name 'mha4mysql-node'; version_from 'lib/MHA/NodeConst.pm'; requires 'DBI'; requires 'DBD::mysql'; license 'GPL v2'; author 'Yoshinori Matsunobu '; install_script(glob 'bin/*'); auto_install; WriteAll; mha4mysql-node-0.54/MANIFEST0000644000000000000000000000155511770663665014162 0ustar rootrootAUTHORS bin/apply_diff_relay_logs bin/filter_mysqlbinlog bin/purge_relay_logs bin/save_binary_logs COPYING debian/changelog debian/compat debian/control debian/copyright debian/rules inc/Module/AutoInstall.pm inc/Module/Install.pm inc/Module/Install/AutoInstall.pm inc/Module/Install/Base.pm inc/Module/Install/Can.pm inc/Module/Install/Fetch.pm inc/Module/Install/Include.pm inc/Module/Install/Makefile.pm inc/Module/Install/Metadata.pm inc/Module/Install/Scripts.pm inc/Module/Install/Win32.pm inc/Module/Install/WriteAll.pm lib/MHA/BinlogHeaderParser.pm lib/MHA/BinlogManager.pm lib/MHA/BinlogPosFinder.pm lib/MHA/BinlogPosFinderElp.pm lib/MHA/BinlogPosFinderXid.pm lib/MHA/BinlogPosFindManager.pm lib/MHA/NodeConst.pm lib/MHA/NodeUtil.pm lib/MHA/SlaveUtil.pm Makefile.PL MANIFEST This list of files META.yml README rpm/masterha_node.spec t/99-perlcritic.t t/perlcriticrc mha4mysql-node-0.54/lib/0000755000000000000000000000000012056326663013561 5ustar rootrootmha4mysql-node-0.54/lib/MHA/0000755000000000000000000000000012056326664014167 5ustar rootrootmha4mysql-node-0.54/lib/MHA/NodeConst.pm0000644000000000000000000000243412056326637016424 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use strict; use warnings FATAL => 'all'; package MHA::NodeConst; our $VERSION = '0.54'; our $MGR_MIN_VERSION = '0.54'; our $SSH_OPT_ALIVE = "-o ServerAliveInterval=60 -o ServerAliveCountMax=20 -o StrictHostKeyChecking=no -o ConnectionAttempts=5 -o PasswordAuthentication=no -o BatchMode=yes"; # apply_diff_relay_logs status codes our $Target_Has_Received_All_Relay_Logs = 2; our $Relay_Log_Not_Found = 10; our $Relay_Pos_Not_Found = 12; our $Applying_SQL_File_Failed = 22; 1; mha4mysql-node-0.54/lib/MHA/BinlogManager.pm0000644000000000000000000004223312056326634017233 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package MHA::BinlogManager; use strict; use warnings FATAL => 'all'; use English qw(-no_match_vars); use Carp qw(croak); use MHA::BinlogHeaderParser; use MHA::NodeUtil; use File::Basename; use File::Copy; use File::Path; use Errno(); sub new { my $class = shift; my $self = { mysql_version => undef, handle_raw_binlog => undef, disable_log_bin => undef, relay_log_info => undef, mysqlbinlog_version => undef, dir => undef, prefix => undef, cur_log => undef, end_log => undef, end_num => undef, debug => undef, @_, }; return bless $self, $class; } sub get_apply_arg($) { my $self = shift; my $arg = ""; if ( should_suppress_row_format( $self->{mysqlbinlog_version}, $self->{mysql_version} ) ) { $arg .= " --base64-output=never"; } if ( $self->{disable_log_bin} ) { $arg .= " --disable-log-bin"; } return $arg; } sub parse_version($) { my $str = shift; my $result = sprintf( '%03d%03d', $str =~ m/(\d+)/g ); return $result; } sub mysqlbinlog_version_ge { my ( $my_version, $target_version ) = @_; my $result = parse_version($my_version) ge parse_version($target_version) ? 1 : 0; return $result; } sub die_if_too_old_version { my $mysqlbinlog_version = shift; if ( !mysqlbinlog_ge_50($mysqlbinlog_version) ) { croak "mysqlbinlog version is $mysqlbinlog_version. This is too old. MHA supports MySQL version 5.0 (mysqlbinlog version 3.2) or higher. Recommended mysqlbinlog version is 3.3+, which is included in MySQL 5.1 or higher.\n"; } } sub init_mysqlbinlog($) { my $self = shift; eval { unless ( $self->{mysql_version} ) { croak "mysql version not found.\n"; } my $v = `mysqlbinlog --version`; chomp($v); if ( $v =~ /Ver (\d+\.\d+)/ ) { $self->{mysqlbinlog_version} = $1; } croak "mysqlbinlog version not found!\n" unless ( $self->{mysqlbinlog_version} ); die_if_too_old_version( $self->{mysqlbinlog_version} ); if ( !mysqlbinlog_ge_51( $self->{mysqlbinlog_version} ) ) { print "mysqlbinlog version is $self->{mysqlbinlog_version} (included in MySQL Client 5.0 or lower). This is not recommended. Consider upgrading MySQL Client to 5.1 or higher.\n"; } if ( !mysqlbinlog_ge_51( $self->{mysqlbinlog_version} ) && $self->{mysql_version} && MHA::NodeUtil::mysql_version_ge( $self->{mysql_version}, "5.1.0" ) ) { croak sprintf( "mysqlbinlog is %s (included in MySQL Client 5.0 or lower), but MySQL server version is %s. mysqlbinlog can not parse row based events. Terminating script for safety reasons.\n", $self->{mysqlbinlog_version}, $self->{mysql_version} ); } }; if ($@) { my $e = $@; undef $@; die $e; } return; } sub open_test($) { my $file = shift; my $fh; open( $fh, "<", $file ) or croak "$!:$file\n"; close($fh); } sub init_from_dir_file($$$) { my $self = shift; $self->{dir} = shift; my $current_binlog = shift; $self->{end_log} = get_end_binlog( $current_binlog, $self->{dir} ); croak "Failed to get tail of the relay/bin log name!\n" unless ( $self->{end_log} ); open_test("$self->{dir}/$self->{end_log}"); ( $self->{prefix}, $self->{end_num} ) = get_head_and_number( $self->{end_log} ); croak "Failed to get relay/bin log prefix!\n" unless ( $self->{prefix} ); croak "Failed to get relay/bin log number!\n" if ( !defined $self->{end_num} ); } sub init_from_relay_log_info($$$) { my $self = shift; $self->{relay_log_info} = shift; my $datadir = shift; ( $self->{dir}, $self->{end_log}, $self->{cur_log} ) = get_relaydir_and_files_from_rinfo( $self->{relay_log_info}, $datadir ); croak "Failed to get relay log directory!\n" unless ( $self->{dir} ); croak "Failed to get relay log end file!\n" unless ( $self->{end_log} ); open_test("$self->{dir}/$self->{end_log}"); ( $self->{prefix}, $self->{end_num} ) = get_head_and_number( $self->{end_log} ); croak "Failed to get relay log prefix!\n" unless ( $self->{prefix} ); croak "Failed to get relay log number!\n" if ( !defined $self->{end_num} ); } sub mysqlbinlog_ge { my $mysqlbinlog_version = shift; my $criteria = shift; if ( mysqlbinlog_version_ge( $mysqlbinlog_version, $criteria ) ) { return 1; } else { return 0; } } sub mysqlbinlog_ge_51 { my $mysqlbinlog_version = shift; return mysqlbinlog_ge( $mysqlbinlog_version, "3.3" ); } sub mysqlbinlog_ge_50 { my $mysqlbinlog_version = shift; return mysqlbinlog_ge( $mysqlbinlog_version, "3.2" ); } # Return: "/var/lib/mysql" "mysqld-relay-bin.000040" sub get_relaydir_and_filename_from_rinfo($$) { my $relay_log_info_path = shift; my $datadir = shift; my $fh; if ( !open( $fh, "<", $relay_log_info_path ) ) { croak "Could not open relay-log-info file $relay_log_info_path.\n"; } my $current_relay_log_file = readline($fh); chomp($current_relay_log_file); # for 5.6 relay-log.info if ( $current_relay_log_file =~ /^[0-9]+$/ ) { $current_relay_log_file = readline($fh); chomp($current_relay_log_file); } my $relay_dir = dirname($current_relay_log_file); # for compatibility unless ($datadir) { $datadir = dirname($relay_log_info_path); } if ( !$current_relay_log_file || !$relay_dir ) { croak "Coundln't get current relay log name.\n"; } unless ( $current_relay_log_file =~ m/^\// ) { $current_relay_log_file =~ s/^\.\///; $datadir =~ s/\/$//; $current_relay_log_file = $datadir . "/" . $current_relay_log_file; $relay_dir = $datadir; } my $relay_log_basename = basename($current_relay_log_file); return $relay_dir, $relay_log_basename; } sub get_head_and_number($) { my $binlog_filename = shift; my $log_number = $binlog_filename; $log_number =~ m/(.*)\.([0-9]+)/; my $binlog_head = $1; $log_number = $2; return $binlog_head, $log_number; } sub find_correct_binlog_dir($$) { my $binlog_file = shift; my $binlog_dirs = shift; my @binlog_dir_array = split( /,/, $binlog_dirs ); foreach (@binlog_dir_array) { return $_ if ( -f "$_/$binlog_file" ); } } sub find_correct_binlog_dir_file_from_prefix($$) { my $binlog_prefix = shift; my $binlog_dirs = shift; my @binlog_dir_array = split( /,/, $binlog_dirs ); foreach (@binlog_dir_array) { my @files = get_all_binlogs_from_prefix( $binlog_prefix, $_ ); return ( $_, $files[0] ) if ( $#files >= 0 ); } } sub get_all_binlogs_from_prefix($$) { my $binlog_prefix = shift; my $binlog_dir = shift; opendir my $dir, "$binlog_dir"; my @files = grep { m/^$binlog_prefix\.[0-9]+/ } readdir $dir; @files = sort @files; closedir $dir; return @files; } sub get_end_binlog_from_prefix($$) { my $binlog_prefix = shift; my $binlog_dir = shift; my @files = get_all_binlogs_from_prefix( $binlog_prefix, $binlog_dir ); if ( $#files < 0 ) { #No binlog file found! return; } return $files[$#files]; } sub get_end_binlog($$) { my $binlog_filename = shift; my $binlog_dir = shift; my ( $prefix, $num ) = get_head_and_number($binlog_filename); return get_end_binlog_from_prefix( $prefix, $binlog_dir ); } sub get_binlog_start_end($$) { my $start_binlog_file = shift; my $binlog_dir = shift; my ( $binlog_prefix, $start_num ) = get_head_and_number($start_binlog_file); my $end_binlog_file = get_end_binlog_from_prefix( $binlog_prefix, $binlog_dir ); croak "Binlog not found from $binlog_dir!\n" unless ($end_binlog_file); my ( $tmp, $end_num ) = get_head_and_number($end_binlog_file); return ( $binlog_prefix, $start_num, $end_num ); } sub get_prev_number($) { my $log_number = shift; $log_number--; return sprintf( "%06d", $log_number ); } sub get_prev_file($) { my $log_file = shift; $log_file =~ m/(.*)\.([0-9]+)/; $log_file = $1 . "." . sprintf( "%06d", ( $2 - 1 ) ); return $log_file; } sub get_prev_number_from_file($) { my $log_file = shift; my ( $ignore, $number ) = get_head_and_number($log_file); return get_prev_number($number); } sub get_post_number($) { my $log_number = shift; $log_number++; return sprintf( "%06d", $log_number ); } sub get_post_file($) { my $log_file = shift; $log_file =~ m/(.*)\.([0-9]+)/; $log_file = $1 . "." . sprintf( "%06d", ( $2 + 1 ) ); return $log_file; } sub should_suppress_row_format { my $mysqlbinlog_version = shift; my $mysql_version = shift; my $suppress_row_format = 0; if ( mysqlbinlog_ge_51($mysqlbinlog_version) && !MHA::NodeUtil::mysql_version_ge( $mysql_version, "5.1.0" ) ) { print "mysqlbinlog is 5.1 or higher, and MySQL version on the target server is 5.0 or lower. So using mysqlbinlog --base64-output=never to disable BINLOG events..\n"; $suppress_row_format = 1; } return $suppress_row_format; } # dir, read_file, exec_file sub get_relaydir_and_files_from_rinfo { my $rinfo = shift; my $datadir = shift; my ( $relay_dir, $exec_relay_file ) = get_relaydir_and_filename_from_rinfo( $rinfo, $datadir ); my $end_relay_file = get_end_binlog( $exec_relay_file, $relay_dir ); return ( $relay_dir, $end_relay_file, $exec_relay_file ); } sub is_binlog_head_readable($) { my $file = shift; # higher than binlog file header (4 bytes) return system("mysqlbinlog --stop-position=5 $file > /dev/null"); } sub get_end_binlog_fde($$$) { my $self = shift; my $dir = shift; my $file = shift; my $p = new MHA::BinlogHeaderParser( dir => $dir, file => $file, debug => $self->{debug} ); $p->open_binlog(); return $p->parse_init_headers(); } sub dump_init_binlog_without_fde($$$$) { my $self = shift; my $dir = shift; my $file = shift; my $outfile = shift; my $p = new MHA::BinlogHeaderParser( dir => $dir, file => $file, debug => $self->{debug} ); $p->open_binlog(); print " Dumping binlog head events (rotate events), skipping format description events from $dir/$file.. "; my $start_effective_pos = $p->parse_init_headers( 1, $outfile ); print "dumped up to pos $start_effective_pos. ok.\n"; return $start_effective_pos; } sub dump_binlog_header_fde($$$$) { my $self = shift; my $dir = shift; my $filebase = shift; my $outfile = shift; my $file = "$dir/$filebase"; my $end_fde_pos = $self->get_end_binlog_fde( $dir, $filebase ); my $fp; my $buf; my $out; open( $fp, "<", $file ) or croak "$!:$file"; binmode $fp; seek( $fp, 0, 0 ); read( $fp, $buf, $end_fde_pos ); open( $out, ">", $outfile ) or croak "$!:$outfile"; binmode $out; print $out $buf; close($fp); close($out); return $end_fde_pos; } sub check_first_header_readable($$$) { my $fp = shift; my $size = shift; my $pos = shift; my ( $event_type, $server_id, $event_length, $end_log_pos ) = MHA::BinlogHeaderParser::unpack_header_util( $fp, $size, $pos ); } sub dump_binlog_from_pos($$$$$) { my $self = shift; my $dir = shift; my $filebase = shift; my $from_pos = shift; my $outfile = shift; my $file = "$dir/$filebase"; my $size = -s $file; my $fp; my $out; my $buf; if ( $from_pos >= $size ) { print " No need to dump effective binlog data from $file (pos starts $from_pos, filesize $size). Skipping.\n"; return; } else { print " Dumping effective binlog data from $file position $from_pos to tail($size).."; } open( $fp, "<", $file ) or croak "$!:$file"; binmode $fp; check_first_header_readable( $fp, $size, $from_pos ); seek( $fp, $from_pos, 0 ); read( $fp, $buf, $size - $from_pos ); open( $out, ">>", $outfile ) or croak "$!:$outfile"; binmode $out; print $out $buf; close($fp); close($out); print " ok.\n"; } sub dump_binlog($$$$$$) { my $self = shift; my $dir = shift; my $from_file = shift; my $from_pos = shift; my $out_diff_file = shift; my $first_file = shift; my $effective_from_pos; if ($first_file) { my $end_fde_pos = $self->dump_binlog_header_fde( $dir, $from_file, $out_diff_file ); print " Dumping binlog format description event, from position 0 to $end_fde_pos.. ok.\n"; if ( $from_pos < $end_fde_pos ) { $effective_from_pos = $end_fde_pos; } else { $effective_from_pos = $from_pos; } } else { $effective_from_pos = $self->dump_init_binlog_without_fde( $dir, $from_file, $out_diff_file ); } $self->dump_binlog_from_pos( $dir, $from_file, $effective_from_pos, $out_diff_file ); } sub dump_mysqlbinlog($$$$$$) { my $self = shift; my $binlog_dir = shift; my $from_file = shift; my $from_pos = shift; my $out_diff_file = shift; my $suppress_row_format = shift; my $disable_log_bin = $self->{disable_log_bin}; my $rc; my $command = "echo \"# Binary/Relay log file $from_file started\" >> $out_diff_file"; system($command); $command = "mysqlbinlog --start-position=$from_pos "; if ($suppress_row_format) { $command .= " --base64-output=never"; } if ($disable_log_bin) { $command .= " --disable-log-bin"; } $command .= " $binlog_dir/$from_file"; $command .= "| filter_mysqlbinlog"; $command .= " >> $out_diff_file"; $rc = system($command); if ($rc) { my ( $high, $low ) = MHA::NodeUtil::system_rc($rc); croak "FATAL: mysqlbinlog to binlog/relaylog file $from_file, generating to $out_diff_file failed with rc $high:$low!\n"; } return 0; } sub concat_all_binlogs_from($$$$) { my $self = shift; my $start_log = shift; my $start_pos = shift; my $outfile = shift; my $binlog_dir = $self->{dir}; my $binlog_prefix = $self->{prefix}; my $end_num = $self->{end_num}; my $handle_raw_binlog = $self->{handle_raw_binlog}; my $mysqlbinlog_version = $self->{mysqlbinlog_version}; my $mysql_version = $self->{mysql_version}; my ( $ignore, $start_num ) = get_head_and_number($start_log); my $suppress_row_format; if ( !$handle_raw_binlog ) { $suppress_row_format = should_suppress_row_format( $mysqlbinlog_version, $mysql_version ); } print " Concat binary/relay logs from $binlog_prefix.$start_num pos $start_pos to $binlog_prefix.$end_num EOF into $outfile ..\n"; for ( my $i = $start_num ; $i <= $end_num ; $i++ ) { my $from_pos = 4; my $first_file = 0; my $from_file = $binlog_prefix . "." . sprintf( "%06d", ($i) ); if ( $i == $start_num ) { $first_file = 1; $from_pos = $start_pos; } # This should never happen if ( !-f "$binlog_dir/$from_file" ) { croak "Target file $binlog_dir/$from_file not found!\n"; } if ($handle_raw_binlog) { $self->dump_binlog( $self->{dir}, $from_file, $from_pos, $outfile, $first_file ); } else { $self->dump_mysqlbinlog( $self->{dir}, $from_file, $from_pos, $outfile, $suppress_row_format ); } } if ( -f $outfile ) { if ($handle_raw_binlog) { croak "$outfile is broken!\n" if is_binlog_head_readable($outfile); if ( -s $outfile <= $self->get_end_binlog_fde( dirname($outfile), basename($outfile) ) ) { print " $outfile has no effective data events.\n"; return 2; } } print " Concat succeeded.\n"; return 0; } else { croak "$outfile not exists!\n"; } return 1; } sub concat_generated_binlogs($$$) { my $self = shift; my $files_ref = shift; my $out = shift; my @diffs = @$files_ref; if ( $self->{handle_raw_binlog} ) { print " Concat all apply files to $out ..\n"; my $from_pos = 0; my $first_file = 1; foreach my $file (@diffs) { if ($first_file) { print " Copying the first binlog file $file to $out.."; copy( $file, $out ) or croak "File copy from $file to $out failed! $!\n"; print " ok.\n"; $first_file = 0; } else { $from_pos = $self->dump_init_binlog_without_fde( dirname($file), basename($file), $out ); if ( $from_pos == 0 ) { print " $file has no effective binlog events.\n"; next; } print " $file has effective binlog events from pos $from_pos.\n"; $self->dump_binlog_from_pos( dirname($file), basename($file), $from_pos, $out ); } } if ( is_binlog_head_readable($out) ) { croak "$out is broken!\n"; } } else { croak "not supported.\n"; } print " Concat succeeded.\n"; } 1; mha4mysql-node-0.54/lib/MHA/BinlogPosFindManager.pm0000644000000000000000000001306412056326635020517 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package MHA::BinlogPosFindManager; use strict; use warnings FATAL => 'all'; use English qw(-no_match_vars); use MHA::BinlogManager; use MHA::BinlogHeaderParser; use MHA::BinlogPosFinder; use MHA::BinlogPosFinderXid; use MHA::BinlogPosFinderElp; use MHA::NodeConst; use MHA::NodeUtil; sub new { my $class = shift; my $self = { binlog_manager => undef, server_id => undef, target_mlf => undef, target_rmlp => undef, master_version => undef, find_logname_only => undef, finder => undef, debug => undef, @_, }; return bless $self, $class; } sub create_finder_elp($) { my $self = shift; return new MHA::BinlogPosFinderElp( name => "BinlogPosFinderElp", master_version => $self->{master_version}, server_id => $self->{server_id}, relay_dir => $self->{binlog_manager}->{dir}, target_rmlp => $self->{target_rmlp}, end_log => $self->{binlog_manager}->{end_log}, handle_raw_binlog => $self->{binlog_manager}->{handle_raw_binlog}, debug => $self->{debug}, ); } sub create_finder_xid($) { my $self = shift; return new MHA::BinlogPosFinderXid( name => "BinlogPosFinderXid", master_version => $self->{master_version}, server_id => $self->{server_id}, relay_dir => $self->{binlog_manager}->{dir}, target_rmlp => $self->{target_rmlp}, end_log => $self->{binlog_manager}->{end_log}, handle_raw_binlog => $self->{binlog_manager}->{handle_raw_binlog}, debug => $self->{debug}, ); } # Recursively reading relay log files in descending order sub find_target_relay_log($$$$) { no warnings qw(recursion); my $self = shift; my $relay_file = shift; my $master_file_on_upper_relay_log = shift; my $post_relay_has_init_rotate_event = shift; my $relay_dir = $self->{binlog_manager}->{dir}; my %status = (); my $has_init_rotate_event = 0; # master log file on this relay log # master log pos at the starting of this relay log my ( $current_mlf, $starting_mlp ); print "Reading $relay_file\n"; my $parser = new MHA::BinlogHeaderParser( dir => $relay_dir, file => $relay_file, self_server_id => $self->{server_id}, master_version => $self->{master_version}, debug => $self->{debug}, ); $parser->open_binlog(); $parser->parse_init_headers(); if ( $parser->{has_real_rotate_event} ) { $current_mlf = $parser->{current_mlf}; $has_init_rotate_event = 1 if ( $parser->{has_real_init_rotate_event} ); } $self->{master_version} = $parser->{master_version} unless ( $self->{master_version} ); if ( ( !$self->{finder} || ( $self->{finder} && $self->{finder}->{name} eq "BinlogPosFinderXid" ) ) && $self->{master_version} && MHA::NodeUtil::mysql_version_ge( $self->{master_version}, "5.0.48" ) ) { $self->{finder} = $self->create_finder_elp(); } else { $self->{finder} = $self->create_finder_xid() unless ( $self->{finder} ); } # master's rotate event not found in this relay log unless ($current_mlf) { # i.e. If master's init rotate event "Rotate to mysqld-bin.000123 (pos 4)" is written in the relay log mysqld-relay-bin.000444 and if mysqld-relay-bin.000443 does not have master's rotate event, mysqld-relay-bin.000443 should have binlog events from mysqld-bin.000122 (mysqld-bin.000123 - 1). If mysqld-relay-bin.000442 does not have master's rotate event, mysqld-relay-bin.000443 should have binlog events from mysqld-bin.000122. if ( $post_relay_has_init_rotate_event == 1 ) { $current_mlf = MHA::BinlogManager::get_prev_file($master_file_on_upper_relay_log); } else { $current_mlf = $master_file_on_upper_relay_log; } } $starting_mlp = $self->{finder}->get_starting_master_pos($parser); $parser->close_binlog(); if ( $current_mlf && defined($starting_mlp) ) { print " $relay_file contains master $current_mlf from position $starting_mlp\n"; } # Target position should be within this relay log # Determining starting relay log position # Starting relay log position equals to just after the end_log_pos that equals to $read_master_log_pos. if ( $current_mlf && defined($starting_mlp) && $current_mlf eq $self->{target_mlf} && $starting_mlp <= $self->{target_rmlp} ) { if ( $self->{find_logname_only} ) { $status{status} = 0; $status{start_rlf} = $relay_file; return %status; } return $self->{finder}->find_starting_relay_pos($relay_file); } else { $self->find_target_relay_log( MHA::BinlogManager::get_prev_file($relay_file), $current_mlf, $has_init_rotate_event ); } } 1; mha4mysql-node-0.54/lib/MHA/NodeUtil.pm0000644000000000000000000001345412056326637016257 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package MHA::NodeUtil; use strict; use warnings FATAL => 'all'; use Carp qw(croak); use MHA::NodeConst; use File::Path; use Errno(); sub create_dir_if($) { my $dir = shift; if ( !-d $dir ) { eval { print "Creating directory $dir.. "; mkpath($dir); print "done.\n"; }; if ($@) { my $e = $@; undef $@; if ( -d $dir ) { print "ok. already exists.\n"; } else { croak "failed to create dir:$dir:$e"; } } } } # Compare file checksum between local and remote host sub compare_checksum { my $local_file = shift; my $remote_path = shift; my $ssh_user = shift; my $ssh_host = shift; my $ssh_port = shift; $ssh_port = 22 unless ($ssh_port); my $local_md5 = `md5sum $local_file`; return 1 if ($?); chomp($local_md5); $local_md5 = substr( $local_md5, 0, 32 ); my $ssh_user_host = $ssh_user . '@' . $ssh_host; my $remote_md5 = `ssh $MHA::NodeConst::SSH_OPT_ALIVE -p $ssh_port $ssh_user_host \"md5sum $remote_path\"`; return 1 if ($?); chomp($remote_md5); $remote_md5 = substr( $remote_md5, 0, 32 ); return 2 if ( $local_md5 ne $remote_md5 ); return 0; } sub file_copy { my $to_remote = shift; my $local_file = shift; my $remote_file = shift; my $ssh_user = shift; my $ssh_host = shift; my $log_output = shift; my $ssh_port = shift; $ssh_port = 22 unless ($ssh_port); my $ssh_user_host = $ssh_user . '@' . $ssh_host; my ( $from, $to ); if ($to_remote) { $from = $local_file; $to = "$ssh_user_host:$remote_file"; } else { $to = $local_file; $from = "$ssh_user_host:$remote_file"; } my $max_retries = 3; my $retry_count = 0; my $copy_fail = 1; my $copy_command = "scp $MHA::NodeConst::SSH_OPT_ALIVE -P $ssh_port $from $to"; if ($log_output) { $copy_command .= " >> $log_output 2>&1"; } while ( $retry_count < $max_retries ) { if ( system($copy_command) || compare_checksum( $local_file, $remote_file, $ssh_user, $ssh_host, $ssh_port ) ) { my $msg = "Failed copy or checksum. Retrying.."; if ($log_output) { system("echo $msg >> $log_output 2>&1"); } else { print "$msg\n"; } $retry_count++; } else { $copy_fail = 0; last; } } return $copy_fail; } sub system_rc($) { my $rc = shift; my $high = $rc >> 8; my $low = $rc & 255; return ( $high, $low ); } sub create_file_if { my $file = shift; if ( $file && ( !-f $file ) ) { open( my $out, ">", $file ) or croak "$!:$file"; close($out); } } sub drop_file_if($) { my $file = shift; if ( $file && -f $file ) { unlink $file or croak "$!:$file"; } } sub get_ip { my $host = shift; my ( $bin_addr_host, $addr_host ); if ( defined($host) ) { $bin_addr_host = gethostbyname($host); unless ($bin_addr_host) { croak "Failed to get IP address on host $host!\n"; } $addr_host = sprintf( "%vd", $bin_addr_host ); return $addr_host; } return; } sub current_time() { my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime(); $mon += 1; $year += 1900; my $val = sprintf( "%d-%02d-%02d %02d:%02d:%02d", $year, $mon, $mday, $hour, $min, $sec ); return $val; } sub check_manager_version { my $manager_version = shift; if ( $manager_version < $MHA::NodeConst::MGR_MIN_VERSION ) { croak "MHA Manager version is $manager_version, but must be $MHA::NodeConst::MGR_MIN_VERSION or higher.\n"; } } sub parse_mysql_version($) { my $str = shift; my $result = sprintf( '%03d%03d%03d', $str =~ m/(\d+)/g ); return $result; } sub parse_mysql_major_version($) { my $str = shift; my $result = sprintf( '%03d%03d', $str =~ m/(\d+)/g ); return $result; } sub mysql_version_ge { my ( $my_version, $target_version ) = @_; my $result = parse_mysql_version($my_version) ge parse_mysql_version($target_version) ? 1 : 0; return $result; } my @shell_escape_chars = ( '"', '!', '#', '&', ';', '`', '|', '*', '?', '~', '<', '>', '^', '(', ')', '[', ']', '{', '}', '$', ',', ' ', '\x0A', '\xFF' ); sub unescape_for_shell { my $str = shift; if ( !index( $str, '\\\\' ) ) { return $str; } foreach my $c (@shell_escape_chars) { my $x = quotemeta($c); my $pattern = "\\\\(" . $x . ")"; $str =~ s/$pattern/$1/g; } return $str; } sub escape_for_shell { my $str = shift; my $ret = ""; foreach my $c ( split //, $str ) { my $x = $c; my $escape = 0; foreach my $e (@shell_escape_chars) { if ( $e eq $x ) { $escape = 1; last; } } if ( $x eq "'" ) { $x =~ s/'/'\\''/; } if ( $x eq "\\" ) { $x = "\\\\"; } if ($escape) { $x = "\\" . $x; } $ret .= "$x"; } $ret = "'" . $ret . "'"; return $ret; } sub escape_for_mysql_command { my $str = shift; my $ret = ""; foreach my $c ( split //, $str ) { my $x = $c; if ( $x eq "'" ) { $x =~ s/'/'\\''/; } $ret .= $x; } $ret = "'" . $ret . "'"; return $ret; } 1; mha4mysql-node-0.54/lib/MHA/BinlogPosFinderElp.pm0000644000000000000000000000431312056326635020211 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package MHA::BinlogPosFinderElp; use strict; use warnings FATAL => 'all'; use MHA::NodeConst; use MHA::NodeUtil; use MHA::BinlogHeaderParser; use MHA::BinlogManager; use base 'MHA::BinlogPosFinder'; sub get_starting_master_pos($$) { my $self = shift; my $parser = shift; return $parser->get_starting_mlp(); } sub find_starting_relay_pos($$) { my $self = shift; my $relay_file = shift; my $start_rlp = 0; my $found = 0; my %status = (); my $relay_dir = $self->{relay_dir}; my $parser = new MHA::BinlogHeaderParser( dir => $relay_dir, file => $relay_file, self_server_id => $self->{server_id}, target_rmlp => $self->{target_rmlp}, debug => $self->{debug}, ); $parser->open_binlog(); ( $found, $start_rlp ) = $parser->find_target_relay_pos(); $parser->close_binlog(); if ($found) { $status{status} = 0; $status{start_rlf} = $relay_file; $status{start_rlp} = $start_rlp; if ( $start_rlp == $parser->{binlog_size} ) { if ( $relay_file eq $self->{end_log} ) { $status{status} = $MHA::NodeConst::Target_Has_Received_All_Relay_Logs; } else { $status{start_rlf} = MHA::BinlogManager::get_post_file($relay_file); $status{start_rlp} = 4; } } return %status; } else { print "Target pos NOT found!\n"; $status{status} = $MHA::NodeConst::Relay_Pos_Not_Found; return %status; } } 1; mha4mysql-node-0.54/lib/MHA/BinlogPosFinder.pm0000644000000000000000000000316012056326635017547 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package MHA::BinlogPosFinder; use strict; use warnings FATAL => 'all'; use MHA::NodeConst; sub new { my $class = shift; my $self = { name => undef, master_version => undef, server_id => undef, mb_arg => "", relay_dir => undef, target_rmlp => undef, end_log => undef, handle_raw_binlog => undef, debug => undef, @_, }; return bless $self, $class; } sub find_starting_relay_pos { } sub get_starting_master_pos { } sub is_match_rotate_event($$) { my $self = shift; my $line = shift; if ( $line =~ m/^#.*server id (\d+).*end_log_pos.*Rotate to\s+(\S+)\s+pos:\s+(\d+)\s+/ ) { my $sid = $1; my $mpos = $3; return 0 if ( $self->{server_id} == $sid ); return 1 if ( $self->{target_rmlp} == $mpos ); } return 0; } 1; mha4mysql-node-0.54/lib/MHA/SlaveUtil.pm0000644000000000000000000001452712056326640016440 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package MHA::SlaveUtil; use strict; use warnings FATAL => 'all'; use English qw(-no_match_vars); use File::Basename; use MHA::NodeUtil; use DBI; use constant Get_Version_SQL => "SELECT VERSION() AS Value"; use constant Get_Datadir_SQL => "SELECT \@\@global.datadir AS Value"; use constant Get_Relay_Log_Info_Type_SQL => "SELECT \@\@global.relay_log_info_repository AS Value"; use constant Get_Relay_Log_File_SQL => "SELECT Relay_log_name FROM mysql.slave_relay_log_info"; use constant Get_Relay_Log_Info_SQL => "SELECT \@\@global.relay_log_info_file AS Value"; use constant Is_Relay_Purge_SQL => "SELECT \@\@global.relay_log_purge As Value"; use constant Show_Log_Error_File_SQL => "SHOW VARIABLES LIKE 'log_error'"; use constant Show_Slave_Status_SQL => "SHOW SLAVE STATUS"; use constant Disable_Relay_Purge_SQL => "SET GLOBAL relay_log_purge=0"; use constant Enable_Relay_Purge_SQL => "SET GLOBAL relay_log_purge=1"; use constant Flush_Relay_Logs_SQL => "FLUSH NO_WRITE_TO_BINLOG /*!50501 RELAY */ LOGS"; use constant Get_Failover_Lock_SQL => "SELECT GET_LOCK('MHA_Master_High_Availability_Failover', ?) AS Value"; use constant Release_Failover_Lock_SQL => "SELECT RELEASE_LOCK('MHA_Master_High_Availability_Failover') As Value"; use constant Get_Monitor_Lock_SQL => "SELECT GET_LOCK('MHA_Master_High_Availability_Monitor', ?) AS Value"; use constant Release_Monitor_Lock_SQL => "SELECT RELEASE_LOCK('MHA_Master_High_Availability_Monitor') As Value"; sub get_variable($$) { my $dbh = shift; my $query = shift; my $sth = $dbh->prepare($query); $sth->execute(); my $href = $sth->fetchrow_hashref; return $href->{Value}; } sub get_version($) { my $dbh = shift; return get_variable( $dbh, Get_Version_SQL ); } sub get_log_error_file($) { my $dbh = shift; return get_variable( $dbh, Show_Log_Error_File_SQL ); } sub get_relay_log_info_type { my $dbh = shift; my $mysql_version = shift; $mysql_version = get_version($dbh) unless ($mysql_version); if ( !MHA::NodeUtil::mysql_version_ge( $mysql_version, "5.6.0" ) ) { return "FILE"; } my $type = get_variable( $dbh, Get_Relay_Log_Info_Type_SQL ); return $type; } sub get_relay_dir_file_from_table($) { my $dbh = shift; my $sth = $dbh->prepare(Get_Relay_Log_File_SQL); my $ret = $sth->execute(); my $href = $sth->fetchrow_hashref; if ( !defined($href) || !defined( $href->{Relay_log_name} ) ) { return; } my $current_relay_log_file = $href->{Relay_log_name}; my $datadir = get_variable( $dbh, Get_Datadir_SQL ); my $relay_dir; unless ( $current_relay_log_file =~ m/^\// ) { $current_relay_log_file =~ s/^\.\///; $current_relay_log_file = $datadir . "/" . $current_relay_log_file; $relay_dir = $datadir; $relay_dir =~ s/\/$//; } else { $relay_dir = dirname($current_relay_log_file); } my $relay_log_basename = basename($current_relay_log_file); return ( $relay_dir, $relay_log_basename ); } sub get_relay_log_info_path { my $dbh = shift; my $mysql_version = shift; my $relay_log_info_path; my $filename; my $datadir = get_variable( $dbh, Get_Datadir_SQL ); $mysql_version = get_version($dbh) unless ($mysql_version); if ( MHA::NodeUtil::mysql_version_ge( $mysql_version, "5.1.0" ) ) { $filename = get_variable( $dbh, Get_Relay_Log_Info_SQL ); } #relay_log_info_file was introduced in 5.1. In 5.0, it's fixed to "relay_log.info" if ( !defined($filename) ) { $filename = "relay-log.info"; } unless ( $filename =~ m/^\// ) { $filename =~ s/^\.\///; $datadir =~ s/\/$//; $relay_log_info_path = $datadir . "/" . $filename; } else { $relay_log_info_path = $filename; } return $relay_log_info_path; } sub is_relay_log_purge($) { my $dbh = shift; return get_variable( $dbh, Is_Relay_Purge_SQL ); } sub disable_relay_log_purge($) { my $dbh = shift; $dbh->do(Disable_Relay_Purge_SQL); } sub purge_relay_logs($) { my $dbh = shift; $dbh->do(Enable_Relay_Purge_SQL); $dbh->do(Flush_Relay_Logs_SQL); # To (almost) make sure that relay log is switched(purged) before setting # relay_log_purge=0; sleep 3; $dbh->do(Disable_Relay_Purge_SQL); return 0; } sub is_slave($) { my $dbh = shift; my $query = Show_Slave_Status_SQL; my $sth = $dbh->prepare($query); my $ret = $sth->execute(); if ( !defined($ret) || $ret != 1 ) { return 0; } return 1; } sub get_advisory_lock_internal($$$) { my $dbh = shift; my $timeout = shift; my $query = shift; my $sth = $dbh->prepare($query); my $ret = $sth->execute($timeout); my $href = $sth->fetchrow_hashref; if ( !defined($href) || !defined( $href->{Value} ) ) { return 2; } elsif ( $href->{Value} != 1 ) { return 1; } return 0; } sub release_advisory_lock_internal($$) { my $dbh = shift; my $query = shift; my $sth = $dbh->prepare($query); my $ret = $sth->execute(); my $href = $sth->fetchrow_hashref; if ( !defined($href) || !defined( $href->{Value} ) || $href->{Value} != 1 ) { return 1; } return 0; } sub get_failover_advisory_lock { my $dbh = shift; my $timeout = shift; return get_advisory_lock_internal( $dbh, $timeout, Get_Failover_Lock_SQL ); } sub release_failover_advisory_lock($) { my $dbh = shift; return release_advisory_lock_internal( $dbh, Release_Failover_Lock_SQL ); } sub get_monitor_advisory_lock { my $dbh = shift; my $timeout = shift; return get_advisory_lock_internal( $dbh, $timeout, Get_Monitor_Lock_SQL ); } sub release_monitor_advisory_lock($) { my $dbh = shift; return release_advisory_lock_internal( $dbh, Release_Monitor_Lock_SQL ); } 1; mha4mysql-node-0.54/lib/MHA/BinlogPosFinderXid.pm0000644000000000000000000000607212056326637020223 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package MHA::BinlogPosFinderXid; use strict; use warnings FATAL => 'all'; use Carp qw(croak); use MHA::NodeConst; use MHA::NodeUtil; use MHA::BinlogHeaderParser; use MHA::BinlogManager; use base 'MHA::BinlogPosFinder'; sub get_starting_master_pos($$) { my $self = shift; my $parser = shift; return $parser->get_starting_mlp_xid(); } sub find_starting_relay_pos($$) { my $self = shift; my $relay_file = shift; my $last_absolute_mpos = 0; my $prev_mpos = 0; my $in_relative = 0; my $real_mpos = 0; my %status = (); my $start_rlp; my $start_rlf; my $found; my $parser; my ( $relay_prefix, $start_relay_num ) = MHA::BinlogManager::get_head_and_number($relay_file); my $relay_dir = $self->{relay_dir}; print "Finding target relay pos by using Xid, not end_log_pos. This is because master's version is 5.0.45 or lower, or master's version is unknown. It is recommended upgrading MySQL 5.0.latest, 5.1 or later.\n"; for ( my $i = $start_relay_num ; ; $i++ ) { my $from_file = $relay_prefix . "." . sprintf( "%06d", ($i) ); last if ( !-f "$relay_dir/$from_file" ); $parser = new MHA::BinlogHeaderParser( dir => $relay_dir, file => $from_file, self_server_id => $self->{server_id}, target_rmlp => $self->{target_rmlp}, debug => $self->{debug}, ); $parser->open_binlog(); ( $found, $start_rlp, $last_absolute_mpos, $prev_mpos, $in_relative, $real_mpos ) = $parser->find_target_relay_pos_xid( $last_absolute_mpos, $prev_mpos, $in_relative, $real_mpos ); $parser->close_binlog(); if ($found) { $start_rlf = $from_file; last; } } if ($found) { $status{status} = 0; $status{start_rlf} = $start_rlf; $status{start_rlp} = $start_rlp; if ( $start_rlp == $parser->{binlog_size} ) { if ( $start_rlf eq $self->{end_log} ) { $status{status} = $MHA::NodeConst::Target_Has_Received_All_Relay_Logs; } else { $status{start_rlf} = MHA::BinlogManager::get_post_file($start_rlf); $status{start_rlp} = 4; } } return %status; } else { print "Target pos NOT found!\n"; $status{status} = $MHA::NodeConst::Relay_Pos_Not_Found; return %status; } } 1; mha4mysql-node-0.54/lib/MHA/BinlogHeaderParser.pm0000644000000000000000000002736712056326633020240 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package MHA::BinlogHeaderParser; use strict; use warnings FATAL => 'all'; use English qw(-no_match_vars); use Carp qw(croak); use File::Basename; use File::Path; use Errno(); sub new { my $class = shift; my $self = { dir => undef, file => undef, self_server_id => undef, target_rmlp => undef, target_mlf => undef, master_version => undef, current_mlf => undef, starting_mlp => undef, fp => undef, current_pos => 4, prev_pos => 4, binlog_size => undef, has_real_rotate_event => 0, has_real_init_rotate_event => 0, debug => 0, @_, }; return bless $self, $class; } our $ROTATE_EVENT = 4; our $FORMAT_DESCRIPTION_EVENT = 15; our $XID_EVENT = 16; our $LOG_EVENT_MINIMAL_HEADER_LEN = 19; our $MAX_ALLOWED_PACKET = 1024 * 1024 * 1024; sub open_binlog($) { my $self = shift; croak "binlog dir must be set.\n" unless ( $self->{dir} ); croak "binlog file must be set.\n" unless ( $self->{file} ); open( $self->{fp}, "<", "$self->{dir}/$self->{file}" ) or croak "$!:$self->{dir}/$self->{file}"; binmode $self->{fp}; $self->{binlog_size} = -s "$self->{dir}/$self->{file}"; } sub close_binlog($) { my $self = shift; close( $self->{fp} ); } sub unpack_header { my $self = shift; my $pos = shift; $pos = $self->{current_pos} if ( !defined($pos) ); my $after_pos = shift; $after_pos = $pos if ( !defined($after_pos) ); my $fp = $self->{fp}; my $file_size = $self->{binlog_size}; return unpack_header_util( $fp, $file_size, $pos, $after_pos ); } sub unpack_header_util { my $fp = shift; my $file_size = shift; my $pos = shift; my $after_pos = shift; $after_pos = $pos if ( !defined($after_pos) ); if ( $pos >= $file_size || $after_pos >= $file_size ) { warn "Invalid position is set. pos=$pos after_pos=$after_pos\n"; return; } my $event_type; my $server_id; my $event_length; my $end_log_pos; seek( $fp, $pos + 4, 0 ); read( $fp, $event_type, 1 ); seek( $fp, $pos + 5, 0 ); read( $fp, $server_id, 4 ); seek( $fp, $pos + 9, 0 ); read( $fp, $event_length, 4 ); seek( $fp, $pos + 13, 0 ); read( $fp, $end_log_pos, 4 ); seek( $fp, $after_pos, 0 ); $event_type = unpack( 'C', $event_type ); $server_id = unpack( 'V', $server_id ); $event_length = unpack( 'V', $event_length ); $end_log_pos = unpack( 'V', $end_log_pos ); if ( $event_length > $MAX_ALLOWED_PACKET ) { croak "Event too large: pos: $pos, event_length: $event_length, event_type: $event_type\n"; } if ( $event_length < $LOG_EVENT_MINIMAL_HEADER_LEN ) { croak "Event too small: pos: $pos, event_length: $event_length, event_type: $event_type\n"; } return ( $event_type, $server_id, $event_length, $end_log_pos ); } sub get_master_version_from_fde($$) { my $self = shift; my $pos = shift; my $fp = $self->{fp}; my ( $event_type, $server_id, $b, $c ) = $self->unpack_header($pos); if ( $event_type == $FORMAT_DESCRIPTION_EVENT ) { seek( $fp, $pos + 21, 0 ); read( $fp, $self->{master_version}, 50 ); $self->{master_version} =~ s/\0//g; print " Master Version is $self->{master_version}\n"; } else { croak "This is not format description event! ev type=$event_type, pos=$pos.\n"; } seek( $fp, $pos, 0 ); return $self->{master_version}; } sub parse_master_rotate_event($$) { my $self = shift; my $pos = shift; my $fp = $self->{fp}; my ( $event_type, $server_id, $event_length, $end_log_pos ) = $self->unpack_header($pos); if ( $event_type == $ROTATE_EVENT ) { # real rotate event if ( $end_log_pos == 0 || $end_log_pos == $self->{current_pos} ) { my $offset = 19; my $header_len = 8; my $rotate_pos; seek( $fp, $pos + $offset, 0 ); read( $fp, $rotate_pos, $header_len ); $end_log_pos = unpack( 'V', $rotate_pos ); seek( $fp, $pos + $offset + $header_len, 0 ); read( $fp, $self->{current_mlf}, $event_length - $offset - $header_len ); $self->{has_real_rotate_event} = 1; $self->{has_real_init_rotate_event} = 1 if ( $end_log_pos <= 4 ); print "parse_master_rotate_event(real rotate event): file=$self->{file} event_type=$event_type server_id=$server_id length=$event_length elp=$end_log_pos\n" if ( $self->{debug} ); } else { print "parse_master_rotate_event(non-real rotate event): file=$self->{file} event_type=$event_type server_id=$server_id length=$event_length elp=$end_log_pos\n" if ( $self->{debug} ); } } else { croak "This is not rotate event! ev type=$event_type, pos=$pos.\n"; } seek( $fp, $pos, 0 ); $self->{starting_mlp} = $end_log_pos unless ( $self->{starting_mlp} ); return $end_log_pos; } sub parse_forward_header($) { my $self = shift; my $fp = $self->{fp}; my $pos = $self->{current_pos}; return if ( $self->{current_pos} >= $self->{binlog_size} ); my ( $event_type, $server_id, $event_length, $end_log_pos ) = $self->unpack_header($pos); $self->{prev_pos} = $self->{current_pos}; $self->{current_pos} = $self->{current_pos} + $event_length; return ( $event_type, $server_id, $event_length, $end_log_pos ); } sub parse_init_headers { my $self = shift; my $do_dump = shift; my $outfile = shift; while ( my ( $event_type, $server_id, $event_length, $end_log_pos ) = $self->parse_forward_header() ) { print "parse_init_headers: file=$self->{file} event_type=$event_type server_id=$server_id length=$event_length nextmpos=$end_log_pos prevrelay=$self->{prev_pos} cur(post)relay=$self->{current_pos}\n" if ( $self->{debug} ); if ( $event_type == $FORMAT_DESCRIPTION_EVENT ) { if ( $self->{self_server_id} && $server_id != $self->{self_server_id} ) { $self->{starting_mlp} = $end_log_pos if ( !$self->{starting_mlp} && $end_log_pos > 0 ); if ( !$self->{master_version} ) { $self->get_master_version_from_fde( $self->{prev_pos} ); } } } elsif ( $event_type == $ROTATE_EVENT ) { if ( $self->{self_server_id} && $server_id != $self->{self_server_id} ) { $end_log_pos = $self->parse_master_rotate_event( $self->{prev_pos} ); } if ($do_dump) { print "dumping rotate event from $self->{prev_pos} to $self->{current_pos}.\n" if ( $self->{debug} ); my $buf; open( my $out, ">>", $outfile ) or croak "$!:$outfile"; binmode $out; seek( $self->{fp}, $self->{prev_pos}, 0 ); read( $self->{fp}, $buf, $self->{current_pos} - $self->{prev_pos} ); print $out $buf; close($out); } } else { return $self->{prev_pos}; } } return $self->{current_pos}; } sub get_starting_mlp($) { my $self = shift; if ( $self->{starting_mlp} ) { print "starting_mlp: $self->{starting_mlp}\n" if ( $self->{debug} ); return $self->{starting_mlp}; } while ( my ( $event_type, $server_id, $event_length, $end_log_pos ) = $self->parse_forward_header() ) { print "get_starting_mlp: file=$self->{file} event_type=$event_type server_id=$server_id length=$event_length next=$end_log_pos\n" if ( $self->{debug} ); next if ( $server_id == $self->{self_server_id} ); next if ( $event_type == $FORMAT_DESCRIPTION_EVENT ); next if ( $event_type == $ROTATE_EVENT ); next if ( $end_log_pos <= 0 ); $self->{starting_mlp} = $end_log_pos; return $self->{starting_mlp}; } return; } sub get_starting_mlp_xid($) { my $self = shift; while ( my ( $event_type, $server_id, $event_length, $end_log_pos ) = $self->parse_forward_header() ) { print "get_starting_mlp_xid: file=$self->{file} event_type=$event_type server_id=$server_id length=$event_length next=$end_log_pos\n" if ( $self->{debug} ); next if ( $server_id == $self->{self_server_id} ); next if ( $event_type == $FORMAT_DESCRIPTION_EVENT ); next if ( $event_type == $ROTATE_EVENT ); next if ( $end_log_pos <= 0 ); if ( $event_type == $XID_EVENT ) { $self->{starting_mlp} = $end_log_pos; return $self->{starting_mlp}; } else { if ( $self->{starting_mlp} && $self->{starting_mlp} <= $end_log_pos ) { return $self->{starting_mlp}; } else { return; } } } return; } sub find_target_relay_pos($) { my $self = shift; my $found = 0; while ( my ( $event_type, $server_id, $event_length, $end_log_pos ) = $self->parse_forward_header() ) { print "find_target_relay_pos: file=$self->{file} event_type=$event_type server_id=$server_id length=$event_length next=$end_log_pos\n" if ( $self->{debug} ); next if ( $server_id == $self->{self_server_id} ); next if ( $event_type == $FORMAT_DESCRIPTION_EVENT ); if ( $event_type == $ROTATE_EVENT ) { $end_log_pos = $self->parse_master_rotate_event( $self->{prev_pos} ); } if ( $end_log_pos == $self->{target_rmlp} ) { $found = 1; return ( $found, $self->{current_pos} ); } } $found = 0; return $found; } sub find_target_relay_pos_xid($$$$$) { my $self = shift; my $last_absolute_mpos = shift; my $prev_mpos = shift; my $in_relative = shift; my $real_mpos = shift; my $found = 0; my $start_rlp; while ( my ( $event_type, $server_id, $event_length, $end_log_pos ) = $self->parse_forward_header() ) { print "find_target_relay_pos_xid: file=$self->{file} event_type=$event_type server_id=$server_id length=$event_length next=$end_log_pos\n" if ( $self->{debug} ); next if ( $event_type == $FORMAT_DESCRIPTION_EVENT ); next if ( $server_id == $self->{self_server_id} ); if ( $event_type == $ROTATE_EVENT ) { $end_log_pos = $self->parse_master_rotate_event( $self->{prev_pos} ); } if ( $end_log_pos == $event_length || ( $end_log_pos < $prev_mpos && !$in_relative ) ) { # Entering relative mode $last_absolute_mpos = $prev_mpos; $in_relative = 1; $real_mpos = $last_absolute_mpos + $end_log_pos; } elsif ( $end_log_pos < $prev_mpos && $in_relative ) { # void event } elsif ( $in_relative && $event_type != $XID_EVENT ) { # Continuing relative mode $real_mpos = $last_absolute_mpos + $end_log_pos; } elsif ( $event_type == $XID_EVENT ) { # Exiting relative mode $real_mpos = $end_log_pos; $last_absolute_mpos = $end_log_pos; $in_relative = 0; } else { # Not in relative mode $real_mpos = $end_log_pos; $last_absolute_mpos = $end_log_pos; } $prev_mpos = $end_log_pos; if ( $real_mpos == $self->{target_rmlp} ) { $found = 1; $start_rlp = $self->{current_pos}; last; } } return ( $found, $start_rlp, $last_absolute_mpos, $prev_mpos, $in_relative, $real_mpos ); } 1; mha4mysql-node-0.54/META.yml0000644000000000000000000000070312056326655014265 0ustar rootroot--- author: - 'Yoshinori Matsunobu ' build_requires: ExtUtils::MakeMaker: 6.42 configure_requires: ExtUtils::MakeMaker: 6.42 distribution_type: module generated_by: 'Module::Install version 0.91' license: 'GPL v2' meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: mha4mysql-node no_index: directory: - inc - t requires: DBD::mysql: 0 DBI: 0 version: 0.54 mha4mysql-node-0.54/AUTHORS0000644000000000000000000000011611770663665014071 0ustar rootrootDeveloper and Maintainer: Yoshinori Matsunobu mha4mysql-node-0.54/bin/0000755000000000000000000000000012056326664013564 5ustar rootrootmha4mysql-node-0.54/bin/save_binary_logs0000755000000000000000000001613712056326632017043 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use strict; use warnings FATAL => 'all'; use Carp qw(croak); use MHA::BinlogManager; use MHA::NodeConst; use MHA::NodeUtil; use File::Basename; use Getopt::Long; use Pod::Usage; GetOptions( \my %opt, qw/ help version command=s start_file=s start_pos=i binlog_prefix=s binlog_dir=s output_file=s datadir=s relay_log_info=s oldest_version=s handle_raw_binlog=i disable_log_bin=i manager_version=s debug /, ) or pod2usage(1); # for compatibility unless ( $opt{datadir} ) { $opt{datadir} = $opt{binlog_dir}; } $opt{binlog_dir} ||= "/var/lib/mysql"; $opt{handle_raw_binlog} = 1 if ( !defined( $opt{handle_raw_binlog} ) ); $opt{disable_log_bin} = 0 if ( !defined( $opt{disable_log_bin} ) ); $| = 1; my $_binlog_manager; my $EVENT_NOT_EXIST = 10; exit &main(); sub main { my $exit_code = 1; eval { if ( $opt{help} ) { pod2usage(0); } if ( $opt{version} ) { print "save_binary_logs version $MHA::NodeConst::VERSION.\n"; exit 0; } MHA::NodeUtil::check_manager_version( $opt{manager_version} ) if ( $opt{manager_version} ); unless ( $opt{command} ) { croak "Set --command=[test|save]\n"; } if ( $opt{command} eq "test" ) { if ( !$opt{start_file} && !$opt{binlog_prefix} ) { croak "Set --start_file= or --binlog_prefix=\n"; } } elsif ( !$opt{start_file} ) { croak "Set --start_file=\n"; } if ( !defined( $opt{start_pos} ) ) { croak "Set --start_pos=\n"; } $_binlog_manager = new MHA::BinlogManager( handle_raw_binlog => $opt{handle_raw_binlog}, disable_log_bin => $opt{disable_log_bin}, mysql_version => $opt{oldest_version}, debug => $opt{debug}, ); $_binlog_manager->init_mysqlbinlog() unless ( $opt{handle_raw_binlog} ); # Finding target binary/relay log directory if ( $opt{relay_log_info} ) { $_binlog_manager->init_from_relay_log_info( $opt{relay_log_info}, $opt{datadir} ); } else { my $binlog_dir; if ( $opt{start_file} ) { $binlog_dir = MHA::BinlogManager::find_correct_binlog_dir( $opt{start_file}, $opt{binlog_dir} ); } else { ( $binlog_dir, $opt{start_file} ) = MHA::BinlogManager::find_correct_binlog_dir_file_from_prefix( $opt{binlog_prefix}, $opt{binlog_dir} ); } croak "Binlog not found from $opt{binlog_dir}! If you got this error at MHA Manager, please set \"master_binlog_dir=/path/to/binlog_directory_of_the_master\" correctly in the MHA Manager's configuration file and try again.\n" unless ($binlog_dir); $_binlog_manager->init_from_dir_file( $binlog_dir, $opt{start_file} ); } unless ( $opt{output_file} ) { croak "Set --output_file=\n"; } printf( " Creating %s if not exists.. ", dirname( $opt{output_file} ) ); MHA::NodeUtil::create_dir_if( dirname( $opt{output_file} ) ); print " ok.\n"; if ( $opt{command} eq "test" ) { print " Checking output directory is accessible or not..\n"; my $fh; open( $fh, ">", $opt{output_file} ) or croak "$!:$opt{output_file}\n"; unlink $opt{output_file}; print " ok.\n"; print " Binlog found at $_binlog_manager->{dir}, up to $_binlog_manager->{end_log}\n"; exit 0; } elsif ( $opt{command} eq "save" ) { my $rc = generate_diff_binary_log(); if ( $rc == $EVENT_NOT_EXIST ) { print "Event not exists.\n"; exit $rc; } elsif ($rc) { croak "Failed!\n"; } else { exit 0; } } else { pod2usage(1); } $exit_code = 0; }; if ($@) { warn "Failed to save binary log: $@"; } return $exit_code; } sub generate_diff_binary_log() { my $start_binlog_file = $opt{start_file}; my $start_binlog_pos = $opt{start_pos}; my $out_diff_file = $opt{output_file}; MHA::NodeUtil::drop_file_if($out_diff_file); if ( $_binlog_manager->concat_all_binlogs_from( $start_binlog_file, $start_binlog_pos, $out_diff_file ) ) { return $EVENT_NOT_EXIST; } return 0; } # ############################################################################ # Documentation # ############################################################################ =pod =head1 NAME save_binary_logs - Concatenating binary or relay logs from the specified file/position to the end of the log. This command is automatically executed from MHA Manager on failover, and manual execution should not be needed normally. =head1 SYNOPSIS # Test $ save_binary_logs --command=test --binlog_dir=/var/lib/mysql --start_file=mysqld-bin.000002 # Saving binary logs $ save_binary_logs --command=save --binlog_dir=/var/lib/mysql --start_file=mysqld-bin.000002 --start_pos=312 --output_file=/var/tmp/aggregate.binlog # Saving relay logs $ save_binary_logs --command=save --start_file=mysqld-relay-bin.000002 --start_pos=312 --relay_log_info=/var/lib/mysql/relay-log.info --output_file=/var/tmp/aggregate.binlog save_binary_logs concatenates binary or relay logs from the specified log file/position to the end of the log. This tool is intended to be invoked from the master failover script(MHA Manager), and manual execution is normally not needed. =head1 DESCRIPTION Suppose that master is crashed and the latest slave server has received binary logs up to mysqld-bin.000002:312. It is likely that master has more binary logs. If it is not sent to the slave, slaves will lose all binlogs from mysqld-bin.000002:312. The purpose of the save_binary_logs is to save binary logs that are not replicated to slaves. If master is reachable through SSH and binary logs are readable, saving binary logs is possible. Here is an example: $ save_binary_logs --command=save --start_file=mysqld-bin.000002 --start_pos=312 --output_file=/var/tmp/aggregate.binlog Then all binary logs starting from mysqld-bin.000002:312 are concatenated and stored into /var/tmp/aggregate.binlog. If you have binary logs up to mysqld-bin.000004, the following mysqlbinlog outputs are written. mysqld-bin.000002:Format Description Event(FDE), plus from 312 to the tail mysqld-bin.000003:from 0 to the tail, excluding FDE mysqld-bin.000004:from 0 to the tail, excluding FDE mha4mysql-node-0.54/bin/apply_diff_relay_logs0000755000000000000000000003715112056326630020047 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use strict; use warnings FATAL => 'all'; use Carp qw(croak); use MHA::BinlogManager; use MHA::BinlogPosFindManager; use MHA::BinlogPosFinder; use MHA::BinlogPosFinderXid; use MHA::BinlogPosFinderElp; use MHA::NodeConst; use MHA::NodeUtil; use Getopt::Long; use Pod::Usage; use File::Basename; use File::Copy; use Sys::Hostname; GetOptions( \my %opt, qw/ help version command=s datadir=s relay_log_info=s relay_dir=s current_relay_log=s scp_user=s scp_host=s scp_port=i ssh_options=s slave_user=s slave_pass=s slave_host=s slave_ip=s slave_port=i master_server_id=i server_id=i latest_mlf=s latest_rmlp=i target_mlf=s target_rmlp=i target_version=s workdir=s diff_file_readtolatest=s apply_files=s timestamp=s handle_raw_binlog=i disable_log_bin=i no_apply manager_version=s debug /, ) or pod2usage(1); $opt{command} ||= ""; $opt{scp_user} ||= "root"; $opt{scp_port} ||= 22; $opt{slave_user} ||= "root"; $opt{slave_pass} ||= ""; # for printing and authentication $opt{slave_host} ||= "127.0.0.1"; $opt{slave_port} ||= 3306; $opt{target_rmlp} ||= 0; $opt{workdir} ||= "/var/tmp"; $opt{timestamp} ||= "0"; $opt{handle_raw_binlog} = 1 if ( !defined( $opt{handle_raw_binlog} ) ); $opt{disable_log_bin} = 0 if ( !defined( $opt{disable_log_bin} ) ); # for compatibility unless ( $opt{datadir} ) { $opt{datadir} = $opt{relay_dir}; } if ( $opt{ssh_options} ) { $MHA::NodeConst::SSH_OPT_ALIVE = $opt{ssh_options}; } my $_binlog_manager; my $_find_logname_only = 0; my $_escaped_slave_user; my $_escaped_slave_pass; $| = 1; if ( $opt{help} ) { pod2usage(0); } if ( $opt{version} ) { print "apply_diff_relay_logs version $MHA::NodeConst::VERSION.\n"; exit 0; } exit &main(); sub escape_for_mysql { my $str = shift; unless ($str) { return $str; } $str = MHA::NodeUtil::unescape_for_shell($str); $str = MHA::NodeUtil::escape_for_mysql_command($str); return $str; } sub escape_mysql_account { $_escaped_slave_user = escape_for_mysql( $opt{slave_user} ); $_escaped_slave_pass = escape_for_mysql( $opt{slave_pass} ); } sub fast_find_pos() { my %status = (); if ( $opt{target_mlf} eq $opt{latest_mlf} ) { my $offset = $opt{latest_rmlp} - $opt{target_rmlp}; my $filesize = -s "$_binlog_manager->{dir}/$_binlog_manager->{end_log}"; my $start_rlp = $filesize - $offset; return if ( $start_rlp <= 0 ); # Checking binlog is readable from this position unless ( system( "mysqlbinlog --start-position=$start_rlp --stop-position=$start_rlp $_binlog_manager->{dir}/$_binlog_manager->{end_log} > /dev/null" ) ) { $status{status} = 0; $status{start_rlf} = $_binlog_manager->{end_log}; $status{start_rlp} = $start_rlp; return %status; } } else { return; } return; } sub generate_diff_relay_log($$$) { my $start_relay_log = shift; my $start_relay_pos = shift; my $out = shift; return $_binlog_manager->concat_all_binlogs_from( $start_relay_log, $start_relay_pos, $out ); } sub find_starting_relay_log { my %start; unless ( $opt{latest_mlf} ) { croak "--latest_mlf (my latest master log file name) must be set.\n"; } unless ( $opt{target_mlf} ) { croak "--target_mlf (target master log file name) must be set.\n"; } unless ( $opt{target_rmlp} ) { croak "--target_rmlp (target master read log pos) must be set.\n"; } unless ( $opt{latest_rmlp} ) { croak "--latest_rmlp (latest master read log pos) must be set.\n"; } unless ( $opt{server_id} ) { croak "--server_id (my server id) must be set.\n"; } if ( %start = fast_find_pos() ) { print " Fast relay log position search succeeded.\n"; } else { print " Fast relay log position search failed. Reading relay logs to find..\n"; %start = new MHA::BinlogPosFindManager( binlog_manager => $_binlog_manager, server_id => $opt{server_id}, target_mlf => $opt{target_mlf}, target_rmlp => $opt{target_rmlp}, find_logname_only => $_find_logname_only, debug => $opt{debug}, )->find_target_relay_log( $_binlog_manager->{end_log}, $opt{latest_mlf}, 0 ); if ( !defined( $start{status} ) ) { $start{status} = $MHA::NodeConst::Relay_Log_Not_Found; return %start; } return %start if ( $start{status} != 0 || $_find_logname_only ); if ( !$start{start_rlf} || !defined( $start{start_rlp} ) ) { print "FATAL: getting start relay file and/or position failed.\n"; $start{status} = $MHA::NodeConst::Relay_Log_Not_Found; return %start; } } print " Target relay log file/position found. start_file:$start{start_rlf}, start_pos:$start{start_rlp}.\n"; return %start; } sub do_generate($$$) { my $start_relay_log = shift; my $start_relay_pos = shift; my $out = shift; my $rc = generate_diff_relay_log( $start_relay_log, $start_relay_pos, $out ); print " Generating diff relay log succeeded. Saved at $out .\n" if ( $rc == 0 ); return $rc; } sub use_binary_mode() { my $v = `mysql --version`; my $mysqlclient_version; chomp($v); if ( $v =~ /Distrib (\d+\.\d+\.\d+)/ ) { $mysqlclient_version = $1; } if ( $mysqlclient_version && MHA::NodeUtil::mysql_version_ge( $mysqlclient_version, "5.6.3" ) ) { print "MySQL client version is $mysqlclient_version. Using --binary-mode.\n"; return "--binary-mode"; } return ""; } sub apply_diff($$) { my $apply_files = shift; my $err_file = shift; my $command = ""; my @diffs = split( /,/, $apply_files ); if ( $#diffs < 0 ) { croak "ERROR: --apply_files must be set.\n"; } foreach my $file (@diffs) { if ( !-f $file ) { croak "ERROR: $file not found!\n"; } } if ( $opt{handle_raw_binlog} ) { if ( $#diffs == 0 ) { $command = "mysqlbinlog $apply_files "; } else { my $out = "$opt{workdir}/total_binlog_for_$opt{slave_host}_$opt{slave_port}.$opt{timestamp}.binlog"; MHA::NodeUtil::drop_file_if($out); $_binlog_manager->concat_generated_binlogs( \@diffs, $out ); print "All apply target binary logs are concatinated at $out .\n"; $command = "mysqlbinlog $out "; } $command .= $_binlog_manager->get_apply_arg(); } else { $command = "cat "; foreach my $file (@diffs) { $command .= "$file "; } } return 0 if ( $opt{no_apply} ); my $binary_mode = use_binary_mode(); escape_mysql_account(); $command .= " | mysql $binary_mode --user=$_escaped_slave_user --password=$_escaped_slave_pass --host=$opt{slave_ip} --port=$opt{slave_port} -vvv --unbuffered > $err_file 2>&1"; # applying relay log print "Applying differential binary/relay log files $apply_files on $opt{slave_host}:$opt{slave_port}. This may take long time...\n"; # applying log failed if ( my $rc = system($command) ) { my ( $high, $low ) = MHA::NodeUtil::system_rc($rc); print "FATAL: applying log files failed with rc $high:$low!\n"; printf( "Error logs from %s:%s (the last 200 lines)..\n", hostname(), $err_file ); system("tail -200 $err_file"); return $MHA::NodeConst::Applying_SQL_File_Failed; } return 0; } sub apply { unless ( $opt{apply_files} ) { croak "ERROR: --apply_files must be set.\n"; } my $date = $opt{timestamp}; unless ( $opt{timestamp} ) { my ( $year, $mon, @time ) = reverse( (localtime)[ 0 .. 5 ] ); $date = sprintf '%04d%02d%02d%02d%02d%02d', $year + 1900, $mon + 1, @time; } return apply_diff( $opt{apply_files}, "$opt{workdir}/relay_log_apply_for_$opt{slave_host}_$opt{slave_port}_$date" . "_err.log" ); } sub check_set_relay_dir_endlog { if ( $opt{relay_dir} && $opt{current_relay_log} ) { $_binlog_manager->init_from_dir_file( $opt{relay_dir}, $opt{current_relay_log} ); } elsif ( $opt{relay_log_info} ) { print " Opening $opt{relay_log_info} ..."; $_binlog_manager->init_from_relay_log_info( $opt{relay_log_info}, $opt{datadir} ); print " ok.\n"; } else { croak "ERROR: Either (--relay_dir=s, --current_relay_log=s) or (--relay_log_info=s) must be set.\n"; } print " Relay log found at $_binlog_manager->{dir}, up to $_binlog_manager->{end_log}\n"; } sub check_slave_host() { croak "--slave_host must be set.\n" unless ( $opt{slave_host} ); unless ( $opt{slave_ip} ) { $opt{slave_ip} = MHA::NodeUtil::get_ip( $opt{slave_host} ); } } sub check() { my $rc; print " Checking slave recovery environment settings..\n"; if ( $rc = system("echo 100 | md5sum > /dev/null") ) { my ( $high, $low ) = MHA::NodeUtil::system_rc($rc); croak "md5sum failed with rc $high:$low!\n"; } check_set_relay_dir_endlog(); print " Temporary relay log file is $_binlog_manager->{dir}/$_binlog_manager->{end_log}\n"; print " Testing mysql connection and privileges.."; check_slave_host(); escape_mysql_account(); if ( $rc = system( "mysql --user=$_escaped_slave_user --password=$_escaped_slave_pass --host=$opt{slave_ip} --port=$opt{slave_port} -e \"set sql_log_bin=0; create table if not exists mysql.apply_diff_relay_logs_test(id int); insert into mysql.apply_diff_relay_logs_test values(1); update mysql.apply_diff_relay_logs_test set id=id+1 where id=1; delete from mysql.apply_diff_relay_logs_test; drop table mysql.apply_diff_relay_logs_test;\"" ) ) { my ( $high, $low ) = MHA::NodeUtil::system_rc($rc); croak "mysql command failed with rc $high:$low!\n"; } print " done.\n"; print " Testing mysqlbinlog output.."; my $workfile = "$opt{workdir}/slavediff_tmp_$opt{slave_host}.log"; if ( $rc = system( "mysqlbinlog $_binlog_manager->{dir}/$_binlog_manager->{end_log} --start-position=4 --stop-position=4 > $workfile" ) ) { my ( $high, $low ) = MHA::NodeUtil::system_rc($rc); croak "mysqlbinlog failed with rc $high:$low!\n"; } print " done.\n"; print " Cleaning up test file(s).."; MHA::NodeUtil::drop_file_if($workfile); print " done.\n"; if ( !$opt{scp_user} || !$opt{scp_host} ) { return 0; } print " Testing connecting to remote slave $opt{scp_host}($opt{scp_port}) via ssh.."; my $ssh_user_host = $opt{scp_user} . '@' . $opt{scp_host}; if ( $rc = system( "ssh $MHA::NodeConst::SSH_OPT_ALIVE -p $opt{scp_port} $ssh_user_host \"exit 0 \"" ) ) { my ( $high, $low ) = MHA::NodeUtil::system_rc($rc); croak "ssh failed with rc $high:$low!\n"; } print " done.\n\n"; return 0; } sub generate_and_send { if ( $opt{command} eq "generate_and_send" ) { if ( !$opt{scp_user} || !$opt{scp_host} ) { croak "ERROR: --scp_user and --scp_host must be set.\n"; } } unless ( $opt{diff_file_readtolatest} ) { croak "ERROR: --diff_file_readtolatest= must be set.\n"; } my $gen_file_dir = dirname( $opt{diff_file_readtolatest} ); MHA::NodeUtil::create_dir_if($gen_file_dir); MHA::NodeUtil::drop_file_if( $opt{diff_file_readtolatest} ); check_set_relay_dir_endlog(); my %status = find_starting_relay_log(); if ( $status{status} == $MHA::NodeConst::Target_Has_Received_All_Relay_Logs ) { print "Target slave has received all relay logs.\n"; return 0; } croak if ( $status{status} != 0 || !$status{start_rlf} ); my $rc = do_generate( $status{start_rlf}, $status{start_rlp}, $opt{diff_file_readtolatest} ); return $rc if ( $rc || $opt{command} eq "generate" ); my $scp_user_host = $opt{scp_user} . '@' . $opt{scp_host}; if ( $rc = system( "ssh $MHA::NodeConst::SSH_OPT_ALIVE $scp_user_host -p $opt{scp_port} \"mkdir -p $gen_file_dir\"" ) ) { my ( $high, $low ) = MHA::NodeUtil::system_rc($rc); croak "ssh $scp_user_host for mkdir $gen_file_dir failed with rc $high:$low!\n"; } if ( MHA::NodeUtil::file_copy( 1, $opt{diff_file_readtolatest}, $opt{diff_file_readtolatest}, $opt{scp_user}, $opt{scp_host}, undef, $opt{scp_port} ) ) { croak "ERROR: scp %s:%s to %s(%d) failed!\n", hostname(), $opt{diff_file_readtolatest}, $scp_user_host, $opt{scp_port}; } else { printf " scp %s:%s to %s(%d) succeeded.\n", hostname(), $opt{diff_file_readtolatest}, $scp_user_host, $opt{scp_port}; } return 0; } sub main() { my $exit_code = 1; eval { MHA::NodeUtil::check_manager_version( $opt{manager_version} ) if ( $opt{manager_version} ); $_binlog_manager = new MHA::BinlogManager( handle_raw_binlog => $opt{handle_raw_binlog}, disable_log_bin => $opt{disable_log_bin}, mysql_version => $opt{target_version}, debug => $opt{debug}, ); if (!$opt{handle_raw_binlog} || $opt{command} eq "test" || $opt{command} eq "apply" ) { croak "--target_version= must be set.\n" unless ( $opt{target_version} ); $_binlog_manager->init_mysqlbinlog(); } MHA::NodeUtil::create_dir_if( $opt{workdir} ); if ( $opt{command} eq "test" ) { croak if ( check() ); } elsif ( $opt{command} eq "generate_and_send" || $opt{command} eq "generate" ) { croak if ( generate_and_send() ); } elsif ( $opt{command} eq "find" ) { $_find_logname_only = 1; check_set_relay_dir_endlog(); my %status = find_starting_relay_log(); croak if ( $status{status} != 0 || !$status{start_rlf} ); print "Target relay log FOUND!\n"; } elsif ( $opt{command} eq "apply" ) { check_slave_host(); $exit_code = apply(); croak if ($exit_code); print "Applying log files succeeded.\n"; } else { croak "Invalid command $opt{command}. Either [test|find|generate|generate_and_send|apply] command must be set.\n"; } $exit_code = 0; }; if ($@) { warn $@; } return $exit_code; } # ############################################################################ # Documentation # ############################################################################ =pod =head1 NAME apply_diff_relay_logs - Generating differential relay logs between the latest slave and target slave, and applying all binlog/relay log files. This command is automatically executed from MHA Manager on failover, and manual execution should not be needed normally. =head1 SYNOPSIS # For checking apply_diff_relay_logs --command=test --target_version=5.1.56 --relay_log_info=s --slave_user=s --slave_host=s --slave_ip=s --slave_port=i --workdir=s # For generating differential log events apply_diff_relay_logs --command=generate_and_send --target_version=5.1.56 --scp_user=s --scp_host=s --latest_mlf=s --target_mlf=s --target_rmlp=i --relay_log_info=s --server_id=i --diff_file_readtolatest=s --target_version=s --workdir=s --timestamp=s # For applying log files apply_diff_relay_logs --command=apply --target_version=5.1.56 --slave_user=s --slave_host=s --slave_ip=s --slave_port=i --apply_files=file1,file2.. --workdir=s --timestamp=s --slave_pass=xxx mha4mysql-node-0.54/bin/purge_relay_logs0000755000000000000000000001635112056326631017054 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use strict; use warnings FATAL => 'all'; use Carp qw(croak); use English qw(-no_match_vars); use Getopt::Long; use Pod::Usage; use File::Basename; use Sys::Hostname; use MHA::BinlogManager; use MHA::SlaveUtil; use MHA::NodeUtil; use MHA::NodeConst; use DBI; GetOptions( \my %opt, qw/ help version workdir=s relay_log_info=s user=s password=s host=s port=i disable_relay_log_purge /, ) or pod2usage(1); $opt{workdir} ||= "/var/tmp"; $opt{user} ||= "root"; $opt{password} ||= ""; $opt{host} ||= "127.0.0.1"; $opt{port} ||= 3306; $| = 1; my $_binlog_manager; my $_relay_log_info_path = $opt{relay_log_info}; if ( $opt{help} ) { pod2usage(0); } if ( $opt{version} ) { print "purge_relay_logs version $MHA::NodeConst::VERSION.\n"; exit 0; } exit &main(); sub hardlink_relay_logs($) { my $current_relay_log = shift; my $relay_dir = $_binlog_manager->{dir}; my $archive_upto = MHA::BinlogManager::get_prev_number_from_file($current_relay_log); print(" Current relay log file: $relay_dir/$current_relay_log\n"); print(" Archiving unused relay log files " . "(up to $relay_dir/$_binlog_manager->{prefix}.$archive_upto) ...\n" ); my @files = MHA::BinlogManager::get_all_binlogs_from_prefix( $_binlog_manager->{prefix}, $relay_dir ); my $archived_num = 0; foreach my $relay_log_basename (@files) { my ( $a, $relay_log_number ) = MHA::BinlogManager::get_head_and_number($relay_log_basename); if ( $relay_log_number > $archive_upto ) { last; } print( " Creating hard link for $relay_dir/$relay_log_basename under $opt{workdir}/$relay_log_basename .." ); croak if system( "ln $relay_dir/$relay_log_basename $opt{workdir}/$relay_log_basename"); print(" ok.\n"); $archived_num++; } if ( $archived_num == 0 ) { print " Old relay logs not found. No need to archive right now.\n"; return 0; } print(" Creating hard links for unused relay log files completed.\n"); return 0; } sub remove_hardlinked_relay_logs() { print(" Removing hard linked relay log files $_binlog_manager->{prefix}* " . "under $opt{workdir}.." ); croak if system( "find $opt{workdir} -maxdepth 1 -type f -name '$_binlog_manager->{prefix}*' | xargs rm -f" ); print(" done.\n"); } sub check_local { return if ( $opt{host} eq "127.0.0.1" ); return if ( $opt{host} =~ m/localhost/ ); my $my_host = hostname(); return if ( $opt{host} eq $my_host ); my $target_addr = MHA::NodeUtil::get_ip( $opt{host} ); my @ifconfig_result = `/sbin/ifconfig -a`; my %addrs; for (@ifconfig_result) { if (/\s*inet addr:([\d.]+)/) { $addrs{$1} = 1; } } if ( !exists( $addrs{$target_addr} ) ) { croak "--host($opt{host}) must be local address (localhost, 127.0.0.1, etc)!\n"; } } sub save_error_log { my $dbh = shift; if ( !MHA::NodeUtil::mysql_version_ge( MHA::SlaveUtil::get_version($dbh), "5.1.51" ) ) { my $log_error_path = MHA::SlaveUtil::get_log_error_file($dbh); my $dir = dirname($log_error_path); my $file = basename($log_error_path); `cat "$dir/$file-old" >> "$dir/$file-saved"` if ( -f "$dir/$file-old" ); } } sub main { my $exit_code = 1; eval { check_local(); my $start = MHA::NodeUtil::current_time(); print "$start: purge_relay_logs script started.\n"; $_binlog_manager = new MHA::BinlogManager(); my $dsn = "DBI:mysql:;host=$opt{host};port=$opt{port}"; my $dbh = DBI->connect( $dsn, $opt{user}, $opt{password}, { PrintError => 0, RaiseError => 1 } ); croak " Failed to get DB Handle on $opt{host}!\n" unless ($dbh); croak " Target mysql server is not defined as replication slave.\n" if ( !MHA::SlaveUtil::is_slave($dbh) ); if ( MHA::SlaveUtil::is_relay_log_purge($dbh) ) { if ( $opt{disable_relay_log_purge} ) { print " relay_log_purge is enabled. Disabling..\n"; MHA::SlaveUtil::disable_relay_log_purge($dbh); } else { print " relay_log_purge is enabled. Exit.\n"; exit 0; } } my ( $relay_dir, $current_relay_log ); if ( MHA::SlaveUtil::get_relay_log_info_type($dbh) eq "TABLE" ) { ( $relay_dir, $current_relay_log ) = MHA::SlaveUtil::get_relay_dir_file_from_table($dbh); if ( !$relay_dir || !$current_relay_log ) { croak "Getting relay log directory or current relay logfile from replication table failed!\n"; } $_binlog_manager->init_from_dir_file( $relay_dir, $current_relay_log ); } else { $_relay_log_info_path = MHA::SlaveUtil::get_relay_log_info_path($dbh) unless ($_relay_log_info_path); unless ($_relay_log_info_path) { croak " Failed to get relay_log_info file path!\n"; } if ( !-f $_relay_log_info_path ) { croak " $_relay_log_info_path does NOT exist.\n"; } else { print " Found relay_log.info: $_relay_log_info_path\n"; } $_binlog_manager->init_from_relay_log_info($_relay_log_info_path); $current_relay_log = $_binlog_manager->{cur_log}; } remove_hardlinked_relay_logs(); croak if ( hardlink_relay_logs($current_relay_log) ); if ( MHA::SlaveUtil::get_failover_advisory_lock( $dbh, 200 ) ) { croak " Getting advisory lock failed. Maybe failover script is running?\n"; } save_error_log($dbh); print " Executing SET GLOBAL relay_log_purge=1; FLUSH LOGS; sleeping a few seconds so that SQL thread can delete older relay log files (if it keeps up); SET GLOBAL relay_log_purge=0; .."; MHA::SlaveUtil::purge_relay_logs($dbh); print " ok.\n"; MHA::SlaveUtil::release_failover_advisory_lock($dbh); remove_hardlinked_relay_logs(); my $end = MHA::NodeUtil::current_time(); printf("$end: All relay log purging operations succeeded.\n"); $exit_code = 0; }; if ($@) { warn $@; } return $exit_code; } # ############################################################################ # Documentation # ############################################################################ =pod =head1 NAME purge_relay_logs - Deleting relay logs without blocking SQL threads =head1 SYNOPSIS purge_relay_logs --user=root --password=rootpass --host=127.0.0.1 See online reference (http://code.google.com/p/mysql-master-ha/wiki/Requirements#purge_relay_logs_script) for details. =head1 DESCRIPTION See online reference (http://code.google.com/p/mysql-master-ha/wiki/Requirements#purge_relay_logs_script) for details. mha4mysql-node-0.54/bin/filter_mysqlbinlog0000755000000000000000000001130712056326630017412 0ustar rootroot#!/usr/bin/env perl # Copyright (C) 2011 DeNA Co.,Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA use strict; use warnings FATAL => 'all'; use English qw(-no_match_vars); use Getopt::Long; use Pod::Usage; use MHA::NodeConst; GetOptions( \my %opt, qw/ help version /, ) or pod2usage(1); if ( $opt{help} ) { pod2usage(0); } if ( $opt{version} ) { print "filter_mysqlbinlog version $MHA::NodeConst::VERSION.\n"; exit 0; } my $line; my @rows_buf = (); my $parsed_events = 0; sub read_line() { if ( $line = ) { push @rows_buf, $line; return $line; } else { return; } } sub print_rows() { foreach (@rows_buf) { print $_; } @rows_buf = (); return 0; } while ( $line = read_line() ) { if ( $line =~ m/^# at \d+\n$/ ) { $parsed_events++; do { read_line(); } while ( ( $line =~ m/^# at \d+\n$/ ) && !print_rows() ); # Remove ROLLBACK statement and equivalent BINLOG statement in a START event. # START event should show up at the beginning of the binary/relay logs, # so ignore it if enough binlog events are already parsed. if ( $line =~ m/^#.*?Start: binlog v.*?created.*\n$/ && $parsed_events < 10 ) { read_line(); if ( $line =~ m/^# Warning: this binlog .*\n$/ ) { read_line(); } if ( $line =~ m/^ROLLBACK.*\n$/ ) { pop @rows_buf; push @rows_buf, "# ROLLBACK and BINLOG events generated by start_event were trimmed.\n"; read_line(); while ( !( $line =~ m/(^# at \d+\n$)|(^DELIMITER ;\n$)/ ) ) { pop @rows_buf; read_line(); } } } print_rows(); } # Trim a tail ROLLBACK statement. mysqlbinlog adds the following statements # at the tail of the output, if neither --disable-log-bin nor --set-charset # was set. # # End of log file # ROLLBACK /* added by mysqlbinlog */; # /*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/; elsif ( $line =~ m/^# End of log file\n$/ ) { read_line(); if ( $line =~ m/^ROLLBACK \/\* added by mysqlbinlog \*\/;\n$/ ) { read_line(); if ( $line =~ m/^\/\*!50003 SET COMPLETION_TYPE=\@OLD_COMPLETION_TYPE\*\/;\n$/ ) { if ( !read_line() ) { pop @rows_buf; pop @rows_buf; push @rows_buf, "# Tail ROLLBACK event generated by mysqlbinlog was trimmed.\n"; goto EOF; } } } print_rows(); } else { print_rows(); } } EOF: print_rows(); exit 0; # ############################################################################ # Documentation # ############################################################################ =pod =head1 NAME filter_mysqlbinlog - Trimming ROLLBACK statements and equivalent BINLOG events added by mysqlbinlog. This script is now obsolete. =head1 SYNOPSIS mysqlbinlog binary_or_relay_log_file | filter_mysqlbinlog Note that this script is now obsolete and not used by MHA by default. =head1 DESCRIPTION mysqlbinlog command provided by Oracle implicitly adds ROLLBACK statements and equivalent BINLOG events. But this causes problems when recovering slave servers. To recover slaves, MHA might need to apply the following binlog events. 1) Relay log events from Relay_Log_Pos to the end of the relay log file 2) Differential relay log events from the latest slave 3) Differential binary log events from the dead master mysqlbinlog command needs to be executed on these files separately. If a transaction does not end by 1) or 2), implicit ROLLBACK event rolls back the transaction, which will result in inconsistency. filter_mysqlbinlog is a tool to fix this issue. Note that ROLLBACK statements themselves are added in usual situations. For example, when you execute 1. BEGIN; 2. Updating transactional tables 3. Updating non-transactional tables 4. ROLLBACK, a ROLLBACK statement is written to the binary log to rollback transactional queries. This is normal situation so filter_mysqlbinlog must not remove all ROLLBACK events. Note that this script is now obsolete and not used by MHA by default. mha4mysql-node-0.54/COPYING0000644000000000000000000004310311770663665014057 0ustar rootroot GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.