#!/usr/bin/perl
# Get ve_ip by ve_id

# /usr/local/src/sitebuilder3/src/utils/vps_get_ve_ip.pl --service_ve_ip=10.58.21.1 --vps_id=132

# Output packet

#<packet time="2006-09-28T09:41:15+0000" priority="0" version="2.6.0">
#<origin>vem</origin>
#<target>vzclient119</target>
#<dst>
#<director>servd</director>
#</dst>
#<data>
#<vem>
#<ve>
#<veid>132</veid>
#<config>
#<ip>10.58.21.132</ip>
#</config>
#</ve>
#</vem>
#</data>
#<auth>
#<ve_list>
#<veid>132</veid>
#</ve_list>
#</auth>
#<src>
#<director>opd</director>
#</src>
#</packet>

use IO::Handle;

my $arg = join(' ',@ARGV);

my @opts 		= map { [ split(/\=/,$_) ] } @ARGV;
my $ve_id 		= undef;
my $sve_ip 		= undef;

foreach my $opt (@opts) {
	$ve_id = $opt->[1] if $opt->[0] eq '--vps_id';
	$sve_ip = $opt->[1] if $opt->[0] eq '--service_ve_ip';
}

my $pkg_for_get_ve_ip = <<PACKET;
<packet version="2.6.0">
<target>vem</target>
<data>
	<vem>
		<ve_info>
			<veid>%%VEID%%</veid>
			<config>
				<ip/>
			</config>
		</ve_info>
	</vem>
</data>
</packet>
PACKET

#Get ve_ip by ve_id
sub get_ve_ip () {
	my $result = 0;
	my ($rd, $wr, $pid) = &vza_ssh_connect(
		"/usr/bin/ssh",
		"-oPasswordAuthentication=no",
		"-oProtocol=1",
		"-lvzagent0",
		"-T",
		"-oStrictHostKeyChecking=no",
		"-oConnectionAttempts=1",
		$sve_ip);
	my $resp = &recv_packet($rd);
	$result = &check_ok($resp);
	if ($result) {
		my $packet = undef;
		$packet = $pkg_for_get_ve_ip;
		$packet =~ s/\%\%VEID\%\%/$ve_id/g;
		&send_packet($wr,$packet);
		$resp = &recv_packet($rd);
		print $resp;
	}
}

sub check_ok {
	my $resp = shift;
	return ($resp && $resp =~ /\<ok\/\>/m) ? 1 : 0;
}

sub vza_ssh_connect {
	my ($rd, $wr);
	my $rd_ssh = undef; my $wr_ssh = undef;

	&exit_error("failed to connect to VZAgent")
	    unless (pipe ($rd, $wr_ssh) && pipe ($rd_ssh, $wr));

	$rd->autoflush(1);
	$wr->autoflush(1);
	$rd_ssh->autoflush(1);
	$wr_ssh->autoflush(1);

	my $pid = fork();
	&exit_error("fork failed")
	    unless defined($pid);

	if (!$pid)
	{
		# Ssh channel
		close($rd); close($wr);

		close(STDOUT); open(STDOUT, ">&".fileno($wr_ssh));
		close(STDIN); open(STDIN, "<&".fileno($rd_ssh));

		exec(@_);
		exit(1);
	}

	# Main program
	close($wr_ssh);
	close($rd_ssh);
	return ($rd,$wr,$pid);
}

sub send_packet {
	my $wr = shift;
	my $packet = shift;
	# warn("Send:");
	# warn($packet);
	my $bytes = syswrite($wr,$packet."\0",length($packet)+1);
	return $bytes;
}

sub recv_packet {
	my $rd = shift;
	my $buf = undef;

	my $old_sep = $/;
	$/ = "\0";

	while(<$rd>) {
		$buf = $_;
		# warn("Rec:");
		# warn($buf);
		chomp($buf);
		length($buf) ? last : next;
	}
	$/ = $old_sep;
	return $buf;
}

get_ve_ip();

#kill 9,$pid;
#waitpid($pid,0);
exit(0);