| 1 | package Gearman::Server; | ||
| 2 | |||
| 3 | =head1 NAME | ||
| 4 | |||
| 5 | Gearman::Server - function call "router" and load balancer | ||
| 6 | |||
| 7 | =head1 DESCRIPTION | ||
| 8 | |||
| 9 | You run a Gearman server (or more likely, many of them for both | ||
| 10 | high-availability and load balancing), then have workers (using | ||
| 11 | L<Gearman::Worker> from the Gearman module, or libraries for other | ||
| 12 | languages) register their ability to do certain functions to all of | ||
| 13 | them, and then clients (using L<Gearman::Client>, | ||
| 14 | L<Gearman::Client::Async>, etc) request work to be done from one of | ||
| 15 | the Gearman servers. | ||
| 16 | |||
| 17 | The servers connect them, routing function call requests to the | ||
| 18 | appropriate workers, multiplexing responses to duplicate requests as | ||
| 19 | requested, etc. | ||
| 20 | |||
| 21 | More than likely, you want to use the provided L<gearmand> wrapper | ||
| 22 | script, and not use Gearman::Server directly. | ||
| 23 | |||
| 24 | =cut | ||
| 25 | |||
| 26 | use strict; | ||
| 27 | use Gearman::Server::Client; | ||
| 28 | use Gearman::Server::Listener; | ||
| 29 | use Gearman::Server::Job; | ||
| 30 | use Socket qw(IPPROTO_TCP SOL_SOCKET SOCK_STREAM AF_UNIX SOCK_STREAM PF_UNSPEC); | ||
| 31 | use Carp qw(croak); | ||
| 32 | use Sys::Hostname (); | ||
| 33 | use IO::Handle (); | ||
| 34 | |||
| 35 | use fields ( | ||
| 36 | 'client_map', # fd -> Client | ||
| 37 | 'sleepers', # func -> { "Client=HASH(0xdeadbeef)" => Client } | ||
| 38 | 'sleepers_list', # func -> [ Client, ... ], ... | ||
| 39 | 'job_queue', # job_name -> [Job, Job*] (key only exists if non-empty) | ||
| 40 | 'job_of_handle', # handle -> Job | ||
| 41 | 'max_queue', # func -> configured max jobqueue size | ||
| 42 | 'job_of_uniq', # func -> uniq -> Job | ||
| 43 | 'handle_ct', # atomic counter | ||
| 44 | 'handle_base', # atomic counter | ||
| 45 | 'listeners', # arrayref of listener objects | ||
| 46 | 'wakeup', # number of workers to wake | ||
| 47 | 'wakeup_delay', # seconds to wait before waking more workers | ||
| 48 | 'wakeup_timers', # func -> timer, timer to be canceled or adjusted when job grab/inject is called | ||
| 49 | ); | ||
| 50 | |||
| 51 | our $VERSION = "1.11"; | ||
| 52 | |||
| 53 | =head1 METHODS | ||
| 54 | |||
| 55 | =head2 new | ||
| 56 | |||
| 57 | $server_object = Gearman::Server->new( %options ) | ||
| 58 | |||
| 59 | Creates and returns a new Gearman::Server object, which attaches itself to the Danga::Socket event loop. The server will begin operating when the Danga::Socket runloop is started. This means you need to start up the runloop before anything will happen. | ||
| 60 | |||
| 61 | Options: | ||
| 62 | |||
| 63 | =over | ||
| 64 | |||
| 65 | =item port | ||
| 66 | |||
| 67 | Specify a port which you would like the Gearman::Server to listen on for TCP connections (not necessary, but useful) | ||
| 68 | |||
| 69 | =back | ||
| 70 | |||
| 71 | =cut | ||
| 72 | |||
| 73 | sub new { | ||
| 74 | my ($class, %opts) = @_; | ||
| 75 | my $self = ref $class ? $class : fields::new($class); | ||
| 76 | |||
| 77 | $self->{client_map} = {}; | ||
| 78 | $self->{sleepers} = {}; | ||
| 79 | $self->{sleepers_list} = {}; | ||
| 80 | $self->{job_queue} = {}; | ||
| 81 | $self->{job_of_handle} = {}; | ||
| 82 | $self->{max_queue} = {}; | ||
| 83 | $self->{job_of_uniq} = {}; | ||
| 84 | $self->{listeners} = []; | ||
| 85 | $self->{wakeup} = 3; | ||
| 86 | $self->{wakeup_delay} = .1; | ||
| 87 | $self->{wakeup_timers} = {}; | ||
| 88 | |||
| 89 | $self->{handle_ct} = 0; | ||
| 90 | $self->{handle_base} = "H:" . Sys::Hostname::hostname() . ":"; | ||
| 91 | |||
| 92 | my $port = delete $opts{port}; | ||
| 93 | |||
| 94 | my $wakeup = delete $opts{wakeup}; | ||
| 95 | |||
| 96 | if (defined $wakeup) { | ||
| 97 | die "Invalid value passed in wakeup option" | ||
| 98 | if $wakeup < 0 && $wakeup != -1; | ||
| 99 | $self->{wakeup} = $wakeup; | ||
| 100 | } | ||
| 101 | |||
| 102 | my $wakeup_delay = delete $opts{wakeup_delay}; | ||
| 103 | |||
| 104 | if (defined $wakeup_delay) { | ||
| 105 | die "Invalid value passed in wakeup_delay option" | ||
| 106 | if $wakeup_delay < 0 && $wakeup_delay != -1; | ||
| 107 | $self->{wakeup_delay} = $wakeup_delay; | ||
| 108 | } | ||
| 109 | |||
| 110 | croak("Unknown options") if %opts; | ||
| 111 | $self->create_listening_sock($port); | ||
| 112 | |||
| 113 | return $self; | ||
| 114 | } | ||
| 115 | |||
| 116 | sub debug { | ||
| 117 | my ($self, $msg) = @_; | ||
| 118 | #warn "$msg\n"; | ||
| 119 | } | ||
| 120 | |||
| 121 | =head2 create_listening_sock | ||
| 122 | |||
| 123 | $server_object->create_listening_sock( $portnum ) | ||
| 124 | |||
| 125 | Add a TCP port listener for incoming Gearman worker and client connections. | ||
| 126 | |||
| 127 | =cut | ||
| 128 | |||
| 129 | sub create_listening_sock { | ||
| 130 | my ($self, $portnum, %opts) = @_; | ||
| 131 | |||
| 132 | my $accept_per_loop = delete $opts{accept_per_loop}; | ||
| 133 | |||
| 134 | warn "Extra options passed into create_listening_sock: " . join(', ', keys %opts) . "\n" | ||
| 135 | if keys %opts; | ||
| 136 | |||
| 137 | my $ssock = IO::Socket::INET->new(LocalPort => $portnum, | ||
| 138 | Type => SOCK_STREAM, | ||
| 139 | Proto => IPPROTO_TCP, | ||
| 140 | Blocking => 0, | ||
| 141 | Reuse => 1, | ||
| 142 | Listen => 1024 ) | ||
| 143 | or die "Error creating socket: $@\n"; | ||
| 144 | |||
| 145 | my $listeners = $self->{listeners}; | ||
| 146 | push @$listeners, Gearman::Server::Listener->new($ssock, $self, accept_per_loop => $accept_per_loop); | ||
| 147 | |||
| 148 | return $ssock; | ||
| 149 | } | ||
| 150 | |||
| 151 | sub new_client { | ||
| 152 | my ($self, $sock) = @_; | ||
| 153 | my $client = Gearman::Server::Client->new($sock, $self); | ||
| 154 | $client->watch_read(1); | ||
| 155 | $self->{client_map}{$client->{fd}} = $client; | ||
| 156 | } | ||
| 157 | |||
| 158 | sub note_disconnected_client { | ||
| 159 | my ($self, $client) = @_; | ||
| 160 | delete $self->{client_map}{$client->{fd}}; | ||
| 161 | } | ||
| 162 | |||
| 163 | sub clients { | ||
| 164 | my $self = shift; | ||
| 165 | return values %{ $self->{client_map} }; | ||
| 166 | } | ||
| 167 | |||
| 168 | # Returns a socket that is connected to the server, we can then use this | ||
| 169 | # socket with a Gearman::Client::Async object to run clients and servers in the | ||
| 170 | # same thread. | ||
| 171 | sub to_inprocess_server { | ||
| 172 | my $self = shift; | ||
| 173 | |||
| 174 | my ($psock, $csock); | ||
| 175 | socketpair($csock, $psock, AF_UNIX, SOCK_STREAM, PF_UNSPEC) | ||
| 176 | or die "socketpair: $!"; | ||
| 177 | |||
| 178 | $csock->autoflush(1); | ||
| 179 | $psock->autoflush(1); | ||
| 180 | |||
| 181 | IO::Handle::blocking($csock, 0); | ||
| 182 | IO::Handle::blocking($psock, 0); | ||
| 183 | |||
| 184 | my $client = Gearman::Server::Client->new($csock, $self); | ||
| 185 | |||
| 186 | my ($package, $file, $line) = caller; | ||
| 187 | $client->{peer_ip} = "[$package|$file|$line]"; | ||
| 188 | $client->watch_read(1); | ||
| 189 | $self->{client_map}{$client->{fd}} = $client; | ||
| 190 | |||
| 191 | return $psock; | ||
| 192 | } | ||
| 193 | |||
| 194 | =head2 start_worker | ||
| 195 | |||
| 196 | $pid = $server_object->start_worker( $prog ) | ||
| 197 | |||
| 198 | ($pid, $client) = $server_object->start_worker( $prog ) | ||
| 199 | |||
| 200 | Fork and start a worker process named by C<$prog> and returns the pid (or pid and client object). | ||
| 201 | |||
| 202 | =cut | ||
| 203 | |||
| 204 | sub start_worker { | ||
| 205 | my ($self, $prog) = @_; | ||
| 206 | |||
| 207 | my ($psock, $csock); | ||
| 208 | socketpair($csock, $psock, AF_UNIX, SOCK_STREAM, PF_UNSPEC) | ||
| 209 | or die "socketpair: $!"; | ||
| 210 | |||
| 211 | $csock->autoflush(1); | ||
| 212 | $psock->autoflush(1); | ||
| 213 | |||
| 214 | my $pid = fork; | ||
| 215 | unless (defined $pid) { | ||
| 216 | warn "fork failed: $!\n"; | ||
| 217 | return undef; | ||
| 218 | } | ||
| 219 | |||
| 220 | # child process | ||
| 221 | unless ($pid) { | ||
| 222 | local $ENV{'GEARMAN_WORKER_USE_STDIO'} = 1; | ||
| 223 | close(STDIN); | ||
| 224 | close(STDOUT); | ||
| 225 | open(STDIN, '<&', $psock) or die "Unable to dup socketpair to STDIN: $!"; | ||
| 226 | open(STDOUT, '>&', $psock) or die "Unable to dup socketpair to STDOUT: $!"; | ||
| 227 | if (UNIVERSAL::isa($prog, "CODE")) { | ||
| 228 | $prog->(); | ||
| 229 | exit 0; # shouldn't get here. subref should exec. | ||
| 230 | } | ||
| 231 | exec $prog; | ||
| 232 | die "Exec failed: $!"; | ||
| 233 | } | ||
| 234 | |||
| 235 | close($psock); | ||
| 236 | |||
| 237 | IO::Handle::blocking($csock, 0); | ||
| 238 | my $sock = $csock; | ||
| 239 | |||
| 240 | my $client = Gearman::Server::Client->new($sock, $self); | ||
| 241 | |||
| 242 | $client->{peer_ip} = "[gearman_child]"; | ||
| 243 | $client->watch_read(1); | ||
| 244 | $self->{client_map}{$client->{fd}} = $client; | ||
| 245 | return wantarray ? ($pid, $client) : $pid; | ||
| 246 | } | ||
| 247 | |||
| 248 | sub enqueue_job { | ||
| 249 | my ($self, $job, $highpri) = @_; | ||
| 250 | my $jq = ($self->{job_queue}{$job->{func}} ||= []); | ||
| 251 | |||
| 252 | if (defined (my $max_queue_size = $self->{max_queue}{$job->{func}})) { | ||
| 253 | $max_queue_size--; # Subtract one, because we're about to add one more below. | ||
| 254 | while (@$jq > $max_queue_size) { | ||
| 255 | my $delete_job = pop @$jq; | ||
| 256 | my $msg = Gearman::Util::pack_res_command("work_fail", $delete_job->handle); | ||
| 257 | $delete_job->relay_to_listeners($msg); | ||
| 258 | $delete_job->note_finished; | ||
| 259 | } | ||
| 260 | } | ||
| 261 | |||
| 262 | if ($highpri) { | ||
| 263 | unshift @$jq, $job; | ||
| 264 | } else { | ||
| 265 | push @$jq, $job; | ||
| 266 | } | ||
| 267 | |||
| 268 | $self->{job_of_handle}{$job->{'handle'}} = $job; | ||
| 269 | } | ||
| 270 | |||
| 271 | sub wake_up_sleepers { | ||
| 272 | my ($self, $func) = @_; | ||
| 273 | |||
| 274 | if (my $existing_timer = delete($self->{wakeup_timers}->{$func})) { | ||
| 275 | $existing_timer->cancel(); | ||
| 276 | } | ||
| 277 | |||
| 278 | return unless $self->_wake_up_some($func); | ||
| 279 | |||
| 280 | my $delay = $self->{wakeup_delay}; | ||
| 281 | |||
| 282 | # -1 means don't setup a timer. 0 actually means go as fast as we can, cooperatively. | ||
| 283 | return if $delay == -1; | ||
| 284 | |||
| 285 | # If we're only going to wakeup 0 workers anyways, don't set up a timer. | ||
| 286 | return if $self->{wakeup} == 0; | ||
| 287 | |||
| 288 | my $timer = Danga::Socket->AddTimer($delay, sub { | ||
| 289 | # Be sure to not wake up more sleepers if we have no jobs in the queue. | ||
| 290 | # I know the object definition above says I can trust the func element to determine | ||
| 291 | # if there are items in the list, but I'm just gonna be safe, rather than sorry. | ||
| 292 | return unless @{$self->{job_queue}{$func} || []}; | ||
| 293 | $self->wake_up_sleepers($func) | ||
| 294 | }); | ||
| 295 | $self->{wakeup_timers}->{$func} = $timer; | ||
| 296 | } | ||
| 297 | |||
| 298 | # Returns true when there are still more workers to wake up | ||
| 299 | # False if there are no sleepers | ||
| 300 | sub _wake_up_some { | ||
| 301 | my ($self, $func) = @_; | ||
| 302 | my $sleepmap = $self->{sleepers}{$func} or return; | ||
| 303 | my $sleeporder = $self->{sleepers_list}{$func} or return; | ||
| 304 | |||
| 305 | # TODO SYNC UP STATE HERE IN CASE TWO LISTS END UP OUT OF SYNC | ||
| 306 | |||
| 307 | my $max = $self->{wakeup}; | ||
| 308 | |||
| 309 | while (@$sleeporder) { | ||
| 310 | my Gearman::Server::Client $c = shift @$sleeporder; | ||
| 311 | next if $c->{closed} || ! $c->{sleeping}; | ||
| 312 | if ($max-- <= 0) { | ||
| 313 | unshift @$sleeporder, $c; | ||
| 314 | return 1; | ||
| 315 | } | ||
| 316 | delete $sleepmap->{"$c"}; | ||
| 317 | $c->res_packet("noop"); | ||
| 318 | $c->{sleeping} = 0; | ||
| 319 | } | ||
| 320 | |||
| 321 | delete $self->{sleepers}{$func}; | ||
| 322 | delete $self->{sleepers_list}{$func}; | ||
| 323 | return; | ||
| 324 | } | ||
| 325 | |||
| 326 | sub on_client_sleep { | ||
| 327 | my $self = shift; | ||
| 328 | my Gearman::Server::Client $cl = shift; | ||
| 329 | |||
| 330 | foreach my $cd (@{$cl->{can_do_list}}) { | ||
| 331 | # immediately wake the sleeper up if there are things to be done | ||
| 332 | if ($self->{job_queue}{$cd}) { | ||
| 333 | $cl->res_packet("noop"); | ||
| 334 | $cl->{sleeping} = 0; | ||
| 335 | return; | ||
| 336 | } | ||
| 337 | |||
| 338 | my $sleepmap = ($self->{sleepers}{$cd} ||= {}); | ||
| 339 | my $count = $sleepmap->{"$cl"}++; | ||
| 340 | |||
| 341 | next if $count >= 2; | ||
| 342 | |||
| 343 | my $sleeporder = ($self->{sleepers_list}{$cd} ||= []); | ||
| 344 | |||
| 345 | # The idea here is to keep workers at the head of the list if they are doing work, hopefully | ||
| 346 | # this will allow extra workers that aren't needed to actually go 'idle' safely. | ||
| 347 | my $jobs_done = $cl->{jobs_done_since_sleep}; | ||
| 348 | |||
| 349 | if ($jobs_done) { | ||
| 350 | unshift @$sleeporder, $cl; | ||
| 351 | } else { | ||
| 352 | push @$sleeporder, $cl; | ||
| 353 | } | ||
| 354 | |||
| 355 | $cl->{jobs_done_since_sleep} = 0; | ||
| 356 | |||
| 357 | } | ||
| 358 | } | ||
| 359 | |||
| 360 | sub jobs_outstanding { | ||
| 361 | my Gearman::Server $self = shift; | ||
| 362 | return scalar keys %{ $self->{job_queue} }; | ||
| 363 | } | ||
| 364 | |||
| 365 | sub jobs { | ||
| 366 | my Gearman::Server $self = shift; | ||
| 367 | return values %{ $self->{job_of_handle} }; | ||
| 368 | } | ||
| 369 | |||
| 370 | sub job_by_handle { | ||
| 371 | my ($self, $handle) = @_; | ||
| 372 | return $self->{job_of_handle}{$handle}; | ||
| 373 | } | ||
| 374 | |||
| 375 | sub note_job_finished { | ||
| 376 | my Gearman::Server $self = shift; | ||
| 377 | my Gearman::Server::Job $job = shift; | ||
| 378 | |||
| 379 | if (my Gearman::Server::Client $worker = $job->worker) { | ||
| 380 | $worker->{jobs_done_since_sleep}++; | ||
| 381 | } | ||
| 382 | |||
| 383 | if (length($job->{uniq})) { | ||
| 384 | delete $self->{job_of_uniq}{$job->{func}}{$job->{uniq}}; | ||
| 385 | } | ||
| 386 | delete $self->{job_of_handle}{$job->{handle}}; | ||
| 387 | } | ||
| 388 | |||
| 389 | # <0/undef/"" to reset. else integer max depth. | ||
| 390 | sub set_max_queue { | ||
| 391 | my ($self, $func, $max) = @_; | ||
| 392 | if (defined $max && length $max && $max >= 0) { | ||
| 393 | $self->{max_queue}{$func} = int($max); | ||
| 394 | } else { | ||
| 395 | delete $self->{max_queue}{$func}; | ||
| 396 | } | ||
| 397 | } | ||
| 398 | |||
| 399 | sub new_job_handle { | ||
| 400 | my $self = shift; | ||
| 401 | return $self->{handle_base} . (++$self->{handle_ct}); | ||
| 402 | } | ||
| 403 | |||
| 404 | sub job_of_unique { | ||
| 405 | my ($self, $func, $uniq) = @_; | ||
| 406 | return undef unless $self->{job_of_uniq}{$func}; | ||
| 407 | return $self->{job_of_uniq}{$func}{$uniq}; | ||
| 408 | } | ||
| 409 | |||
| 410 | sub set_unique_job { | ||
| 411 | my ($self, $func, $uniq, $job) = @_; | ||
| 412 | $self->{job_of_uniq}{$func} ||= {}; | ||
| 413 | $self->{job_of_uniq}{$func}{$uniq} = $job; | ||
| 414 | } | ||
| 415 | |||
| 416 | sub grab_job { | ||
| 417 | my ($self, $func) = @_; | ||
| 418 | return undef unless $self->{job_queue}{$func}; | ||
| 419 | |||
| 420 | my $empty = sub { | ||
| 421 | delete $self->{job_queue}{$func}; | ||
| 422 | return undef; | ||
| 423 | }; | ||
| 424 | |||
| 425 | my Gearman::Server::Job $job; | ||
| 426 | while (1) { | ||
| 427 | $job = shift @{$self->{job_queue}{$func}}; | ||
| 428 | return $empty->() unless $job; | ||
| 429 | return $job unless $job->require_listener; | ||
| 430 | |||
| 431 | foreach my Gearman::Server::Client $c (@{$job->{listeners}}) { | ||
| 432 | return $job if $c && ! $c->{closed}; | ||
| 433 | } | ||
| 434 | $job->note_finished(0); | ||
| 435 | } | ||
| 436 | } | ||
| 437 | |||
| 438 | |||
| 439 | 1; | ||
| 440 | __END__ |