#!/usr/bin/env perl use Dancer ':script'; use Dancer::Plugin::DBIC 'schema'; # add dispatch methods for each port control action use base 'Netdisco::PortControl::Actions'; use Daemon::Generic::While1; use Netdisco::Util qw/load_nd_config is_discoverable/; use Try::Tiny; newdaemon( progname => 'netdisco-daemon', ($> != 0 ? (pidbase => './') : ()), configfile => '/etc/netdisco/netdisco.conf', logpriority => 'daemon.info', ); sub gd_preconfig { my $self = shift; my $config = load_nd_config($self->{configfile}); $self->gd_error("No read-write community string has been set.") unless length $config->{_}->{community_rw}; # add local settings $config->{loc} = { sleep_time => 5, }; return (); # important } sub gd_run_body { my $self = shift; # get all pending jobs my $rs = schema('netdisco')->resultset('Admin')->search({ action => [qw/location contact portcontrol portname vlan/], status => 'queued', }); while (my $job = $rs->next) { my $target = 'set_'. $job->action; next unless $self->can($target); # filter for discover_* next unless is_discoverable($job->device); # mark job as running next unless $self->lock_job($job); # do job my ($status, $log) = $self->$target($job); # revert to queued status if we failed to action the job if (not $status) { $self->revert_job($job->job); } else { # update job state to done/error with log $self->close_job($job->job, $status, $log); } } $self->gd_sleep( var('nd_config')->{loc}->{sleep_time} ); } sub revert_job { my ($self, $id) = @_; try { schema('netdisco')->resultset('Admin') ->find($id) ->update({status => 'queued', started => undef}); } catch { warn "error reverting job: $_\n" }; } sub close_job { my ($self, $id, $status, $log) = @_; try { schema('netdisco')->resultset('Admin') ->find($id) ->update({status => $status, log => $log, finished => \'now()'}); } catch { warn "error closing job: $_\n" }; } sub lock_job { my ($self, $job) = @_; # lock db table, check job state is still queued, update to running try { my $status_updated = schema('netdisco')->txn_do(sub { my $row = schema('netdisco')->resultset('Admin')->find( {job => $job->job}, {for => 'update'} ); return 0 if $row->status ne 'queued'; $row->update({status => 'running', started => \'now()'}); return 1; }); return 0 if not $status_updated; } catch { warn "error locking job: $_\n"; return 0; }; return 1; }