smallseo.info

poe

POE is a portable perl multitasking and networking framework for any event loop. POE: Perl Object Environment

How do I send a raw IRC message when using Bot::BasicBot

Bot::BasicBot provides a method for fetching the handle of the underlying POE::Component::IRC::State object, pocoirc(). Using this object handle, it seems like it should be possible to send a raw message like this:

sub said {
  my ($self, $message) = @_;
  $self->pocoirc()->yield('raw_events' => 1);
  $self->pocoirc()->yield('irc_raw_out' => 'RAW message');

However, this gives the error "Can't call method "yield" without a package or object reference" - the returned object doesn't seem to export the expected method. Have I misunderstood what kind of object I'm getting back, or how to trigger sending of a raw message?


Source: (StackOverflow)

Is my POE::Component::IRC Event loop stuck?

I've been tasked with writing an IRC bot which will join channels on the internal IRC system here, and post messages to channels which don't appear to be used anymore, warning any potential users that the channel is about to be retired. Our IRC system has about 6,500 channels which need these messages posted to them, and the IRC server we use (a customised fork of Hybrid) limits concurrent channel joins to 100 per connection. In an attempt not to hit this limit, the code I've got is this :

if ($channel_list->{$channel}{joined}) {
    # If we're already joined, privmsg immediately
    $logger->info("Trying to message $channel");
    $data_entry->notified('true');
    $data_entry->update;
    $irc->yield(privmsg => $msg_channel, $message);
    $irc->yield(part => $msg_channel);
} else {
    # Otherwise join, and let the join event do the privmsg and part
    $logger->info("Trying to join $channel");
    $data_entry->notified('true');
    $data_entry->update;
    $irc->yield(join => $msg_channel);
}

i.e. it will see if we're joined already, and if we are, try to post the notification message, and then immediately part. If we're not joined, it tries to join first (and the join event will fire the message sending).

The problem is the code never seems to run the

$irc->yield(part => $msg_channel);

line, as eventually I start getting irc_405 events back from the IRC server saying the code has joined too many channels. Anyone got any idea what am I doing wrong?


Source: (StackOverflow)

How do I check if a user is authenticated with NickServ using POE::Component::IRC::State in Perl?

I'm trying to test whether a user is registered on FreeNode. nick_info() doesn't seem to return information about this, so I want to use $irc->yield(whois => $nick); and then grab the irc_whois event's reply. The problem is that I want to wait until this event is fired, so I created a global variable $whois_result and wrote a sub like this:

sub whois {
    my $nick = $_[0];
    $whois_result = 0;
    $irc->yield(whois => $nick);
    while($whois_result == 0) { }
    return $whois_result;
}

with the irc_whois handler looking like:

sub on_whois {
    $whois_result = $_[ARG0];
    print "DEBUG: irc_whois fired.\n";
}

Unfortunately, the event can't fire while the loop is running so this hangs. I'm sure there's a better way to do this, but I'm not familiar enough with this kind of programming to know. Any help would be greatly appreciated.


Source: (StackOverflow)

How do I get the responses from POE::Component::Client::HTTP?

My component

  POE::Component::Client::HTTP->spawn(
        Agent     => "MyScript/1.0",
        Alias     => 'browser',
        Timeout   => 60,
        FollowRedirects => 3,
  );

This is the event handler of another POE component from where the HTTP request is sent

 sub connected {
     my ($heap,$kernel) = @_[HEAP,KERNEL];
     my $request = POST 'http://mydomain.com', [qw(hello world this is my script)];
     $kernel->post('browser','request','response',$request);
   }

 sub response {
     print "I am inside the response handler!\n"; # It never reaches here
   }

I checked my Webserver logs and the HTTP request is sent correctly but it doesn't send the HTTP::Response object (or anything) to the response handler. What did I do wrong?


Source: (StackOverflow)

Understanding name spaces in POE-Tk

I posted "How to undersand the POE-Tk use of destroy?" in an attempt to reduce the bug in my production code to a test case. But it seems that the solution to the test case is not working in the full program.

The program is 800+ lines long so I am hesitant to post it in full. I realize that the snippets I provide here may be too short to be of any use, but I hope to get some direction in either where to look for a solution or what additional information I can provide.

Here is the Session::Create section of my POE-Tk app.


POE::Session->create(
    inline_states => {
    	_start		=> \&ui_start,
    	get_zone	=> \&get_zone,
    	ping		=> \&ping,
    	mk_disable	=> \&mk_disable,
    	mk_active	=> \&mk_active,
    	pop_up_add => \&pop_up_add,
    	add_button_press => sub {
    		my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
    		print "\nadd button pressed\n\n";
    		&validate;
    	},
    	ih_button_1_press => sub {
    		my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
    		print "\nih_button_1 pressed\n\n";
    		if( Tk::Exists($heap->{ih_mw}) ) {
    			print "\n\nih_mw exists in ih_button_1_press\n\n";
    		} else {
    			print "\n\nih_mw does not exist in ih_button_1_press\n\n";
    		}
    		1;
    		$heap->{ih_mw}->destroy if Tk::Exists($heap->{ih_mw});
    		&auth;
    	},
    	pop_up_del => \&pop_up_del,
    	auth		=> \&auth,
#   	validate	=> \&validate,
    	auth_routine => \&auth_routine,
    	raise_widget	=> \&raise_widget,
    	del_action	=> \&del_action,
    	over		=> sub { exit; }
    }
);

add_button_press is called here;


sub pop_up_add {
    ...
    my $add_but_2 = $add_frm_2->Button( 
    	-text => "Add Record",
    	-command => $session->postback("add_button_press"),
    	-font => "{Arial} 12 {bold}") -> pack(
    		-anchor => 'c',
    		-pady => 6,
    	);
    ...
}

validate creates the Toplevel widget $heap->{ih_mw};


sub validate {
    ...
    if( ! $valid ) {
    	print "\n! valid entered\n\n";
    	$heap->{label_text} .= "Add record anyway?";
    	my $lt_ref = \$heap->{label_text};
    ...
    	my $heap->{ih_mw} = $heap->{add_mw}->Toplevel( -title => "ih_mw");
    ...	
    	if( Tk::Exists($heap->{ih_mw}) ) {
    		print "\n\nih_mw exists in validate\n\n";
    	} else {
    		print "\n\nih_mw does not exist in validate\n\n";
    	}
    ...
    	my $ih_but1 = $heap->{ih_mw}->Button( -text => "Add",
    		-font => 'vfont',
    		-command => $session->postback("ih_button_1_press"),
    		)->pack( -pady => 5 );
    ...
}

Pressing $ih_but1 results in this;

C:\scripts\alias\resource>alias_poe_V-3_0_par.pl

add button pressed

sub validate called

! valid entered

ih_mw exists in validate

ih_button_1 pressed

ih_mw does not exist in ih_button_1_press

So the $heap->{ih_mw} widget seems to be unkown to the ih_button_1_press anonymous subroutine even with the inclusion of "($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];"


Source: (StackOverflow)

Perl POE::Wheel::FollowTail running in a thread not modifying global variables

In this program POE::Wheel::FollowTail works well for following the tail of a file, it is also running in a separate thread to simply monitor the progress of a compile job.
Inside the InputEvent handler there's a crude regex to extract compile results, and there everything is working fine, but I cannot get any result values to be accessible outside this sub. Even if I put result variables in the global scope they are not modified.

The program consists of one process running the compile job, another watching the log, and the main loop waiting.

Global scope:

my $Pass = 0;
my $Done = 0;

Then to kick off the monitoring:

threads->create(\&StartWatcher);

Where the watch-log file sub looks like this:

sub StartWatcher
{
my $logfile = "filename.log";

# Create the logfile watcher
POE::Session->create
    (
    inline_states => 
        {
        _start => sub 
            {
            $_[HEAP]{tailor} = POE::Wheel::FollowTail->new( Filename => $logfile, InputEvent => "got_log_line", );
            },
        got_log_line => sub 
            {
            $Pass += () = $_[ARG0] =~ /^\d+.*vcproj \- 0 error\(s\), \d+ warning\(s\)/g;
            $Done += () = $_[ARG0] =~ /^\d+.*vcproj \- \d+ error\(s\), \d+ warning\(s\)/g;
            print "POE InputEvent Pass: $Pass, Done: $Done\n"; # Debug output
            },
        }
    );

POE::Kernel->run();
}

The $logfile is being written by a Visual Studio compile job started using Win32::Process::Create and the main Perl execution is sitting in this loop waiting for the compiler to terminate, and producing a status output every second.

    while('true')
    {
    $ProcessObj->Wait(100);  # milliseconds wait
    $ProcessObj->GetExitCode($exitcode);
    if ( $exitcode == STILL_ACTIVE ) 
        {
        "Compiling... [$Done/$Count]  Pass: $Pass  Failed: $failed" 
            if($RunCounter++ % 10 == 0);
        next;
        }
    last;
    }

The output produced is similar to this:

POE InputEvent Pass: 1, Done: 1
Compiling... [0/91]  Pass: 0  Failed: 0                           

ie. in the InputEvent handler got_log_line the two global variables have been incremented, yet in the Perl main loop they are still at zero. I realise that I could do the print output from the InputEvent handler but why doesn't it modify global variables?

What is going wrong?


Source: (StackOverflow)

POE complains that POE::Kernel's run method was never called when I fork

This is my code:

 if ($DAEMON) {
                my $pid = fork();
                if (not defined $pid) {
                                        print "Unable to start daemon.\n";
                                        exit(1);
                                      }
                elsif ($pid == 0) {
                                   open STDOUT, '>', '/dev/null';
                                   open STDERR, '>', '/dev/null';
                                   _create_sessions($self, $settings);
                                   $poe_kernel->run;
                                  }
                else { print "Script forked to background with PID $pid\n"; }
              }
 else {
        _create_sessions($self, $settings);
        $poe_kernel->run;
      }

When $DAEMON = 1, it complains that POE::Kernel's run() method was never called, but as you can see in the above code, I did that already. The script works perfectly fine when in daemon mode, but I can't get rid of that warning or understand why it says that. I also tried calling $poe_kernel->has_forked() and that didn't make a difference either.

I'm out of ideas. Any suggestions?

Updated to add: Maybe I wasn't clear enough. The code below creates the session and runs the kernel.

_create_sessions($self, $settings);
$poe_kernel->run;

It works perfectly fine. It's only when the same code is run inside a fork'd child so I can send the script to the background, that it says POE::Kernel's run method wasn't called. The script does go into the background and works like it should which means the kernel is indeed running. I'm only looking to get rid of that annoying warning.


Source: (StackOverflow)

monitoring an exe applicaion launching

I need to monitor an console exe application which don't have any stdin from the user it only print some info to the screen i used a POE:Wheel for this task

Below are my code:

use POE qw( Wheel::Run);

    POE::Session->create(
      inline_states => {
         _start => sub {
            my ($heap) = $_[HEAP];

            my $run    = POE::Wheel::Run->new(
                Program      => "my_program.exe",
                StdoutEvent  => "print"
            );


            $heap->{run}  = $run   ;

         },

         print => sub {print "somthing";}
      }
    );
$poe_kernel->run(  );

When i run the above code/script and run the my_program.exe i didn't see any print on the screen could someone tell what could be my problem here .


Source: (StackOverflow)

Dancer : how to share data and waiting response between 2 POST without blocking

I have a server written in on a VM, this is the workflow :

  • customers POST some stuff in /post_wait route : the POST should waiting the business processing to return the result
  • the request is processed by another VMs (communication is processed by POE + IKC)
  • the report should be returned by /report route to the customer identified with the session id by the REST server

DANCER CODE : (that's what I tried so far)

package var;
use Data::Dumper;
use Dancer ':syntax';
use JSON::XS;

my $session = {};

# curl -H 'Content-Type: application/json' -X POST -d '{"id":22}' http://127.0.0.1:3000/post_wait
post '/post_wait' => sub {
    my $json = request->body;
    my $h = decode_json $json;
    my $id = $h->{id};
    until (exists $session->{$id}->{report}) {
        sleep 1;
        print STDERR ".";
    }

    return Dumper $session;
};

# curl -H 'Content-Type: application/json' -X POST -d '{"foobar":"xxxx"}' http://127.0.0.1:3000/report
post '/report' => sub {
    my $json = request->body;
    my $h = decode_json $json;
    my $id = $h->{id};
    $session->{$id}->{report} = $h;
    return "OK\n";
};

true;

The problem is that this code hangs, because I sleep the parent process.

Maybe I should use :

My information system should be scalable and in mode.

What is the best practice to do what I want ?


Source: (StackOverflow)

How to undersand the POE-Tk use of destroy?

Here is some test code to illustrate my problem;


use Tk;
use POE qw( Loop::TkActiveState );
use Tk::Toplevel;

POE::Session->create(
    inline_states => {
    	_start		=> \&ui_start
    	,top1		=> \&top1
    	,top2		=> \&top2
#   	,kill_top1	=> \&kill_top1
    	,kill_top1	=> 	sub {
    		$heap->{tl1}->destroy;
    	}
    	,over		=> sub { exit }
    }
);

$poe_kernel->run();
exit 0;

sub ui_start {
    my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
    $heap->{mw} = $poe_main_window;
    $but1 = $heap->{mw}->Button(
        -text => 'Exit',
        -width => 12,
        -command => $session->postback("over")
    )->pack( -padx => 7,
    	-side => 'left',
    	-expand => 0 );

    $but2 = $heap->{mw}->Button(
        -text => 'Top1',
        -width => 12,
        -command => $session->postback("top1")
    )->pack( -padx => 7,
    	-side => 'left',
    	-expand => 0 );
    $but2 = $heap->{mw}->Button(
        -text => 'Top2',
        -width => 12,
        -command => $session->postback("top2")
    )->pack( -padx => 7,
    	-side => 'left',
    	-expand => 0 );
    $but3 = $heap->{mw}->Button(
        -text => 'Kill TL',
        -width => 12,
        -command => $session->postback("kill_top1")
    )->pack( -padx => 7,
    	-side => 'left',
    	-expand => 0 );
}

sub top1 {
    my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
    unless(Tk::Exists($heap->{tl1})) {
    	$heap->{tl1} = $heap->{mw}->Toplevel( title => "Top1");
    }
}   

sub top2 {
    my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
    $heap->{tl2} = $heap->{mw}->Toplevel( title => "Top2");
    $heap->{tl1}->destroy if Tk::Exists($heap->{tl1});
}   

sub kill_top1 {
    my ($kernel, $session, $heap) = @_[KERNEL, SESSION, HEAP];
    $heap->{tl1}->destroy if Tk::Exists($heap->{tl1});
}

If I uncomment the version of the inline state kill_top1, all is well. If I use the version (as shown) that calls the anonymous sub, I get;


C:\scripts\alias\resource>alias_poe_V-3_0_par.pl
 error:Can't call method "destroy" on an undefined value at C:\scripts\alias\res
ource\alias_poe_V-3_0_par.pl line 328,  line 365.

Tk::Error: Can't call method "destroy" on an undefined value at C:\scripts\alias
\resource\alias_poe_V-3_0_par.pl line 328,  line 365.
 Tk::After::once at C:/Perl/site/lib/Tk/After.pm line 89
 [once,[{},undef,100,once,[\&POE::Kernel::_poll_for_io]]]
 ("after" script)

In this posting [link text][1] Rocco Caputo explains;

"Tk is not passing the event information to POE.

As you know, postbacks are anonymous subroutine references that post POE events when they're called. They're used as a thin, flexible interface between POE and Tk, among other things.

Postbacks are blessed, and their DESTROY methods are used to notify POE when Tk is done with them. From Tk's point of view, the only difference between a callback and a postback is this blessing.

For some reason, Tk does not pass parameters to a blessed callback."

He gives a workaround, but I am not sure 1) if this is the issue I have uncovered or )2 if it is, how to apply the workaround.

[1]: http://osdir.com/ml/lang.perl.poe/2004-01/msg00002.html :Tk With POE - bind() function for keypresses"


Source: (StackOverflow)

POE::Kernel->run() takes around 15 seconds to stop/

This is my code, have redacted the "use" statements. They all are working as desired.

my $json_data;

sub request {
    my ( $method, $container, $params, $content_type) = @_;

    #get the complete URL, works fine
    my $full_url = get_url( $method, $container, $params, $content_type);

    POE::Component::Client::HTTP->spawn(Alias => 'ua');

    # Start a session that will drive the resolver.
    # Callbacks are named functions in the "main" package.
    POE::Session->create(
    inline_states => {
        _start       => \&_start,
        got_response => \&got_response,
        }
    );

    POE::Kernel->run();
    return $json_data;
}

sub _start {
    my $kernel = $_[KERNEL];
    $kernel->post("ua" => "request", "got_response", $full_url);
}

sub got_response {
    my ($response_packet) = $_[ARG1];

    my $http_response = $response_packet->[0];
    my $response_string = $http_response->decoded_content();
    $json_data = decode_json( $response_string);
    print Dumper $json_data;
}

The Dumper in got_response prints the value instantly, but after that I have to wait at least 15 seconds for the return statement after POE::Kernel->run to execute. It returns the correct value but I can't wait that long. If I add exit after the sub get_reponse dumper statement, then no value is returned.

Any help and suggestion will be appreciated.


Source: (StackOverflow)

How do I find the current value of a processes STDOUT in Perl?

I have a POE Perl program forking children.

The children it is forking do logging and interactive telnets into remote devices. POE uses STDOUT to return output back up to the parent process but for some reason it's getting lost (not going to screen or to any files).

I'm theorising that this is because STDOUT is being redirected somewhere - I need to ascertain where.

I have used (-t STDOUT) to identify that the STDOUT of the child is not a TTY.

I have also reset the STDOUT of the child to be that of the parent before the child was called - but this method seems to avoid POE's event handlers and it just dumps the output to parents STDOUT.

Q) How do I identify what the current STDOUT points at so I can find where my data is going

Thanks

Simon


Source: (StackOverflow)

Are multiple simultaneous Perl POE providers permitted?

I'm using POE to build a system that bridges several protocols (HTTP, IRC, XMPP), and I'd like to use POE to drive a single event loop that handles these protocols. Can I do this safely, and if so, how?


Source: (StackOverflow)

How can I identify Windows PnP events with Perl's POE?

Is there a POE module that identifies PnP events in Windows? If yes, could someone provide idea code snippet?


Source: (StackOverflow)

How do I write tests against POE EasyDBI?

I'm looking for some ideas or techniques to write tests against code that uses an EasyDBI session for accessing data in mysql. I don't want the EasyDBI session to be aware of being tested, so I was hoping to find a way to mock a DSN or something like that. But, It's not clear to me how I might do that.

Anyone had/solved this problem before?


Source: (StackOverflow)