#!/bin/perl
# **********************************************************************
#
# Copyright (c) 2000 
# Object Oriented Concepts, Inc.
# Billerica, MA, USA
#
# All Rights Reserved
#
# **********************************************************************

package TestSuiteUtilities;

use strict;
use Exporter;
use FileHandle;
use IO::Socket;
use File::Spec;

if($^O eq "MSWin32")
{
    require Win32::Process;
    'Win32::Process'
}

use vars qw($received_events
	    $validate_results
	    @reception_times 
	    $top_src_dir 
	    $admin_tool 
	    $admin_args 
	    $push_client_tool 
	    $push_client_args 
	    $pull_client_tool 
	    $pull_client_args 
	    $push_server_tool  
	    $push_server_args 
	    $pull_server_tool 
	    $pull_server_args 
	    $typed_push_client_tool 
	    $typed_push_client_args 
	    $typed_push_server_tool  
	    $typed_push_server_args 
	    $service 
	    $service_args 
	    $typed_service_args 
	    $received
	    $expected
	    $existingService
	    $base_port
	    @ISA 
	    @EXPORT);

@ISA = qw(Exporter);

@EXPORT = qw(&obtainChannel
             &obtainConsumerAdmin 
	     &obtainSupplierAdmin 
             &obtainPushConsumer 
	     &obtainPushSupplier 
	     &obtainPullConsumer
             &obtainPullSupplier 
	     &obtainTypedChannel
             &obtainTypedConsumerAdmin 
	     &obtainTypedSupplierAdmin 
             &obtainTypedPushConsumer 
	     &obtainTypedPushSupplier 
	     
	     &makeConnected
	     &makeConnectedTyped
	     &sendEvents 
	     &sendTypedEvents 
	     &receiveEvents  
	     &receiveTypedEvents  
	     &verifyOutput 
	     &printErrorMessage

	     &initializeTools
	     &startService 
	     &startTypedService 
	     &shutdownService 
	     &shutdownTypedService 
	    
	     &useExistingService
	     &useOwnService);

############################################################################
#
# Private helper methods.
#
############################################################################

#
# Timestamps must be stripped before handing an event list to this function.
# 
sub formatEventStr($)
{
    my $event_str = shift;	# The string describing all the events.
    my @events;			# Each event from $event_str.
    my $event;			# A single event from @events.
    my @event_data;		# The components of a single event.
    my $formatted_event_str;	# The "sorted" event string.
    my %hash;			# a hash to do the sorting with.
    my $nvpair;			# a name value pair.

    #
    # Get individual events by splitting on whitespace.
    #
    @events = split (/\s/, $event_str);

    #
    # For each event remove whitespace from the name value pairs 
    # (except Data) and then place them in the formatted event string 
    # in a standard order.
    #
    foreach $event (@events)
    {
        @event_data = split(/,/, $event);

	foreach $nvpair (@event_data)
	{
	    $nvpair =~ s/^\s*(\w)\s*/$1/;
	    if($nvpair !~ m/^Data/)
	    {
	        $nvpair =~ s/\s//g;
	    }
	    my($name,$value) = split(/=/,$nvpair);
	    $hash{$name} = $value;
	}
	@_ = sort keys %hash;
	if(($event eq  "Disconnect") || ($event eq  "auto"))
	{
	    $formatted_event_str .= $event . ",";
        }
        else
	{
	    foreach $_ (@_)
	    {
		$formatted_event_str .= $_ . "=" . $hash{$_} . ",";
	    }
	}

	#
	# Replace last comma with a space.
	#
	chop $formatted_event_str;
	$formatted_event_str .= " ";
    }
    return $formatted_event_str;
}

#
# Strips the timestamps off of events and places them in @reception_times.
# Then returns the stripped event list
#
sub stripTimestamps($)
{
    my $event_list = shift;
    my @events;
    my $event;
    my $stripped_event_list;

    #
    # Empty the reception times array.
    #
    @reception_times = ();

    @events = split(/\s/, $event_list);
    foreach $event (@events)
    {

	#
	# Get the timestamp from the front of the event.
	#
	$_ = $event;
	s/(\d*)::.*/$1/;
	push(@reception_times,$1);

	#
	# Now remove the timestamp from the event and add the event to 
	#stripped_event_list
	#
	$_ = $event;
	s/\d*::(.*)/$1/;
	$stripped_event_list .= $_ ." ";
    }
    return $stripped_event_list
}

#
# Verify that the start times of the received events are before the 
# reception times.
#
sub verifyStartTimes($)
{
    my $event_list = shift;
    my @events = split(/\s/, $event_list);
    my @start_times;
    my $number_of_events = @events;
    my $number_of_times;
    my $event;
    
    for(my $i = 0 ; $i < $number_of_events ; $i++)
    {
	$_ = @events[$i];
	if(/.*StartTime=.*/)
        {
	    s/.*StartTime=(\d*).*/$1/;
	    push(@start_times,$1);
	}
    }

    $number_of_times = @start_times;
    for(my $j = 0 ; $j < $number_of_times ; $j++)
    {
	if($reception_times[$j] lt $start_times[$j])
	{
	    return 0;
	}
    }
    return 1;
}

#
# Run the given process in another thread
#
sub forkService($)
{
    if($^O eq "MSWin32") 
    {
	my $process;
	my $app = shift;
	my $cmdline;
	while ($_ = shift)
	{
	    if($_ ne "") { $cmdline .= $_; }
	    else { last; }
	    
	}
	
	Win32::Process::Create($process, $app, $cmdline, 0, 0, ".") or 
	    die print Win32::FormatMessage( Win32::GetLastError() );

	return $process;
    }
    else
    {
	my $pid = fork;
	my $command = shift or die "forksys called with no arguments";
	my $args = shift;
	if(!defined($pid)) { die $! }

	if($pid) { return $pid }
	exec($command . $args);
	exit 0;
    }
}

#
# Extract the events to send from the given data file. 
#
sub getEvents($)
{
    my $data_file = shift;
    my $event_str;
    
    #
    # Read the events from the data file.
    #
    open(IN, $data_file) or 
        die ("Error:  Can't open required datafile: $data_file");

    while(<IN>) 
    { 
        if(/^in:/) { last; } 
    }

    while(<IN>)
    {
	if($_ ne "\n") { $event_str .= $_; }
	else { last; }
    }
    close(IN);
    
    #
    # Sort each name value pair.
    #
    $event_str = &formatEventStr($event_str);

    return $event_str;
}

#
# Extract the events to expect to receive from the given data file. 
#
sub getExpectedEvents($)
{
    my $data_file = shift;
    my $event_str;
    
    #
    # Read the events from the data file.
    #
    open(IN, $data_file) or 
        die ("Error:  Can't open required datafile: $data_file.");

    while(<IN>)
    {
        if(/^out:/) { last; }
    }

    while(<IN>)
    {
	if($_ ne "\n") { $event_str .= $_; }
	else { last; }
    }
    
    #
    # Sort each events name value pairs into a standard order.
    #
    $event_str = &formatEventStr($event_str);
    $event_str .= "Disconnect";
    return $event_str;
}

#
# Extract the number of events from the event list.
#
sub getNumberEvents($)
{
    my $data_file = shift;
    my $num = 0;
    
    #
    # Read the number of expected events from the data file.
    #
    open(IN, $data_file) or 
        die ("Error:  Can't open required datafile: $data_file.");

    while(<IN>)
    {
        if(/^out:/) { last; }
    }

    while(<IN>)
    {
	$num = $num + 1;
    }
    return $num;
}

sub isJava()
{
    # Open ob.conf
    open(IN, "../../config/sh.init");

    while(<IN>)
    {
        if(/OB_CPP_DIST/)
        {
	    return 1;
	}
	elsif(/OB_JAVA_DIST/)
	{
	    return 0;
	}
    }
    print "Error, no distribution indicator in ../../config/sh.init\n";
    exit(1);
}

sub getJavaCommand()
{
    # Open ob.conf
    open(IN, "../../config/sh.init");

    while(<IN>)
    {
        if(/JAVA=(.*)/)
        {
	    return "$1" . ".exe";
	}
    }
    print "Error,`JAVA=` not found in ../../config/sh.init\n";
    exit(1);
}

sub getJavaPath($)
{
    my $cmd = shift;
    my $IsWin32 = $^O eq 'MSWin32';

    my $dir;
    foreach $dir (File::Spec->path)
    {
	my $scr = "$dir" . "\\$cmd";
	if (-r $scr && (!$IsWin32 || -x _))
	{
	    return $scr;
	}
    }
    print "Error: cannot find java.exe in the PATH\n";
    exit(1);
}
   

############################################################################
#
# Public methods.
#
############################################################################

sub printErrorMessage()
{
    print "\nExpected\n\t$expected\n";
    print "\nReceived\n\t$received\n";
}

#
# Tell the script to use an existing service
#
sub useExistingService
{
    $existingService = 1;
}

#
# Tell the script to use a new service
#
sub useOwnService
{
    $existingService = 0;
}

sub getBasePort()
{
    # Open ob.conf
    open(IN, "ob.conf");

    while(<IN>)
    {
        if (/ooc.testsuite.baseport=(.*)/)
        {
            $base_port = $1;
            return;
        }
    }
    #
    # Base port isn't defined so use port 9000 as a default.
    #
    $base_port = 9000;
}

#
# We have to initialize the values for these variables before they can be
# used properly.
#
sub initializeTools()
{
    &getBasePort();
    my $Config = "";

    if (isJava())
    {
	my $BOOTCLASSPATH;
        my $java;
	my $java_exec;
        $Config = "-ORBconfig ob.conf";

	if($^O eq "MSWin32")
	{
	    #
	    # Set the CLASSPATH
	    #            
	    $ENV{"CLASSPATH"}="../../ob/lib;../lib;classes;\$CLASSPATH";

	    $java_exec = getJavaCommand();
	    $java = getJavaPath($java_exec); 
	    
	    #
	    # Workaround for JDK 1.3
	    #
	    my $java_version = `$java -version 2>&1`;
	    if($java_version =~ /1\.3/)
	    {
		$BOOTCLASSPATH = "-Xbootclasspath/p:../../ob/lib";
	    }

	    $service = $java;
	    $service_args = "$java_exec $BOOTCLASSPATH " .
	    		    "com.ooc.CosEventServer.Server $Config -u";
	    $typed_service_args = "$java_exec $BOOTCLASSPATH " .
	    			  "com.ooc.CosEventServer.Server $Config -t";
	}
	else 
	{
	    #
	    # Set the CLASSPATH
	    #            
	    $ENV{"CLASSPATH"}="../../ob/lib:../lib:classes:\$CLASSPATH";

	    $java = "java"; 
	    
	    #
	    # Workaround for JDK 1.3
	    #
	    my $java_version = `$java -version 2>&1`;
	    if($java_version =~ /1\.3/)
	    {
		$BOOTCLASSPATH = "-Xbootclasspath/p:../../ob/lib";
	    }

	    $service = "java $BOOTCLASSPATH com.ooc.CosEventServer.Server";
	    $service_args = " $Config -u";
	    $typed_service_args = " $Config -t";
	}

        $admin_tool = "$java event.Admin";
        $push_client_tool = "$java event.PushEventClient";
        $pull_client_tool = "$java event.PullEventClient";
        $push_server_tool = "$java event.PushEventServer";
        $pull_server_tool = "$java event.PullEventServer";
        $typed_push_server_tool = "$java event.TypedPushEventServer";
        $typed_push_client_tool = "$java event.TypedPushEventClient";
    }
    else
    {
        if($existingService == 0)
        {
            $ENV{"ORBACUS_CONFIG"}="ob.conf";
            $Config = "-ORBconfig ob.conf";
        }

        my $top_src_dir = "..";

        my $EXE = "";
        if($^O eq "MSWin32")
        {
            $EXE = ".exe";
        }

        $admin_tool = "$top_src_dir/test/admin$EXE";
        $push_client_tool = "$top_src_dir/test/pusheventclient$EXE";
        $pull_client_tool = "$top_src_dir/test/pulleventclient$EXE";
        $push_server_tool = "$top_src_dir/test/pusheventserver$EXE";
        $pull_server_tool = "$top_src_dir/test/pulleventserver$EXE";
        $typed_push_server_tool = "$top_src_dir/test/typedpusheventserver$EXE";
        $typed_push_client_tool = "$top_src_dir/test/typedpusheventclient$EXE";

        $service = "$top_src_dir/bin/eventserv$EXE";
        $service_args = "";
        $typed_service_args = " -t";
    }

    $admin_args = " $Config";
    $push_client_args = " $Config";
    $pull_client_args = " -ORBthreaded -OAthread_per_request $Config";
    $push_server_args = " $Config";
    $pull_server_args = " $Config";
    $typed_push_server_args = " -ORBthreaded $Config";
    $typed_push_client_args = " -ORBthreaded -OAthread_per_request $Config"; 
}
   
 
sub obtainChannel($)
{
    my $creation_message = `$admin_tool $admin_args CreateChannel`;
    chomp $creation_message;
    
    if($creation_message eq undef())
    {
	print "\n\nChannel is undefined upon creation!\n";
 	return "-1";	
    }
    elsif($creation_message =~ /.*ERROR.*/)
    {
	print "\n\n$creation_message\n";
 	return "-1";	
    }
    else
    {
	chomp $creation_message;
	return $creation_message;
    }
}

sub obtainTypedChannel($)
{
    my $creation_message = `$admin_tool $admin_args CreateTypedChannel`;
    chomp $creation_message;
    
    if($creation_message eq undef())
    {
	print "\n\nChannel is undefined upon creation!\n";
 	return "-1";	
    }
    elsif($creation_message =~ /.*ERROR.*/)
    {
	print "\n\n$creation_message\n";
 	return "-1";	
    }
    else
    {
	chomp $creation_message;
	return $creation_message;
    }
}

sub obtainConsumerAdmin($)
{
    my $channel = shift; 
    if($channel eq undef())
    {
	print "Warning:  Cannot obtain_consumer_admin without a valid " .
              "channel!\n";
        return;
    }

    my $admin = `$admin_tool $admin_args CreateConsumerAdmin $channel`;
    chomp $admin;

    if($admin =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
 	return "-1";	
    }
    return $admin;
}

sub obtainTypedConsumerAdmin($)
{
    my $channel = shift; 
    if($channel eq undef())
    {
	print "Warning:  Cannot obtain_consumer_admin without a valid " .
              "channel!\n";
        return;
    }

    my $admin = `$admin_tool $admin_args CreateTypedConsumerAdmin $channel`;
    chomp $admin;

    if($admin =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
 	return "-1";	
    }
    return $admin;
}

sub obtainSupplierAdmin($)
{
    my $channel = shift; 
    if($channel eq undef())
    {
	print "Warning:  Cannot obtain_supplier_admin without a valid " .
              "channel!\n";
        return;
    }

    my $admin = `$admin_tool $admin_args CreateSupplierAdmin $channel`;
    chomp $admin;
    
    if($admin =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
 	return "-1";	
    }
    return $admin;
}

sub obtainTypedSupplierAdmin($)
{
    my $channel = shift; 
    if($channel eq undef())
    {
	print "Warning:  Cannot obtain_supplier_admin without a valid " .
              "channel!\n";
        return;
    }

    my $admin = `$admin_tool $admin_args CreateTypedSupplierAdmin $channel`;
    chomp $admin;
	                    
    if($admin =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
 	return "-1";	
    }
    return $admin;
}

sub obtainPushConsumer($)
{
    my $admin = shift; 
    if($admin eq undef())
    {
	print "Warning:  Cannot obtain_push_consumer without a valid " .
               "Supplier Admin!\n";
        return;
    }

    my $creation_message = 
    `$admin_tool $admin_args CreatePushConsumer $admin`;
    chomp $creation_message;
    
    if($creation_message =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
	return -1;	
    }
    return $creation_message;
}

sub obtainTypedPushConsumer($)
{
    my $admin = shift; 
    my $ref = shift;
    
    if($admin eq undef())
    {
	print "Warning:  Cannot obtain_push_consumer without a valid " .
               "Supplier Admin!\n";
        return;
    }

    my $creation_message = 
    `$admin_tool $admin_args CreateTypedPushConsumer $admin $ref`;
    chomp $creation_message;
    
    if($creation_message =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
	return -1;	
    }
    return $creation_message;
}

sub obtainPullConsumer($)
{
    my $admin = shift; 
    if($admin eq undef())
    {
	print "Warning:  Cannot obtain_pull_supplier without a valid " .
               "Supplier Admin!\n";
        return;
    }

    my $creation_message = 
    `$admin_tool $admin_args CreatePullConsumer $admin`;
    chomp $creation_message;
    
    if($creation_message =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
	return -1;	
    }
    return $creation_message;
}

sub obtainPushSupplier($)
{
    my $admin = shift; 
    if($admin eq undef())
    {
	print "Warning:  Cannot obtain_push_consumer without a valid " .
               "Consumer Admin!\n";
        return;
    }

    my $creation_message = 
    `$admin_tool $admin_args CreatePushSupplier $admin`;
    chomp $creation_message;
    
    if($creation_message =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
	return -1;	
    }
    return $creation_message;
}

sub obtainTypedPushSupplier($)
{
    my $admin = shift; 
    my $ref = shift;
    
    if($admin eq undef())
    {
	print "Warning:  Cannot obtain_push_consumer without a valid " .
               "Consumer Admin!\n";
        return;
    }

    my $creation_message = 
    `$admin_tool $admin_args CreateTypedPushSupplier $admin $ref`;
    chomp $creation_message;
    
    if($creation_message =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
	return -1;	
    }
    return $creation_message;
}

sub obtainPullSupplier($)
{
    my $admin = shift; 
    if($admin eq undef())
    {
	print "Warning:  Cannot obtain_pull_consumer without a valid " .
               "Consumer Admin!\n";
        return;
    }

    my $creation_message = 
    `$admin_tool $admin_args CreatePullSupplier $admin`;
    chomp $creation_message;
    
    if($creation_message =~ /.*ERROR.*/)
    {
	print "\n\n$admin\n";
	return -1;	
    }
    return $creation_message;
}

sub makeConnected($)
{
    my $proxy = shift; 
    my $model = shift;
    my $port = shift or 0;

    $port += $base_port;	
    my $port_args = "-OAport $port";
    my $push_connect_command = "$push_client_tool $port_args " .
	                       "$push_client_args $proxy --disconnect";
    my $pull_connect_command = "$pull_client_tool $port_args " .
	                       "$pull_client_args $proxy --disconnect";
   
    if($model eq "push")
    {
    	`$push_connect_command`;
    } 
    else
    {
	`$pull_connect_command`;
    }
}

sub makeConnectedTyped($)
{
    my $proxy = shift; 
    my $port = shift or 0;
    
    $port += $base_port;	
    my $port_args = "-OAport $port";

    my $cmd = "$typed_push_client_tool $typed_push_client_args $port_args " .
              "$proxy --disconnect";
    `$cmd`;
}

sub sendEvents($)
{
    my $proxy = shift;
    my $model = shift;
    my $data_file = shift;
    my $sleeptime = 2;
    my $event_list;

    if($data_file eq "auto")
    {
	$event_list = "auto";
    }
    elsif($data_file =~ /\D/)
    {
	$event_list = getEvents($data_file);
    } 
    else
    {
	$event_list = $data_file;
    }

    if($model eq "push")
    {
        `$push_server_tool $push_server_args $proxy $event_list`;
    }
    else
    {
        `$pull_server_tool $pull_server_args $proxy $event_list`;
    }
   
    sleep($sleeptime);
}

sub sendTypedEvents($)
{
    my $proxy = shift;
    my $data_file = shift;
    my $sleeptime = 5;
    my $event_list;

    if($data_file eq "auto")
    {
	$event_list = "auto";
    }
    elsif($data_file =~ /\D/)
    {
	$event_list = getEvents($data_file);
    } 
    else
    {
	$event_list = $data_file;
    }

    `$typed_push_server_tool $typed_push_server_args $proxy $event_list`;
    sleep($sleeptime);
}

sub receiveEvents($)
{
    my $proxy = shift;
    my $model = shift;
    my $sleeptime = shift;
    my $datafile = shift;
    my $port = shift or 0;
    my $RESULTS = new FileHandle;

    $port += $base_port;	
    my $port_args = "-OAport $port";

    if($model eq "push")
    {
	my $push_receiver = "$push_client_tool $port_args " .
			     "$push_client_args $proxy";
	open($RESULTS, "$push_receiver|");
    }
    else
    {
	my $num_events;
	if($datafile eq "auto")
	{
	    $num_events = 1000000;
	}
	else
	{
	    $num_events = getNumberEvents($datafile);
	}
	my $pull_receiver = "$pull_client_tool $port_args " .
			     "$pull_client_args $proxy " .
	                     "--expect $num_events"; 
	open($RESULTS, "$pull_receiver|");
    }
   
    #
    # Wait for client to receive the events that are queued, then destroy
    # the supplier so that the service do not hang.  Must sleep for at least
    # 4 seconds to ensure events have time to be received.
    #
    if($sleeptime < 4) 
    {
	$sleeptime = 4;
    }
    sleep($sleeptime);

    `$admin_tool $admin_args DestroyProxySupplier $proxy`;

    $received_events = "";
    while(<$RESULTS>) 
    { 
	$received_events .= $_;
    }
    close $RESULTS;
}

sub receiveTypedEvents($)
{
    my $proxy = shift;
    my $sleeptime = shift;
    my $datafile = shift;
    my $port = shift or 0;
    my $RESULTS = new FileHandle;

    $port += $base_port;	
    my $port_args = "-OAport $port";
    
    my $push_receiver = "$typed_push_client_tool $port_args " . 
    			"$typed_push_client_args $proxy"; 

    open($RESULTS, "$push_receiver|");
   
    #
    # Wait for client to receive the events that are queued, then destroy
    # the supplier so that the service do not hang.  Must sleep for at least
    # 4 seconds to ensure events have time to be received.
    #
    if($sleeptime < 4) 
    {
	$sleeptime = 4;
    }
    sleep($sleeptime);

    `$admin_tool $admin_args DestroyTypedProxySupplier $proxy`;

    $received_events = "";
    while(<$RESULTS>) 
    { 
	$received_events .= $_;
    }

    close $RESULTS;
}

sub verifyOutput($)
{
    my $data_file = shift;
    my $expected_output = &getExpectedEvents($data_file);
    $received_events = &stripTimestamps($received_events);
    $received_events = &formatEventStr($received_events);
    $expected_output = &formatEventStr($expected_output);
    
   if(!(&verifyStartTimes($received_events)))
    {
	$received = "StartTimes failed!\n";
	$expected = "";
	return 0;
    }

    $received_events =~ s/,StartTime=\d*//g;
    $received_events =~ s/,StopTime=\d*//g;
    
    if($expected_output eq $received_events) 
    { 
	return 1; 
    }
    else 
    { 
	$expected = "$expected_output";
	$received = "$received_events";
	return 0; 
    }
}

sub startTypedService()
{
    if($existingService == 0)
    {
	&forkService($service, $typed_service_args); 
	&waitForService();
    }
}

sub startService()
{
    if($existingService == 0)
    {
	&forkService($service, $service_args); 
	&waitForService();
    }
}

sub shutdownService()
{
    if($existingService == 0)
    {
	`$admin_tool $admin_args Shutdown`;
	sleep(1);
    }
}
sub shutdownTypedService()
{
    if($existingService == 0)
    {
	`$admin_tool $admin_args TypedShutdown`;
	sleep(1);
    }
}

sub waitForService()
{
    #
    # Note that PeerPort must correspond to the port the service is using
    # from ob.conf in the test directory.
    #
    my $port;
    my $host;

    # Open ob.conf
    open(IN, "ob.conf");

    while(<IN>)
    {
	if(/EventChannelFactory=(.*)/)
	{
	     #
	     # This line is of the form <STRING>:<STRING>:<PORT>:<STRING>
	     #
	     my @tokens = split(":", $1);
	     $host = $tokens[2];
	     my $line = $tokens[3];
	
	     #
	     # This line is of the form <PORT>/<STRING>
	     #
	     @tokens = split("/", $line);
	     $port = $tokens[0];
	     last;
	}	
    }
    
    my $index;

    for($index = 0 ; $index < 10 ; $index++)
    {
	my $sock = new IO::Socket::INET (PeerAddr => $host, 
					 PeerPort => $port, Proto => 'tcp');
	if($sock)
	{
	    return;
	}
	sleep(1);
    }
    print "Could not connect to Event Service for 10 secs!\n";
}

