display gearman server used
[MojoX-Gearman.git] / lib / MojoX / Gearman.pm
1 package MojoX::Gearman;
2
3 use strict;
4 use warnings;
5
6 our $VERSION = 0.1;
7 use base 'Mojo::Base';
8
9 use Mojo::IOLoop;
10 use List::Util    ();
11 use Mojo::Util    ();
12 use Scalar::Util        ();
13 use Data::Dump qw(dump);
14 require Carp;
15
16 __PACKAGE__->attr(server   => '127.0.0.1:4730');
17 __PACKAGE__->attr(ioloop   => sub { Mojo::IOLoop->new });
18 __PACKAGE__->attr(error => undef);
19 __PACKAGE__->attr(timeout  => 300);
20 __PACKAGE__->attr(encoding => 'UTF-8');
21 __PACKAGE__->attr(
22         on_error => sub {
23                 sub {
24                         my $gearman = shift;
25                         warn "Gearman error: ", $gearman->error, "\n";
26                   }
27         }
28 );
29 __PACKAGE__->attr(res => undef);
30
31 sub DESTROY {
32         my $self = shift;
33
34         # Loop
35         return unless my $loop = $self->ioloop;
36
37         # Cleanup connection
38         $loop->drop($self->{_connection})
39           if $self->{_connection};
40 }
41
42 sub connect {
43         my $self = shift;
44
45         # drop old connection
46         if ($self->connected) {
47                 $self->ioloop->drop($self->{_connection});
48         }
49
50         $self->server =~ m{^([^:]+)(:(\d+))?};
51         my $address = $1;
52         my $port = $3 || 4730;
53
54         Scalar::Util::weaken $self;
55
56         # connect
57         $self->{_connecting} = 1;
58         $self->{_connection} = $self->ioloop->connect(
59                 {   address     => $address,
60                         port       => $port,
61                         on_connect => sub { $self->_on_connect(@_) },
62                         on_read => sub { $self->_on_read(@_) },
63                         on_error   => sub { $self->_on_error(@_) },
64                         on_hup   => sub { $self->_on_hup(@_) },
65                 }
66         );
67
68         warn "# using gearman server $address:$port\n";
69
70         return $self;
71 }
72
73 sub connected {
74         my $self = shift;
75
76         return $self->{_connection};
77 }
78
79 my $packet_type = {
80         CAN_DO => 1,
81
82         PRE_SLEEP => 4,
83
84         NOOP => 6,
85
86         SUBMIT_JOB => 7,
87         JOB_CREATED => 8,
88
89         GRAB_JOB => 9,
90         NO_JOB => 10,
91         JOB_ASSIGN => 11,
92
93         WORK_COMPLETE => 13,
94
95         ECHO_REQ => 16,
96         ECHO_RES => 17,
97
98         ERROR => 19,
99 };
100
101 my $nr2type;
102 $nr2type->{ $packet_type->{$_} } = $_ foreach keys %$packet_type;
103
104
105 sub parse_packet {
106         my ($self,$data) = @_;
107         die "no data in packet" unless $data;
108         my ($magic, $type, $len) = unpack( "a4NN", $data );
109         die "wrong magic [$magic]" unless $magic eq "\0RES";
110         die "unsupported type [$type]" unless exists $nr2type->{$type};
111         die "ERROR" if $type == $packet_type->{ERROR};
112         return ( $type, split("\0", substr($data,12,$len)) );
113 }
114
115 sub req {
116         my $self = shift;
117 warn "XXX req ",dump(@_);
118         my $type = shift;
119         my $callback = pop @_ if ref $_[$#_] eq 'CODE';
120         my $data = join("\0", @_);
121
122         die "can't find packet type $type in ", dump $packet_type unless exists $packet_type->{$type};
123         Mojo::Util::encode($self->encoding, $data) if $self->encoding;
124
125         $self->{_res} = undef;
126
127         my $response;
128         my $cb = sub {
129                 my ( $self, $data ) = @_;
130                 my ( $type, @data ) = $self->parse_packet($data);
131                 warn "# <<<< ", $nr2type->{$type}, " ",dump(@data);
132
133                 if ( $type == $packet_type->{JOB_CREATED} ) {
134                         push @{ $self->{_cb_queue} }, sub {
135                                 my ( $self,$data ) = @_;
136 warn "# WORK_COMPLETE ",dump $data;
137                                 my ( $type, $handle, $out ) = $self->parse_packet($data);
138                                 die "not WORK_COMPLETE" unless $type == $packet_type->{WORK_COMPLETE};
139                                 $self->res( $out );
140                                 $self->stop;
141                         };
142                 } elsif ( $type == $packet_type->{NO_JOB} ) {
143                         $self->req( 'PRE_SLEEP' );
144                         $self->stop;
145                 } elsif ( $type == $packet_type->{JOB_ASSIGN} ) {
146                         my ( $handle, $function, $workload ) = @data;
147                         my $callback = $self->{_function}->{$function};
148                         die "no $function callback" unless ref $callback eq 'CODE';
149                         my $out = $callback->( $workload );
150                         warn "## $data $callback = ", dump $out;
151                         $self->req( 'WORK_COMPLETE', $handle, $out );
152                         $self->req( 'GRAB_JOB' );
153                 } elsif ( $type == $packet_type->{NOOP} ) {
154                         $self->req( 'GRAB_JOB' );
155                 } else {
156                         $self->stop;
157                 }
158
159                 my $out = $#data == 0 ? $data[0] : [ @data ];
160                 $self->res( $out );
161
162         };
163
164 #       $data .= "\0" if $data;
165         my $len = length($data);
166         my $message = pack("a4NN", "\0REQ", $packet_type->{$type}, length $data ) . $data;
167         warn "# >>>> $type ",dump($message);
168
169         my $mqueue = $self->{_message_queue} ||= [];
170         my $cqueue = $self->{_cb_queue}   ||= [];
171
172         push @$mqueue, $message;
173         push @$cqueue, $cb;
174
175         $self->connect unless $self->{_connection};
176         $self->_send_next_message;
177
178         if ( $type eq 'CAN_DO' ) {
179                 $self->{_function}->{$data} = $callback;
180                 $self->res( $callback );
181                 warn "# installed $data callback $callback";
182         } elsif ( $type =~ m/^(ECHO_REQ|SUBMIT_JOB|GRAB_JOB)$/ ) { # sync commands
183                 $self->start;
184         }
185
186         $self->res;
187 }
188
189 sub start {
190         my ($self) = @_;
191         warn "# start";
192         $self->ioloop->start;
193         return $self;
194 }
195
196 sub stop {
197         my ($self) = @_;
198         warn "# stop";
199         $self->ioloop->stop;
200         return $self;
201 }
202
203 sub _send_next_message {
204         my ($self) = @_;
205
206         if ((my $c = $self->{_connection}) && !$self->{_connecting}) {
207                 while (my $message = shift @{$self->{_message_queue}}) {
208                         warn "# write ",dump($message);
209                         $self->ioloop->write($c, $message);
210                 }
211         }
212 }
213
214 sub _on_connect {
215         my ($self, $ioloop, $id) = @_;
216         delete $self->{_connecting};
217
218         $ioloop->connection_timeout($id => $self->timeout);
219
220         $self->_send_next_message;
221 }
222
223 sub _on_error {
224         my ($self, $ioloop, $id, $error) = @_;
225
226         warn "ERROR: $error";
227
228         $self->error($error);
229         $self->_inform_queue;
230
231         $self->on_error->($self);
232
233         $ioloop->drop($id);
234 }
235
236 sub _on_hup {
237         my ($self, $ioloop, $id) = @_;
238
239         $self->{error} ||= 'disconnected';
240         $self->_inform_queue;
241
242         delete $self->{_message_queue};
243
244         delete $self->{_connecting};
245         delete $self->{_connection};
246 }
247
248 sub _inform_queue {
249         my ($self) = @_;
250
251         for my $cb (@{$self->{_cb_queue}}) {
252                 $cb->($self) if $cb;
253         }
254         $self->{_queue} = [];
255 }
256
257 sub _on_read {
258         my ($self, $ioloop, $id, $data) = @_;
259
260         my $cb = shift @{$self->{_cb_queue}};
261         if ($cb) {
262                 Mojo::Util::decode($self->encoding, $data) if $data;
263                 warn "# on read callback with ", dump($data);
264                 $cb->($self, $data);
265         } else {
266                 warn "no callback";
267         }
268
269         # Reset error after callback dispatching
270         $self->error(undef);
271 }
272
273 1;
274 __END__
275
276 =head1 NAME
277
278 MojoX::Gearman - asynchronous Gearman client for L<Mojolicious>.
279
280 =head1 SYNOPSIS
281
282         use MojoX::Gearman;
283
284         my $gearman = MojoX::Gearman->new(server => '127.0.0.1:4730');
285
286 =head1 DESCRIPTION
287
288 L<MojoX::Gearman> is an asynchronous client to Gearman for Mojo.
289
290 =head1 ATTRIBUTES
291
292 L<MojoX::Gearman> implements the following attributes.
293
294 =head2 C<server>
295
296         my $server = $gearman->server;
297         $gearman         = $gearman->server('127.0.0.1:4730');
298
299 C<Gearman> server connection string, defaults to '127.0.0.1:4730'.
300
301 =head2 C<ioloop>
302
303         my $ioloop = $gearman->ioloop;
304         $gearman         = $gearman->ioloop(Mojo::IOLoop->new);
305
306 Loop object to use for io operations, by default a L<Mojo::IOLoop> singleton
307 object will be used.
308
309 =head2 C<timeout>
310
311         my $timeout = $gearman->timeout;
312         $gearman          = $gearman->timeout(100);
313
314 Maximum amount of time in seconds a connection can be inactive before being
315 dropped, defaults to C<300>.
316
317 =head2 C<encoding>
318
319         my $encoding = $gearman->encoding;
320         $gearman           = $gearman->encoding('UTF-8');
321
322 Encoding used for stored data, defaults to C<UTF-8>.
323
324 =head1 METHODS
325
326 =head2 C<req>
327
328         $gearman->req( $type, $data, ..., sub { # callback } );
329
330 =head2 C<error>
331
332         $gearman->execute("ping" => sub {
333                 my ($gearman, $result) = @_;
334                 die $gearman->error unless defined $result;
335         }
336
337 Returns error occured during command execution.
338 Note that this method returns error code just from current command and
339 can be used just in callback.
340
341 =head2 C<on_error>
342
343         $gearman->on_error(sub{
344                 my $gearman = shift;
345                 warn 'Gearman error ', $gearman->error, "\n";
346         });
347
348 Executes if error occured. Called before commands callbacks.
349
350 =head2 C<start>
351
352         $gearman->start;
353
354 Starts IOLoop. Shortcut for $gearman->ioloop->start;
355
356 =head1 SEE ALSO
357
358 L<Gearman::Client>, L<Mojolicious>, L<Mojo::IOLoop>
359
360 =head1 SUPPORT
361
362 =head1 DEVELOPMENT
363
364 =head2 Repository
365
366         https://github.com/dpavlin/mojox-gearman
367
368 =head1 AUTHOR
369
370 Dobrica Pavlinusic, C<dpavlin@rot13.org>.
371
372 =head1 COPYRIGHT AND LICENSE
373
374 Copyright (C) 2010, Dobrica Pavlinusic
375
376 This program is free software, you can gearmantribute it and/or modify it under
377 the terms of the Artistic License version 2.0.
378
379 =cut