Merge remote-tracking branch 'bogomips/list_keys' into next-small
[MogileFS-Server.git] / lib / MogileFS / Worker / Query.pm
blob4ab5910c9a597bf2ecfea1d14fa1641f7e60280a
1 package MogileFS::Worker::Query;
2 # responds to queries from Mogile clients
4 use strict;
5 use warnings;
7 use base 'MogileFS::Worker';
8 use fields qw(querystarttime reqid callid);
9 use MogileFS::Util qw(error error_code first weighted_list
10 device_state eurl decode_url_args);
11 use MogileFS::HTTPFile;
12 use MogileFS::Rebalance;
13 use MogileFS::Config;
14 use MogileFS::Server;
16 sub new {
17 my ($class, $psock) = @_;
18 my $self = fields::new($class);
19 $self->SUPER::new($psock);
21 $self->{querystarttime} = undef;
22 $self->{reqid} = undef;
23 $self->{callid} = undef;
24 return $self;
27 # no query should take 30 seconds, and we check in every 5 seconds.
28 sub watchdog_timeout { 30 }
30 # called by plugins to register a command in the namespace
31 sub register_command {
32 my ($cmd, $sub) = @_;
34 # validate the command, then convert it to the actual thing the user
35 # will be calling
36 return 0 unless $cmd =~ /^[\w\d]+$/;
37 $cmd = "plugin_$cmd";
39 # register in namespace with 'cmd_' which we will automatically find
40 no strict 'refs';
41 *{"cmd_$cmd"} = $sub;
43 # all's well
44 return 1;
47 sub work {
48 my $self = shift;
49 my $psock = $self->{psock};
50 my $rin = '';
51 vec($rin, fileno($psock), 1) = 1;
52 my $buf;
54 while (1) {
55 my $rout;
56 unless (select($rout=$rin, undef, undef, 5.0)) {
57 $self->still_alive;
58 next;
61 my $newread;
62 my $rv = sysread($psock, $newread, 1024);
63 if (!$rv) {
64 if (defined $rv) {
65 die "While reading pipe from parent, got EOF. Parent's gone. Quitting.\n";
66 } else {
67 die "Error reading pipe from parent: $!\n";
70 $buf .= $newread;
72 while ($buf =~ s/^(.+?)\r?\n//) {
73 my $line = $1;
74 if ($self->process_generic_command(\$line)) {
75 $self->still_alive; # no-op for watchdog
76 } else {
77 $self->validate_dbh;
78 $self->process_line(\$line);
84 sub process_line {
85 my MogileFS::Worker::Query $self = shift;
86 my $lineref = shift;
88 # see what kind of command this is
89 return $self->err_line('unknown_command')
90 unless $$lineref =~ /^(\d+-\d+)?\s*(\S+)\s*(.*)/;
92 $self->{reqid} = $1 || undef;
93 my ($client_ip, $line) = ($2, $3);
95 # set global variables for zone determination
96 local $MogileFS::REQ_client_ip = $client_ip;
98 # Use as array here, otherwise we get a string which breaks usage of
99 # Time::HiRes::tv_interval further on.
100 $self->{querystarttime} = [ Time::HiRes::gettimeofday() ];
102 # fallback to normal command handling
103 if ($line =~ /^(\w+)\s*(.*)/) {
104 my ($cmd, $orig_args) = ($1, $2);
105 $cmd = lc($cmd);
107 no strict 'refs';
108 my $cmd_handler = *{"cmd_$cmd"}{CODE};
109 my $args = decode_url_args(\$orig_args);
110 $self->{callid} = $args->{callid};
111 if ($cmd_handler) {
112 local $MogileFS::REQ_altzone = ($args->{zone} && $args->{zone} eq 'alt');
113 eval {
114 $cmd_handler->($self, $args);
116 if ($@) {
117 my $errc = error_code($@);
118 if ($errc eq "dup") {
119 return $self->err_line("dup");
120 } else {
121 warn "Error: $@\n";
122 error("Error running command '$cmd': $@");
123 return $self->err_line("failure");
126 return;
130 return $self->err_line('unknown_command');
133 # this is a half-finished command. in particular, errors tend to
134 # crash the parent or child or something. it's a quick hack for a quick
135 # ops task that needs done. note in particular how it reaches across
136 # package boundaries into an API that the Replicator probably doesn't
137 # want exposed.
138 sub cmd_httpcopy {
139 my MogileFS::Worker::Query $self = shift;
140 my $args = shift;
141 my $sdevid = $args->{sdevid};
142 my $ddevid = $args->{ddevid};
143 my $fid = $args->{fid};
145 my $err;
146 my $rv = MogileFS::Worker::Replicate::http_copy(sdevid => $sdevid,
147 ddevid => $ddevid,
148 fid => $fid,
149 errref => \$err);
150 if ($rv) {
151 my $dfid = MogileFS::DevFID->new($ddevid, $fid);
152 $dfid->add_to_db
153 or return $self->err_line("copy_err", "failed to add link to database");
154 return $self->ok_line;
155 } else {
156 return $self->err_line("copy_err", $err);
160 # returns 0 on error, or dmid of domain
161 sub check_domain {
162 my MogileFS::Worker::Query $self = shift;
163 my $args = shift;
165 my $domain = $args->{domain};
167 return $self->err_line("no_domain") unless defined $domain && length $domain;
169 # validate domain
170 my $dmid = eval { Mgd::domain_factory()->get_by_name($domain)->id } or
171 return $self->err_line("unreg_domain");
173 return $dmid;
176 sub cmd_sleep {
177 my MogileFS::Worker::Query $self = shift;
178 my $args = shift;
179 sleep($args->{duration} || 10);
180 return $self->ok_line;
183 sub cmd_test {
184 my MogileFS::Worker::Query $self = shift;
185 my $args = shift;
186 die "Crashed on purpose" if $args->{crash};
187 return $self->ok_line;
190 sub cmd_clear_cache {
191 my MogileFS::Worker::Query $self = shift;
193 $self->forget_that_monitor_has_run;
194 $self->send_to_parent(":refresh_monitor");
195 $self->wait_for_monitor;
197 return $self->ok_line(@_);
200 sub cmd_create_open {
201 my MogileFS::Worker::Query $self = shift;
202 my $args = shift;
204 # has to be filled out for some plugins
205 $args->{dmid} = $self->check_domain($args) or return;
207 # first, pass this to a hook to do any manipulations needed
208 eval {MogileFS::run_global_hook('cmd_create_open', $args)};
210 return $self->err_line("plugin_aborted", "$@")
211 if $@;
213 # validate parameters
214 my $dmid = $args->{dmid};
215 my $key = $args->{key} || "";
216 my $multi = $args->{multi_dest} ? 1 : 0;
217 my $size = $args->{size} || undef; # Size is optional at create time,
218 # but used to grep devices if available
220 # optional profiling of stages, if $args->{debug_profile}
221 my @profpoints; # array of [point,hires-starttime]
222 my $profstart = sub {
223 my $pt = shift;
224 push @profpoints, [$pt, Time::HiRes::time()];
226 $profstart = sub {} unless $args->{debug_profile};
227 $profstart->("begin");
229 # we want it to be undef if not explicit, else force to numeric
230 my $exp_fidid = $args->{fid} ? int($args->{fid}) : undef;
232 # get DB handle
233 my $sto = Mgd::get_store();
235 # figure out what classid this file is for
236 my $class = $args->{class} || "";
237 my $classid = 0;
238 if (length($class)) {
239 $classid = eval { Mgd::class_factory()->get_by_name($dmid, $class)->id }
240 or return $self->err_line("unreg_class");
243 # if we haven't heard from the monitoring job yet, we need to chill a bit
244 # to prevent a race where we tell a user that we can't create a file when
245 # in fact we've just not heard from the monitor
246 $profstart->("wait_monitor");
247 $self->wait_for_monitor;
249 $profstart->("find_deviceid");
251 my @devices = Mgd::device_factory()->get_all;
252 if ($size) {
253 # We first ignore all the devices with an unknown space free.
254 @devices = grep { length($_->mb_free) && ($_->mb_free * 1024*1024) > $size } @devices;
256 # If we didn't find any, try all the devices with an unknown space free.
257 # This may happen if mogstored isn't running.
258 if (!@devices) {
259 @devices = grep { !length($_->mb_free) } Mgd::device_factory()->get_all;
263 unless (MogileFS::run_global_hook('cmd_create_open_order_devices', [ @devices ], \@devices)) {
264 @devices = sort_devs_by_freespace(@devices);
267 # find suitable device(s) to put this file on.
268 my @dests; # MogileFS::Device objects which are suitable
270 while (scalar(@dests) < ($multi ? 3 : 1)) {
271 my $ddev = shift @devices;
273 last unless $ddev;
274 next unless $ddev->not_on_hosts(map { $_->host } @dests);
276 push @dests, $ddev;
278 return $self->err_line("no_devices") unless @dests;
280 my $fidid = eval {
281 $sto->register_tempfile(
282 fid => $exp_fidid, # may be undef/NULL to mean auto-increment
283 dmid => $dmid,
284 key => $key,
285 classid => $classid,
286 devids => join(',', map { $_->id } @dests),
289 unless ($fidid) {
290 my $errc = error_code($@);
291 return $self->err_line("fid_in_use") if $errc eq "dup";
292 warn "Error registering tempfile: $@\n";
293 return $self->err_line("db");
296 # make sure directories exist for client to be able to PUT into
297 foreach my $dev (@dests) {
298 $profstart->("vivify_dir_on_dev" . $dev->id);
299 my $dfid = MogileFS::DevFID->new($dev, $fidid);
300 $dfid->vivify_directories;
303 $profstart->("end");
305 # common reply variables
306 my $res = {
307 fid => $fidid,
310 # add profiling data
311 if (@profpoints) {
312 $res->{profpoints} = 0;
313 for (my $i=0; $i<$#profpoints; $i++) {
314 my $ptnum = ++$res->{profpoints};
315 $res->{"prof_${ptnum}_name"} = $profpoints[$i]->[0];
316 $res->{"prof_${ptnum}_time"} =
317 sprintf("%0.03f",
318 $profpoints[$i+1]->[1] - $profpoints[$i]->[1]);
322 # add path info
323 if ($multi) {
324 my $ct = 0;
325 foreach my $dev (@dests) {
326 $ct++;
327 $res->{"devid_$ct"} = $dev->id;
328 $res->{"path_$ct"} = MogileFS::DevFID->new($dev, $fidid)->url;
330 $res->{dev_count} = $ct;
331 } else {
332 $res->{devid} = $dests[0]->id;
333 $res->{path} = MogileFS::DevFID->new($dests[0], $fidid)->url;
336 return $self->ok_line($res);
339 sub sort_devs_by_freespace {
340 my @devices_with_weights = map {
341 [$_, 100 * $_->percent_free]
342 } sort {
343 $b->percent_free <=> $a->percent_free;
344 } grep {
345 $_->should_get_new_files;
346 } @_;
348 my @list =
349 MogileFS::Util::weighted_list(splice(@devices_with_weights, 0, 20));
351 return @list;
354 sub valid_key {
355 my ($key) = @_;
357 return defined($key) && length($key);
360 sub cmd_create_close {
361 my MogileFS::Worker::Query $self = shift;
362 my $args = shift;
364 # has to be filled out for some plugins
365 $args->{dmid} = $self->check_domain($args) or return;
367 # call out to a hook that might modify the arguments for us
368 MogileFS::run_global_hook('cmd_create_close', $args);
370 # late validation of parameters
371 my $dmid = $args->{dmid};
372 my $key = $args->{key};
373 my $fidid = $args->{fid} or return $self->err_line("no_fid");
374 my $devid = $args->{devid} or return $self->err_line("no_devid");
375 my $path = $args->{path} or return $self->err_line("no_path");
376 my $checksum = $args->{checksum};
378 if ($checksum) {
379 $checksum = eval { MogileFS::Checksum->from_string($fidid, $checksum) };
380 return $self->err_line("invalid_checksum_format") if $@;
383 my $fid = MogileFS::FID->new($fidid);
384 my $dfid = MogileFS::DevFID->new($devid, $fid);
386 # is the provided path what we'd expect for this fid/devid?
387 return $self->err_line("bogus_args")
388 unless $path eq $dfid->url;
390 my $sto = Mgd::get_store();
392 # find the temp file we're closing and making real. If another worker
393 # already has it, bail out---the client closed it twice.
394 # this is racy, but the only expected use case is a client retrying.
395 # should still be fixed better once more scalable locking is available.
396 my $trow = $sto->delete_and_return_tempfile_row($fidid) or
397 return $self->err_line("no_temp_file");
399 # Protect against leaving orphaned uploads.
400 my $failed = sub {
401 $dfid->add_to_db;
402 $fid->delete;
405 unless ($trow->{devids} =~ m/\b$devid\b/) {
406 $failed->();
407 return $self->err_line("invalid_destdev", "File uploaded to invalid dest $devid. Valid devices were: " . $trow->{devids});
410 # if a temp file is closed without a provided-key, that means to
411 # delete it.
412 unless (valid_key($key)) {
413 $failed->();
414 return $self->ok_line;
417 # get size of file and verify that it matches what we were given, if anything
418 my $httpfile = MogileFS::HTTPFile->at($path);
419 my $size = $httpfile->size;
421 # size check is optional? Needs to support zero byte files.
422 $args->{size} = -1 unless $args->{size};
423 if (!defined($size) || $size == MogileFS::HTTPFile::FILE_MISSING) {
424 # storage node is unreachable or the file is missing
425 my $type = defined $size ? "missing" : "cantreach";
426 my $lasterr = MogileFS::Util::last_error();
427 $failed->();
428 return $self->err_line("size_verify_error", "Expected: $args->{size}; actual: 0 ($type); path: $path; error: $lasterr")
431 if ($args->{size} > -1 && ($args->{size} != $size)) {
432 $failed->();
433 return $self->err_line("size_mismatch", "Expected: $args->{size}; actual: $size; path: $path")
436 # checksum validation is optional as it can be very expensive
437 # However, we /always/ verify it if the client wants us to, even
438 # if the class does not enforce or store it.
439 if ($checksum && $args->{checksumverify}) {
440 my $alg = $checksum->hashname;
441 my $actual = $httpfile->digest($alg, sub { $self->still_alive });
442 if ($actual ne $checksum->{checksum}) {
443 $failed->();
444 $actual = "$alg:" . unpack("H*", $actual);
445 return $self->err_line("checksum_mismatch",
446 "Expected: $checksum; actual: $actual; path: $path");
450 # see if we have a fid for this key already
451 my $old_fid = MogileFS::FID->new_from_dmid_and_key($dmid, $key);
452 if ($old_fid) {
453 # Fail if a file already exists for this fid. Should never
454 # happen, as it should not be possible to close a file twice.
455 return $self->err_line("fid_exists")
456 unless $old_fid->{fidid} != $fidid;
458 $old_fid->delete;
461 # TODO: check for EIO?
463 # insert file_on row
464 $dfid->add_to_db;
466 $checksum->maybe_save($dmid, $trow->{classid}) if $checksum;
468 $sto->replace_into_file(
469 fidid => $fidid,
470 dmid => $dmid,
471 key => $key,
472 length => $size,
473 classid => $trow->{classid},
474 devcount => 1,
477 # mark it as needing replicating:
478 $fid->enqueue_for_replication();
480 # call the hook - if this fails, we need to back the file out
481 my $rv = MogileFS::run_global_hook('file_stored', $args);
482 if (defined $rv && ! $rv) { # undef = no hooks, 1 = success, 0 = failure
483 $fid->delete;
484 return $self->err_line("plugin_aborted");
487 # all went well, we would've hit condthrow on DB errors
488 return $self->ok_line;
491 sub cmd_updateclass {
492 my MogileFS::Worker::Query $self = shift;
493 my $args = shift;
495 $args->{dmid} = $self->check_domain($args) or return;
497 # call out to a hook that might modify the arguments for us, abort if it tells us to
498 my $rv = MogileFS::run_global_hook('cmd_updateclass', $args);
499 return $self->err_line('plugin_aborted') if defined $rv && ! $rv;
501 my $dmid = $args->{dmid};
502 my $key = $args->{key};
503 valid_key($key) or return $self->err_line("no_key");
504 my $class = $args->{class} or return $self->err_line("no_class");
506 my $classobj = Mgd::class_factory()->get_by_name($dmid, $class)
507 or return $self->err_line('class_not_found');
508 my $classid = $classobj->id;
510 my $fid = MogileFS::FID->new_from_dmid_and_key($dmid, $key)
511 or return $self->err_line('invalid_key');
513 my @devids = $fid->devids;
514 return $self->err_line("no_devices") unless @devids;
516 if ($fid->classid != $classid) {
517 $fid->update_class(classid => $classid);
518 $fid->enqueue_for_replication();
521 return $self->ok_line;
524 sub cmd_delete {
525 my MogileFS::Worker::Query $self = shift;
526 my $args = shift;
528 # validate domain for plugins
529 $args->{dmid} = $self->check_domain($args) or return;
531 # now invoke the plugin, abort if it tells us to
532 my $rv = MogileFS::run_global_hook('cmd_delete', $args);
533 return $self->err_line('plugin_aborted')
534 if defined $rv && ! $rv;
536 # validate parameters
537 my $dmid = $args->{dmid};
538 my $key = $args->{key};
540 valid_key($key) or return $self->err_line("no_key");
542 # is this fid still owned by this key?
543 my $fid = MogileFS::FID->new_from_dmid_and_key($dmid, $key)
544 or return $self->err_line("unknown_key");
546 $fid->delete;
548 return $self->ok_line;
551 # Takes either domain/dkey or fid and tries to return as much as possible.
552 sub cmd_file_debug {
553 my MogileFS::Worker::Query $self = shift;
554 my $args = shift;
555 # Talk to the master since this is "debug mode"
556 my $sto = Mgd::get_store();
557 my $ret = {};
559 # If a FID is provided, just use that.
560 my $fid;
561 my $fidid;
562 if ($args->{fid}) {
563 $fidid = $args->{fid}+0;
564 # It's not fatal if we don't find the row here.
565 $fid = $sto->file_row_from_fidid($args->{fid}+0);
566 } else {
567 # If not, require dmid/dkey and pick up the fid from there.
568 $args->{dmid} = $self->check_domain($args) or return;
569 return $self->err_line("no_key") unless valid_key($args->{key});
571 # now invoke the plugin, abort if it tells us to
572 my $rv = MogileFS::run_global_hook('cmd_file_debug', $args);
573 return $self->err_line('plugin_aborted')
574 if defined $rv && ! $rv;
576 $fid = $sto->file_row_from_dmid_key($args->{dmid}, $args->{key});
577 return $self->err_line("unknown_key") unless $fid;
578 $fidid = $fid->{fid};
581 if ($fid) {
582 $fid->{domain} = Mgd::domain_factory()->get_by_id($fid->{dmid})->name;
583 $fid->{class} = Mgd::class_factory()->get_by_id($fid->{dmid},
584 $fid->{classid})->name;
587 # Fetch all of the queue data.
588 my $tfile = $sto->tempfile_row_from_fid($fidid);
589 my $repl = $sto->find_fid_from_file_to_replicate($fidid);
590 my $del = $sto->find_fid_from_file_to_delete2($fidid);
591 my $reb = $sto->find_fid_from_file_to_queue($fidid, REBAL_QUEUE);
592 my $fsck = $sto->find_fid_from_file_to_queue($fidid, FSCK_QUEUE);
594 # Fetch file_on rows, and turn into paths.
595 my @devids = $sto->fid_devids($fidid);
596 for my $devid (@devids) {
597 # Won't matter if we can't make the path (dev is dead/deleted/etc)
598 eval {
599 my $dfid = MogileFS::DevFID->new($devid, $fidid);
600 my $path = $dfid->get_url;
601 $ret->{'devpath_' . $devid} = $path;
604 $ret->{devids} = join(',', @devids) if @devids;
606 # Always look for a checksum
607 my $checksum = Mgd::get_store()->get_checksum($fidid);
608 if ($checksum) {
609 $checksum = MogileFS::Checksum->new($checksum);
610 $ret->{checksum} = $checksum->info;
611 } else {
612 $ret->{checksum} = 'NONE';
615 # Return file row (if found) and all other data.
616 my %toret = (fid => $fid, tempfile => $tfile, replqueue => $repl,
617 delqueue => $del, rebqueue => $reb, fsckqueue => $fsck);
618 while (my ($key, $hash) = each %toret) {
619 while (my ($name, $val) = each %$hash) {
620 $ret->{$key . '_' . $name} = $val;
624 return $self->err_line("unknown_fid") unless keys %$ret;
625 return $self->ok_line($ret);
628 sub cmd_file_info {
629 my MogileFS::Worker::Query $self = shift;
630 my $args = shift;
632 # validate domain for plugins
633 $args->{dmid} = $self->check_domain($args) or return;
635 # now invoke the plugin, abort if it tells us to
636 my $rv = MogileFS::run_global_hook('cmd_file_info', $args);
637 return $self->err_line('plugin_aborted')
638 if defined $rv && ! $rv;
640 # validate parameters
641 my $dmid = $args->{dmid};
642 my $key = $args->{key};
644 valid_key($key) or return $self->err_line("no_key");
646 my $fid;
647 Mgd::get_store()->slaves_ok(sub {
648 $fid = MogileFS::FID->new_from_dmid_and_key($dmid, $key);
650 $fid or return $self->err_line("unknown_key");
652 my $ret = {};
653 $ret->{fid} = $fid->id;
654 $ret->{domain} = Mgd::domain_factory()->get_by_id($fid->dmid)->name;
655 my $class = Mgd::class_factory()->get_by_id($fid->dmid, $fid->classid);
656 $ret->{class} = $class->name;
657 if ($class->{hashtype}) {
658 my $checksum = Mgd::get_store()->get_checksum($fid->id);
659 if ($checksum) {
660 $checksum = MogileFS::Checksum->new($checksum);
661 $ret->{checksum} = $checksum->info;
662 } else {
663 $ret->{checksum} = "MISSING";
666 $ret->{key} = $key;
667 $ret->{'length'} = $fid->length;
668 $ret->{devcount} = $fid->devcount;
669 # Only if requested, also return the raw devids.
670 # Caller should use get_paths if they intend to fetch the file.
671 if ($args->{devices}) {
672 $ret->{devids} = join(',', $fid->devids);
675 return $self->ok_line($ret);
678 sub cmd_list_fids {
679 my MogileFS::Worker::Query $self = shift;
680 my $args = shift;
682 # validate parameters
683 my $fromfid = ($args->{from} || 0)+0;
684 my $count = ($args->{to} || 0)+0;
685 $count ||= 100;
686 $count = 500 if $count > 500 || $count < 0;
688 my $rows = Mgd::get_store()->file_row_from_fidid_range($fromfid, $count);
689 return $self->err_line('failure') unless $rows;
690 return $self->ok_line({ fid_count => 0 }) unless @$rows;
692 # setup temporary storage of class/host
693 my (%domains, %classes);
695 # now iterate over our data rows and construct result
696 my $ct = 0;
697 my $ret = {};
698 foreach my $r (@$rows) {
699 $ct++;
700 my $fid = $r->{fid};
701 $ret->{"fid_${ct}_fid"} = $fid;
702 $ret->{"fid_${ct}_domain"} = ($domains{$r->{dmid}} ||=
703 Mgd::domain_factory()->get_by_id($r->{dmid})->name);
704 $ret->{"fid_${ct}_class"} = ($classes{$r->{dmid}}{$r->{classid}} ||=
705 Mgd::class_factory()->get_by_id($r->{dmid}, $r->{classid})->name);
706 $ret->{"fid_${ct}_key"} = $r->{dkey};
707 $ret->{"fid_${ct}_length"} = $r->{length};
708 $ret->{"fid_${ct}_devcount"} = $r->{devcount};
710 $ret->{fid_count} = $ct;
711 return $self->ok_line($ret);
714 sub cmd_list_keys {
715 my MogileFS::Worker::Query $self = shift;
716 my $args = shift;
718 # validate parameters
719 my $dmid = $self->check_domain($args) or return;
720 my ($prefix, $after, $limit) = ($args->{prefix}, $args->{after}, $args->{limit});
722 if (defined $prefix and $prefix ne '') {
723 # now validate that after matches prefix
724 return $self->err_line('after_mismatch')
725 if $after && $after !~ /^$prefix/;
728 $limit ||= 1000;
729 $limit += 0;
730 $limit = 1000 if $limit > 1000;
732 my $keys = Mgd::get_store()->get_keys_like($dmid, $prefix, $after, $limit);
734 # if we got nothing, say so
735 return $self->err_line('none_match') unless $keys && @$keys;
737 # construct the output and send
738 my $ret = { key_count => 0, next_after => '' };
739 foreach my $key (@$keys) {
740 $ret->{key_count}++;
741 $ret->{next_after} = $key
742 if $key gt $ret->{next_after};
743 $ret->{"key_$ret->{key_count}"} = $key;
745 return $self->ok_line($ret);
748 sub cmd_rename {
749 my MogileFS::Worker::Query $self = shift;
750 my $args = shift;
752 # validate parameters
753 my $dmid = $self->check_domain($args) or return;
754 my ($fkey, $tkey) = ($args->{from_key}, $args->{to_key});
755 unless (valid_key($fkey) && valid_key($tkey)) {
756 return $self->err_line("no_key");
759 my $fid = MogileFS::FID->new_from_dmid_and_key($dmid, $fkey)
760 or return $self->err_line("unknown_key");
762 $fid->rename($tkey) or
763 $self->err_line("key_exists");
765 return $self->ok_line;
768 sub cmd_get_hosts {
769 my MogileFS::Worker::Query $self = shift;
770 my $args = shift;
772 my $ret = { hosts => 0 };
773 for my $host (Mgd::host_factory()->get_all) {
774 next if defined $args->{hostid} && $host->id != $args->{hostid};
775 my $n = ++$ret->{hosts};
776 my $fields = $host->fields(qw(hostid status hostname hostip http_port
777 http_get_port altip altmask));
778 while (my ($key, $val) = each %$fields) {
779 # must be regular data so copy it in
780 $ret->{"host${n}_$key"} = $val;
784 return $self->ok_line($ret);
787 sub cmd_get_devices {
788 my MogileFS::Worker::Query $self = shift;
789 my $args = shift;
791 my $ret = { devices => 0 };
792 for my $dev (Mgd::device_factory()->get_all) {
793 next if defined $args->{devid} && $dev->id != $args->{devid};
794 my $n = ++$ret->{devices};
796 my $sum = $dev->fields;
797 while (my ($key, $val) = each %$sum) {
798 $ret->{"dev${n}_$key"} = $val;
802 return $self->ok_line($ret);
805 sub cmd_create_device {
806 my MogileFS::Worker::Query $self = shift;
807 my $args = shift;
809 my $status = $args->{state} || "alive";
810 return $self->err_line("invalid_state") unless
811 device_state($status);
813 my $devid = $args->{devid};
814 return $self->err_line("invalid_devid") unless $devid && $devid =~ /^\d+$/;
816 my $hostid;
818 my $sto = Mgd::get_store();
819 if ($args->{hostid} && $args->{hostid} =~ /^\d+$/) {
820 $hostid = $sto->get_hostid_by_id($args->{hostid});
821 return $self->err_line("unknown_hostid") unless $hostid;
822 } elsif (my $hname = $args->{hostname}) {
823 $hostid = $sto->get_hostid_by_name($hname);
824 return $self->err_line("unknown_host") unless $hostid;
825 } else {
826 return $self->err_line("bad_args", "No hostid/hostname parameter");
829 if (eval { $sto->create_device($devid, $hostid, $status) }) {
830 return $self->cmd_clear_cache;
833 my $errc = error_code($@);
834 return $self->err_line("existing_devid") if $errc;
835 die $@; # rethrow;
838 sub cmd_create_domain {
839 my MogileFS::Worker::Query $self = shift;
840 my $args = shift;
842 my $domain = $args->{domain} or
843 return $self->err_line('no_domain');
845 my $dom = eval { Mgd::get_store()->create_domain($domain); };
846 if ($@) {
847 if (error_code($@) eq "dup") {
848 return $self->err_line('domain_exists');
850 return $self->err_line('failure', "$@");
853 return $self->cmd_clear_cache({ domain => $domain });
856 sub cmd_delete_domain {
857 my MogileFS::Worker::Query $self = shift;
858 my $args = shift;
860 my $domain = $args->{domain} or
861 return $self->err_line('no_domain');
863 my $sto = Mgd::get_store();
864 my $dmid = $sto->get_domainid_by_name($domain) or
865 return $self->err_line('domain_not_found');
867 if (eval { $sto->delete_domain($dmid) }) {
868 return $self->cmd_clear_cache({ domain => $domain });
871 my $err = error_code($@);
872 return $self->err_line('domain_has_files') if $err eq "has_files";
873 return $self->err_line('domain_has_classes') if $err eq "has_classes";
874 return $self->err_line("failure");
877 sub cmd_create_class {
878 my MogileFS::Worker::Query $self = shift;
879 my $args = shift;
881 my $domain = $args->{domain};
882 return $self->err_line('no_domain') unless length $domain;
884 my $class = $args->{class};
885 return $self->err_line('no_class') unless length $class;
887 my $mindevcount = $args->{mindevcount}+0;
888 return $self->err_line('invalid_mindevcount') unless $mindevcount > 0;
890 my $replpolicy = $args->{replpolicy} || '';
891 if ($replpolicy) {
892 eval {
893 MogileFS::ReplicationPolicy->new_from_policy_string($replpolicy);
895 return $self->err_line('invalid_replpolicy', $@) if $@;
898 my $hashtype = $args->{hashtype};
899 if ($hashtype && $hashtype ne 'NONE') {
900 my $tmp = $MogileFS::Checksum::NAME2TYPE{$hashtype};
901 return $self->err_line('invalid_hashtype') unless $tmp;
902 $hashtype = $tmp;
905 my $sto = Mgd::get_store();
906 my $dmid = $sto->get_domainid_by_name($domain) or
907 return $self->err_line('domain_not_found');
909 my $clsid = $sto->get_classid_by_name($dmid, $class);
910 if (!defined $clsid && $args->{update} && $class eq 'default') {
911 $args->{update} = 0;
913 if ($args->{update}) {
914 return $self->err_line('class_not_found') if ! defined $clsid;
915 $sto->update_class_name(dmid => $dmid, classid => $clsid,
916 classname => $class);
917 } else {
918 $clsid = eval { $sto->create_class($dmid, $class); };
919 if ($@) {
920 if (error_code($@) eq "dup") {
921 return $self->err_line('class_exists');
923 return $self->err_line('failure', "$@");
926 $sto->update_class_mindevcount(dmid => $dmid, classid => $clsid,
927 mindevcount => $mindevcount);
928 # don't erase an existing replpolicy if we're not setting a new one.
929 $sto->update_class_replpolicy(dmid => $dmid, classid => $clsid,
930 replpolicy => $replpolicy) if $replpolicy;
931 if ($hashtype) {
932 $sto->update_class_hashtype(dmid => $dmid, classid => $clsid,
933 hashtype => $hashtype eq 'NONE' ? undef : $hashtype);
936 # return success
937 return $self->cmd_clear_cache({ class => $class, mindevcount => $mindevcount, domain => $domain });
940 sub cmd_update_class {
941 my MogileFS::Worker::Query $self = shift;
942 my $args = shift;
944 # simply passes through to create_class with update set
945 $self->cmd_create_class({ %$args, update => 1 });
948 sub cmd_delete_class {
949 my MogileFS::Worker::Query $self = shift;
950 my $args = shift;
952 my $domain = $args->{domain};
953 return $self->err_line('no_domain') unless length $domain;
954 my $class = $args->{class};
955 return $self->err_line('no_class') unless length $domain;
957 return $self->err_line('nodel_default_class') if $class eq 'default';
959 my $sto = Mgd::get_store();
960 my $dmid = $sto->get_domainid_by_name($domain) or
961 return $self->err_line('domain_not_found');
962 my $clsid = $sto->get_classid_by_name($dmid, $class);
963 return $self->err_line('class_not_found') unless defined $clsid;
965 if (eval { Mgd::get_store()->delete_class($dmid, $clsid) }) {
966 return $self->cmd_clear_cache({ domain => $domain, class => $class });
969 my $errc = error_code($@);
970 return $self->err_line('class_has_files') if $errc eq "has_files";
971 return $self->err_line('failure');
974 sub cmd_create_host {
975 my MogileFS::Worker::Query $self = shift;
976 my $args = shift;
978 my $hostname = $args->{host} or
979 return $self->err_line('no_host');
981 my $sto = Mgd::get_store();
982 my $hostid = $sto->get_hostid_by_name($hostname);
984 # if we're creating a new host, require ip/port, and default to
985 # host being down if client didn't specify
986 if ($args->{update}) {
987 return $self->err_line('host_not_found') unless $hostid;
988 } else {
989 return $self->err_line('host_exists') if $hostid;
990 return $self->err_line('no_ip') unless $args->{ip};
991 return $self->err_line('no_port') unless $args->{port};
992 $args->{status} ||= 'down';
995 if ($args->{status}) {
996 return $self->err_line('unknown_state')
997 unless MogileFS::Host->valid_state($args->{status});
1000 # arguments all good, let's do it.
1002 $hostid ||= $sto->create_host($hostname, $args->{ip});
1004 # Protocol mismatch data fixup.
1005 $args->{hostip} = delete $args->{ip} if exists $args->{ip};
1006 $args->{http_port} = delete $args->{port} if exists $args->{port};
1007 $args->{http_get_port} = delete $args->{getport} if exists $args->{getport};
1008 my @toupdate = grep { exists $args->{$_} } qw(status hostip http_port
1009 http_get_port altip altmask);
1010 $sto->update_host($hostid, { map { $_ => $args->{$_} } @toupdate });
1012 # return success
1013 return $self->cmd_clear_cache({ hostid => $hostid, hostname => $hostname });
1016 sub cmd_update_host {
1017 my MogileFS::Worker::Query $self = shift;
1018 my $args = shift;
1020 # simply passes through to create_host with update set
1021 $self->cmd_create_host({ %$args, update => 1 });
1024 sub cmd_delete_host {
1025 my MogileFS::Worker::Query $self = shift;
1026 my $args = shift;
1028 my $sto = Mgd::get_store();
1029 my $hostid = $sto->get_hostid_by_name($args->{host})
1030 or return $self->err_line('unknown_host');
1032 # TODO: $sto->delete_host should have a "has_devices" test internally
1033 for my $dev ($sto->get_all_devices) {
1034 return $self->err_line('host_not_empty')
1035 if $dev->{hostid} == $hostid;
1038 $sto->delete_host($hostid);
1040 return $self->cmd_clear_cache;
1043 sub cmd_get_domains {
1044 my MogileFS::Worker::Query $self = shift;
1045 my $args = shift;
1047 my $ret = {};
1048 my $dm_n = 0;
1049 for my $dom (Mgd::domain_factory()->get_all) {
1050 $dm_n++;
1051 $ret->{"domain${dm_n}"} = $dom->name;
1052 my $cl_n = 0;
1053 foreach my $cl ($dom->classes) {
1054 $cl_n++;
1055 $ret->{"domain${dm_n}class${cl_n}name"} = $cl->name;
1056 $ret->{"domain${dm_n}class${cl_n}mindevcount"} = $cl->mindevcount;
1057 $ret->{"domain${dm_n}class${cl_n}replpolicy"} =
1058 $cl->repl_policy_string;
1059 $ret->{"domain${dm_n}class${cl_n}hashtype"} = $cl->hashtype_string;
1061 $ret->{"domain${dm_n}classes"} = $cl_n;
1063 $ret->{"domains"} = $dm_n;
1065 return $self->ok_line($ret);
1068 sub cmd_get_paths {
1069 my MogileFS::Worker::Query $self = shift;
1070 my $args = shift;
1072 # memcache mappings are as follows:
1073 # mogfid:<dmid>:<dkey> -> fidid
1074 # mogdevids:<fidid> -> \@devids (and TODO: invalidate when deletion is run!)
1076 # if you specify 'noverify', that means a correct answer isn't needed and memcache can
1077 # be used.
1078 my $memc = MogileFS::Config->memcache_client;
1079 my $get_from_memc = $memc && $args->{noverify};
1080 my $memcache_ttl = MogileFS::Config->server_setting_cached("memcache_ttl") || 3600;
1082 # validate domain for plugins
1083 $args->{dmid} = $self->check_domain($args) or return;
1085 # now invoke the plugin, abort if it tells us to
1086 my $rv = MogileFS::run_global_hook('cmd_get_paths', $args);
1087 return $self->err_line('plugin_aborted')
1088 if defined $rv && ! $rv;
1090 # validate parameters
1091 my $dmid = $args->{dmid};
1092 my $key = $args->{key};
1094 valid_key($key) or return $self->err_line("no_key");
1096 # We default to returning two possible paths.
1097 # but the client may ask for more if they want.
1098 my $pathcount = $args->{pathcount} || 2;
1099 $pathcount = 2 if $pathcount < 2;
1101 # get DB handle
1102 my $fid;
1103 my $need_fid_in_memcache = 0;
1104 my $mogfid_memkey = "mogfid:$args->{dmid}:$key";
1105 if ($get_from_memc) {
1106 if (my $fidid = $memc->get($mogfid_memkey)) {
1107 $fid = MogileFS::FID->new($fidid);
1108 } else {
1109 $need_fid_in_memcache = 1;
1112 unless ($fid) {
1113 Mgd::get_store()->slaves_ok(sub {
1114 $fid = MogileFS::FID->new_from_dmid_and_key($dmid, $key);
1116 $fid or return $self->err_line("unknown_key");
1119 # add to memcache, if needed. for an hour.
1120 $memc->set($mogfid_memkey, $fid->id, $memcache_ttl ) if $need_fid_in_memcache || ($memc && !$get_from_memc);
1122 my $dmap = Mgd::device_factory()->map_by_id;
1124 my $ret = {
1125 paths => 0,
1128 # find devids that FID is on in memcache or db.
1129 my @fid_devids;
1130 my $need_devids_in_memcache = 0;
1131 my $devid_memkey = "mogdevids:" . $fid->id;
1132 if ($get_from_memc) {
1133 if (my $list = $memc->get($devid_memkey)) {
1134 @fid_devids = @$list;
1135 } else {
1136 $need_devids_in_memcache = 1;
1139 unless (@fid_devids) {
1140 Mgd::get_store()->slaves_ok(sub {
1141 @fid_devids = $fid->devids;
1143 $memc->set($devid_memkey, \@fid_devids, $memcache_ttl ) if $need_devids_in_memcache || ($memc && !$get_from_memc);
1146 my @devices = map { $dmap->{$_} } @fid_devids;
1148 my @sorted_devs;
1149 unless (MogileFS::run_global_hook('cmd_get_paths_order_devices', \@devices, \@sorted_devs)) {
1150 @sorted_devs = sort_devs_by_utilization(@devices);
1153 # keep one partially-bogus path around just in case we have nothing else to send.
1154 my $backup_path;
1156 # files on devices set for drain may disappear soon.
1157 my @drain_paths;
1159 # construct result paths
1160 foreach my $dev (@sorted_devs) {
1161 next unless $dev && $dev->host;
1163 my $dfid = MogileFS::DevFID->new($dev, $fid);
1164 my $path = $dfid->get_url;
1165 my $currently_up = $dev->should_read_from;
1167 if (! $currently_up) {
1168 $backup_path = $path;
1169 next;
1172 # only verify size one first one, and never verify if they've asked not to
1173 next unless
1174 $ret->{paths} ||
1175 $args->{noverify} ||
1176 $dfid->size_matches;
1178 if ($dev->dstate->should_drain) {
1179 push @drain_paths, $path;
1180 next;
1183 my $n = ++$ret->{paths};
1184 $ret->{"path$n"} = $path;
1185 last if $n == $pathcount; # one verified, one likely seems enough for now. time will tell.
1188 # deprioritize devices set for drain, they could disappear soon...
1189 # Clients /should/ try to use lower-numbered paths first to avoid this.
1190 if ($ret->{paths} < $pathcount && @drain_paths) {
1191 foreach my $path (@drain_paths) {
1192 my $n = ++$ret->{paths};
1193 $ret->{"path$n"} = $path;
1194 last if $n == $pathcount;
1198 # use our backup path if all else fails
1199 if ($backup_path && ! $ret->{paths}) {
1200 $ret->{paths} = 1;
1201 $ret->{path1} = $backup_path;
1204 return $self->ok_line($ret);
1207 sub sort_devs_by_utilization {
1208 my @devices_with_weights;
1210 # is this fid still owned by this key?
1211 foreach my $dev (@_) {
1212 my $weight;
1213 my $util = $dev->observed_utilization;
1215 if (defined($util) and $util =~ /\A\d+\Z/) {
1216 $weight = 102 - $util;
1217 $weight ||= 100;
1218 } else {
1219 $weight = $dev->weight;
1220 $weight ||= 100;
1222 push @devices_with_weights, [$dev, $weight];
1225 # randomly weight the devices
1226 my @list = MogileFS::Util::weighted_list(@devices_with_weights);
1228 return @list;
1231 # ------------------------------------------------------------
1233 # NOTE: cmd_edit_file is EXPERIMENTAL. Please see the documentation
1234 # for edit_file in L<MogileFS::Client>.
1235 # It is not recommended to use cmd_edit_file on production systems.
1237 # cmd_edit_file is similar to cmd_get_paths, except we:
1238 # - take the device of the first path we would have returned
1239 # - get a tempfile with a new fid (pointing to nothing) on the same device
1240 # the tempfile has the same key, so will replace the old contents on
1241 # create_close
1242 # - detach the old fid from that device (leaving the file in place)
1243 # - attach the new fid to that device
1244 # - returns only the first path to the old fid and a path to new fid
1245 # (the client then DAV-renames the old path to the new path)
1247 # TODO - what to do about situations where we would be reducing the
1248 # replica count to zero?
1249 # TODO - what to do about pending replications where we remove the source?
1250 # TODO - the current implementation of cmd_edit_file is based on a copy
1251 # of cmd_get_paths. Once proven mature, consider factoring out common
1252 # code from the two functions.
1253 # ------------------------------------------------------------
1254 sub cmd_edit_file {
1255 my MogileFS::Worker::Query $self = shift;
1256 my $args = shift;
1258 my $memc = MogileFS::Config->memcache_client;
1260 # validate domain for plugins
1261 $args->{dmid} = $self->check_domain($args) or return;
1263 # now invoke the plugin, abort if it tells us to
1264 my $rv = MogileFS::run_global_hook('cmd_get_paths', $args);
1265 return $self->err_line('plugin_aborted')
1266 if defined $rv && ! $rv;
1268 # validate parameters
1269 my $dmid = $args->{dmid};
1270 my $key = $args->{key};
1272 valid_key($key) or return $self->err_line("no_key");
1274 # get DB handle
1275 my $fid;
1276 my $need_fid_in_memcache = 0;
1277 my $mogfid_memkey = "mogfid:$args->{dmid}:$key";
1278 if (my $fidid = $memc->get($mogfid_memkey)) {
1279 $fid = MogileFS::FID->new($fidid);
1280 } else {
1281 $need_fid_in_memcache = 1;
1283 unless ($fid) {
1284 Mgd::get_store()->slaves_ok(sub {
1285 $fid = MogileFS::FID->new_from_dmid_and_key($dmid, $key);
1287 $fid or return $self->err_line("unknown_key");
1290 # add to memcache, if needed. for an hour.
1291 $memc->add($mogfid_memkey, $fid->id, 3600) if $need_fid_in_memcache;
1293 my $dmap = Mgd::device_factory()->map_by_id;
1295 my @devices_with_weights;
1297 # find devids that FID is on in memcache or db.
1298 my @fid_devids;
1299 my $need_devids_in_memcache = 0;
1300 my $devid_memkey = "mogdevids:" . $fid->id;
1301 if (my $list = $memc->get($devid_memkey)) {
1302 @fid_devids = @$list;
1303 } else {
1304 $need_devids_in_memcache = 1;
1306 unless (@fid_devids) {
1307 Mgd::get_store()->slaves_ok(sub {
1308 @fid_devids = $fid->devids;
1310 $memc->add($devid_memkey, \@fid_devids, 3600) if $need_devids_in_memcache;
1313 # is this fid still owned by this key?
1314 foreach my $devid (@fid_devids) {
1315 my $weight;
1316 my $dev = $dmap->{$devid};
1317 my $util = $dev->observed_utilization;
1319 if (defined($util) and $util =~ /\A\d+\Z/) {
1320 $weight = 102 - $util;
1321 $weight ||= 100;
1322 } else {
1323 $weight = $dev->weight;
1324 $weight ||= 100;
1326 push @devices_with_weights, [$devid, $weight];
1329 # randomly weight the devices
1330 # TODO - should we reverse the order, to leave the best
1331 # one there for get_paths?
1332 my @list = MogileFS::Util::weighted_list(@devices_with_weights);
1334 # Filter out bad devs
1335 @list = grep {
1336 my $devid = $_;
1337 my $dev = $dmap->{$devid};
1339 $dev && $dev->should_read_from;
1340 } @list;
1342 # Take first remaining device from list
1343 my $devid = $list[0];
1345 my $classid = $fid->classid;
1346 my $newfid = eval {
1347 Mgd::get_store()->register_tempfile(
1348 fid => undef, # undef => let the store pick a fid
1349 dmid => $dmid,
1350 key => $key, # This tempfile will ultimately become this key
1351 classid => $classid,
1352 devids => $devid,
1355 unless ($newfid) {
1356 my $errc = error_code($@);
1357 return $self->err_line("fid_in_use") if $errc eq "dup";
1358 warn "Error registering tempfile: $@\n";
1359 return $self->err_line("db");
1361 unless (Mgd::get_store()->remove_fidid_from_devid($fid->id, $devid)) {
1362 warn "Error removing fidid from devid";
1363 return $self->err_line("db");
1365 unless (Mgd::get_store()->add_fidid_to_devid($newfid, $devid)) {
1366 warn "Error removing fidid from devid";
1367 return $self->err_line("db");
1370 my @paths = map {
1371 my $dfid = MogileFS::DevFID->new($devid, $_);
1372 my $path = $dfid->get_url;
1373 } ($fid, $newfid);
1374 my $ret;
1375 $ret->{oldpath} = $paths[0];
1376 $ret->{newpath} = $paths[1];
1377 $ret->{fid} = $newfid;
1378 $ret->{devid} = $devid;
1379 $ret->{class} = $classid;
1380 return $self->ok_line($ret);
1383 sub cmd_set_weight {
1384 my MogileFS::Worker::Query $self = shift;
1385 my $args = shift;
1387 # figure out what they want to do
1388 my ($hostname, $devid, $weight) = ($args->{host}, $args->{device}+0, $args->{weight}+0);
1389 return $self->err_line('bad_params')
1390 unless $hostname && $devid && $weight >= 0;
1392 my $dev = Mgd::device_factory()->get_by_id($devid);
1393 return $self->err_line('no_device') unless $dev;
1394 return $self->err_line('host_mismatch')
1395 unless $dev->host->hostname eq $hostname;
1397 Mgd::get_store()->set_device_weight($dev->id, $weight);
1399 return $self->cmd_clear_cache;
1402 sub cmd_set_state {
1403 my MogileFS::Worker::Query $self = shift;
1404 my $args = shift;
1406 # figure out what they want to do
1407 my ($hostname, $devid, $state) = ($args->{host}, $args->{device}+0, $args->{state});
1409 my $dstate = device_state($state);
1410 return $self->err_line('bad_params')
1411 unless $hostname && $devid && $dstate;
1413 my $dev = Mgd::device_factory()->get_by_id($devid);
1414 return $self->err_line('no_device') unless $dev;
1415 return $self->err_line('host_mismatch')
1416 unless $dev->host->hostname eq $hostname;
1418 # make sure the destination state isn't too high
1419 return $self->err_line('state_too_high')
1420 unless $dev->can_change_to_state($state);
1422 Mgd::get_store()->set_device_state($dev->id, $state);
1423 return $self->cmd_clear_cache;
1426 sub cmd_noop {
1427 my MogileFS::Worker::Query $self = shift;
1428 my $args = shift;
1429 return $self->ok_line;
1432 sub cmd_replicate_now {
1433 my MogileFS::Worker::Query $self = shift;
1435 my $rv = Mgd::get_store()->replicate_now;
1436 return $self->ok_line({ count => int($rv) });
1439 sub cmd_set_server_setting {
1440 my MogileFS::Worker::Query $self = shift;
1441 my $args = shift;
1442 my $key = $args->{key} or
1443 return $self->err_line("bad_params");
1444 my $val = $args->{value};
1446 my $chk = MogileFS::Config->server_setting_is_writable($key) or
1447 return $self->err_line("not_writable");
1449 my $cleanval = eval { $chk->($val); };
1450 return $self->err_line("invalid_format", $@) if $@;
1452 MogileFS::Config->set_server_setting($key, $cleanval);
1454 # GROSS HACK: slave settings are managed directly by MogileFS::Client, but
1455 # I need to add a version key, so we check and inject that code here.
1456 # FIXME: Move this when slave keys are managed by query worker commands!
1457 if ($key =~ /^slave_/) {
1458 Mgd::get_store()->incr_server_setting('slave_version', 1);
1461 return $self->ok_line;
1464 sub cmd_server_setting {
1465 my MogileFS::Worker::Query $self = shift;
1466 my $args = shift;
1467 my $key = $args->{key};
1468 return $self->err_line("bad_params") unless $key;
1469 my $value = MogileFS::Config->server_setting($key);
1470 return $self->ok_line({key => $key, value => $value});
1473 sub cmd_server_settings {
1474 my MogileFS::Worker::Query $self = shift;
1475 my $ss = Mgd::get_store()->server_settings;
1476 my $ret = {};
1477 my $n = 0;
1478 while (my ($k, $v) = each %$ss) {
1479 next unless MogileFS::Config->server_setting_is_readable($k);
1480 $ret->{"key_count"} = ++$n;
1481 $ret->{"key_$n"} = $k;
1482 $ret->{"value_$n"} = $v;
1484 return $self->ok_line($ret);
1487 sub cmd_do_monitor_round {
1488 my MogileFS::Worker::Query $self = shift;
1489 my $args = shift;
1490 $self->forget_that_monitor_has_run;
1491 $self->wait_for_monitor;
1492 return $self->ok_line;
1495 sub cmd_fsck_start {
1496 my MogileFS::Worker::Query $self = shift;
1497 my $sto = Mgd::get_store();
1499 my $fsck_host = MogileFS::Config->server_setting("fsck_host");
1500 my $rebal_host = MogileFS::Config->server_setting("rebal_host");
1502 return $self->err_line("fsck_running", "fsck is already running") if $fsck_host;
1503 return $self->err_line("rebal_running", "rebalance running; cannot run fsck at same time") if $rebal_host;
1505 # reset position, if a previous fsck was already completed.
1506 my $intss = sub { MogileFS::Config->server_setting($_[0]) || 0 };
1507 my $checked_fid = $intss->("fsck_highest_fid_checked");
1508 my $final_fid = $intss->("fsck_fid_at_end");
1509 if (($checked_fid && $final_fid && $checked_fid >= $final_fid) ||
1510 (!$final_fid && !$checked_fid)) {
1511 $self->_do_fsck_reset or return $self->err_line("db");
1514 # set params for stats:
1515 $sto->set_server_setting("fsck_start_time", $sto->get_db_unixtime);
1516 $sto->set_server_setting("fsck_stop_time", undef);
1517 $sto->set_server_setting("fsck_fids_checked", 0);
1518 my $start_fid =
1519 MogileFS::Config->server_setting('fsck_highest_fid_checked') || 0;
1520 $sto->set_server_setting("fsck_start_fid", $start_fid);
1522 # and start it:
1523 $sto->set_server_setting("fsck_host", MogileFS::Config->hostname);
1524 MogileFS::ProcManager->wake_a("fsck");
1526 return $self->ok_line;
1529 sub cmd_fsck_stop {
1530 my MogileFS::Worker::Query $self = shift;
1531 my $sto = Mgd::get_store();
1532 $sto->set_server_setting("fsck_host", undef);
1533 $sto->set_server_setting("fsck_stop_time", $sto->get_db_unixtime);
1534 return $self->ok_line;
1537 sub cmd_fsck_reset {
1538 my MogileFS::Worker::Query $self = shift;
1539 my $args = shift;
1541 my $sto = Mgd::get_store();
1542 $sto->set_server_setting("fsck_opt_policy_only",
1543 ($args->{policy_only} ? "1" : undef));
1544 $sto->set_server_setting("fsck_highest_fid_checked",
1545 ($args->{startpos} ? $args->{startpos} : "0"));
1547 $self->_do_fsck_reset or return $self->err_line("db");
1548 return $self->ok_line;
1551 sub _do_fsck_reset {
1552 my MogileFS::Worker::Query $self = shift;
1553 eval {
1554 my $sto = Mgd::get_store();
1555 $sto->set_server_setting("fsck_start_time", undef);
1556 $sto->set_server_setting("fsck_stop_time", undef);
1557 $sto->set_server_setting("fsck_fids_checked", 0);
1558 $sto->set_server_setting("fsck_fid_at_end", $sto->max_fidid);
1560 # clear existing event counts summaries.
1561 my $ss = $sto->server_settings;
1562 foreach my $k (keys %$ss) {
1563 next unless $k =~ /^fsck_sum_evcount_/;
1564 $sto->set_server_setting($k, undef);
1566 my $logid = $sto->max_fsck_logid;
1567 $sto->set_server_setting("fsck_start_maxlogid", $logid);
1568 $sto->set_server_setting("fsck_logid_processed", $logid);
1570 if ($@) {
1571 error("DB error in _do_fsck_reset: $@");
1572 return 0;
1574 return 1;
1577 sub cmd_fsck_clearlog {
1578 my MogileFS::Worker::Query $self = shift;
1579 my $sto = Mgd::get_store();
1580 $sto->clear_fsck_log;
1581 return $self->ok_line;
1584 sub cmd_fsck_getlog {
1585 my MogileFS::Worker::Query $self = shift;
1586 my $args = shift;
1588 my $sto = Mgd::get_store();
1589 my @rows = $sto->fsck_log_rows($args->{after_logid}, 100);
1590 my $ret;
1591 my $n = 0;
1592 foreach my $row (@rows) {
1593 $n++;
1594 foreach my $k (keys %$row) {
1595 $ret->{"row_${n}_$k"} = $row->{$k} if defined $row->{$k};
1598 $ret->{row_count} = $n;
1599 return $self->ok_line($ret);
1602 sub cmd_fsck_status {
1603 my MogileFS::Worker::Query $self = shift;
1605 my $sto = Mgd::get_store();
1606 # Kick up the summary before we read the values
1607 $sto->fsck_log_summarize;
1608 my $fsck_host = MogileFS::Config->server_setting('fsck_host');
1609 my $intss = sub { MogileFS::Config->server_setting($_[0]) || 0 };
1610 my $ret = {
1611 running => ($fsck_host ? 1 : 0),
1612 host => $fsck_host,
1613 max_fid_checked => $intss->('fsck_highest_fid_checked'),
1614 policy_only => $intss->('fsck_opt_policy_only'),
1615 end_fid => $intss->('fsck_fid_at_end'),
1616 start_time => $intss->('fsck_start_time'),
1617 stop_time => $intss->('fsck_stop_time'),
1618 current_time => $sto->get_db_unixtime,
1619 max_logid => $sto->max_fsck_logid,
1622 # throw some stats in.
1623 my $ss = $sto->server_settings;
1624 foreach my $k (keys %$ss) {
1625 next unless $k =~ /^fsck_sum_evcount_(.+)/;
1626 $ret->{"num_$1"} += $ss->{$k};
1629 return $self->ok_line($ret);
1632 sub cmd_rebalance_status {
1633 my MogileFS::Worker::Query $self = shift;
1635 my $sto = Mgd::get_store();
1637 my $rebal_state = MogileFS::Config->server_setting('rebal_state');
1638 return $self->err_line('no_rebal_state') unless $rebal_state;
1639 return $self->ok_line({ state => $rebal_state });
1642 sub cmd_rebalance_start {
1643 my MogileFS::Worker::Query $self = shift;
1645 my $rebal_host = MogileFS::Config->server_setting("rebal_host");
1646 my $fsck_host = MogileFS::Config->server_setting("fsck_host");
1648 return $self->err_line("rebal_running", "rebalance is already running") if $rebal_host;
1649 return $self->err_line("fsck_running", "fsck running; cannot run rebalance at same time") if $fsck_host;
1651 my $rebal_state = MogileFS::Config->server_setting('rebal_state');
1652 unless ($rebal_state) {
1653 my $rebal_pol = MogileFS::Config->server_setting('rebal_policy');
1654 return $self->err_line('no_rebal_policy') unless $rebal_pol;
1656 my $rebal = MogileFS::Rebalance->new;
1657 $rebal->policy($rebal_pol);
1658 my @devs = Mgd::device_factory()->get_all;
1659 $rebal->init(\@devs);
1660 my $sdevs = $rebal->source_devices;
1662 $rebal_state = $rebal->save_state;
1663 MogileFS::Config->set_server_setting('rebal_state', $rebal_state);
1665 # TODO: register start time somewhere.
1666 MogileFS::Config->set_server_setting('rebal_host', MogileFS::Config->hostname);
1667 return $self->ok_line({ state => $rebal_state });
1670 sub cmd_rebalance_test {
1671 my MogileFS::Worker::Query $self = shift;
1672 my $rebal_pol = MogileFS::Config->server_setting('rebal_policy');
1673 my $rebal_state = MogileFS::Config->server_setting('rebal_state');
1674 return $self->err_line('no_rebal_policy') unless $rebal_pol;
1676 my $rebal = MogileFS::Rebalance->new;
1677 my @devs = Mgd::device_factory()->get_all;
1678 $rebal->policy($rebal_pol);
1679 $rebal->init(\@devs);
1681 # client should display list of source, destination devices.
1682 # FIXME: can probably avoid calling this twice by pulling state?
1683 # *or* not running init.
1684 my $sdevs = $rebal->filter_source_devices(\@devs);
1685 my $ddevs = $rebal->filter_dest_devices(\@devs);
1686 my $ret = {};
1687 $ret->{sdevs} = join(',', @$sdevs);
1688 $ret->{ddevs} = join(',', @$ddevs);
1690 return $self->ok_line($ret);
1693 sub cmd_rebalance_reset {
1694 my MogileFS::Worker::Query $self = shift;
1695 my $host = MogileFS::Config->server_setting('rebal_host');
1696 if ($host) {
1697 return $self->err_line("rebal_running", "rebalance is running") if $host;
1699 MogileFS::Config->set_server_setting('rebal_state', undef);
1700 return $self->ok_line;
1703 sub cmd_rebalance_stop {
1704 my MogileFS::Worker::Query $self = shift;
1705 my $host = MogileFS::Config->server_setting('rebal_host');
1706 unless ($host) {
1707 return $self->err_line('rebal_not_started');
1709 MogileFS::Config->set_server_setting('rebal_signal', 'stop');
1710 return $self->ok_line;
1713 sub cmd_rebalance_set_policy {
1714 my MogileFS::Worker::Query $self = shift;
1715 my $args = shift;
1717 my $rebal_host = MogileFS::Config->server_setting("rebal_host");
1718 return $self->err_line("no_set_rebal", "cannot change rebalance policy while rebalance is running") if $rebal_host;
1720 # load policy object, test policy, set policy.
1721 my $rebal = MogileFS::Rebalance->new;
1722 eval {
1723 $rebal->policy($args->{policy});
1725 if ($@) {
1726 return $self->err_line("bad_rebal_pol", $@);
1729 MogileFS::Config->set_server_setting('rebal_policy', $args->{policy});
1730 MogileFS::Config->set_server_setting('rebal_state', undef);
1731 return $self->ok_line;
1734 sub ok_line {
1735 my MogileFS::Worker::Query $self = shift;
1737 my $delay = '';
1738 if ($self->{querystarttime}) {
1739 $delay = sprintf("%.4f ", Time::HiRes::tv_interval( $self->{querystarttime} ));
1740 $self->{querystarttime} = undef;
1743 my $id = defined $self->{reqid} ? "$self->{reqid} " : '';
1745 my $args = shift || {};
1746 $args->{callid} = $self->{callid} if defined $self->{callid};
1747 my $argline = join('&', map { eurl($_) . "=" . eurl($args->{$_}) } keys %$args);
1748 $self->send_to_parent("${id}${delay}OK $argline");
1749 return 1;
1752 # first argument: error code.
1753 # second argument: optional error text. text will be taken from code if no text provided.
1754 sub err_line {
1755 my MogileFS::Worker::Query $self = shift;
1757 my $err_code = shift;
1758 my $err_text = shift || {
1759 'dup' => "Duplicate name/number used.",
1760 'after_mismatch' => "Pattern does not match the after-value?",
1761 'bad_params' => "Invalid parameters to command; please see documentation",
1762 'class_exists' => "That class already exists in that domain",
1763 'class_has_files' => "Class still has files, unable to delete",
1764 'class_not_found' => "Class not found",
1765 'db' => "Database error",
1766 'domain_has_files' => "Domain still has files, unable to delete",
1767 'domain_exists' => "That domain already exists",
1768 'domain_not_empty' => "Domain still has classes, unable to delete",
1769 'domain_not_found' => "Domain not found",
1770 'failure' => "Operation failed",
1771 'host_exists' => "That host already exists",
1772 'host_mismatch' => "The device specified doesn't belong to the host specified",
1773 'host_not_empty' => "Unable to delete host; it contains devices still",
1774 'host_not_found' => "Host not found",
1775 'invalid_checker_level' => "Checker level invalid. Please see documentation on this command.",
1776 'invalid_mindevcount' => "The mindevcount must be at least 1",
1777 'key_exists' => "Target key name already exists; can't overwrite.",
1778 'no_class' => "No class provided",
1779 'no_devices' => "No devices found to store file",
1780 'no_device' => "Device not found",
1781 'no_domain' => "No domain provided",
1782 'no_host' => "No host provided",
1783 'no_ip' => "IP required to create host",
1784 'no_port' => "Port required to create host",
1785 'no_temp_file' => "No tempfile or file already closed",
1786 'none_match' => "No keys match that pattern and after-value (if any).",
1787 'plugin_aborted' => "Action aborted by plugin",
1788 'state_too_high' => "Status cannot go from dead to alive; must use down",
1789 'unknown_command' => "Unknown server command",
1790 'unknown_host' => "Host not found",
1791 'unknown_state' => "Invalid/unknown state",
1792 'unreg_domain' => "Domain name invalid/not found",
1793 'rebal_not_started' => "Rebalance not running",
1794 'no_rebal_state' => "No available rebalance status",
1795 'no_rebal_policy' => "No rebalance policy available",
1796 'nodel_default_class' => "Cannot delete the default class",
1797 }->{$err_code} || $err_code;
1799 my $delay = '';
1800 if ($self->{querystarttime}) {
1801 $delay = sprintf("%.4f ", Time::HiRes::tv_interval($self->{querystarttime}));
1802 $self->{querystarttime} = undef;
1803 } else {
1804 # don't send another ERR line if we already sent one
1805 error("err_line called redundantly with $err_code ( " . eurl($err_text) . ")");
1806 return 0;
1809 my $id = defined $self->{reqid} ? "$self->{reqid} " : '';
1810 my $callid = defined $self->{callid} ? ' ' . eurl($self->{callid}) : '';
1812 $self->send_to_parent("${id}${delay}ERR $err_code " . eurl($err_text) . $callid);
1813 return 0;
1818 # Local Variables:
1819 # mode: perl
1820 # c-basic-indent: 4
1821 # indent-tabs-mode: nil
1822 # End:
1824 __END__
1826 =head1 NAME
1828 MogileFS::Worker::Query -- implements the MogileFS client protocol
1830 =head1 SEE ALSO
1832 L<MogileFS::Worker>