| 1 | package App::Netdisco::Worker::Plugin::AddPseudoDevice; | ||
| 2 | |||
| 3 | use Dancer ':syntax'; | ||
| 4 | use Dancer::Plugin::DBIC; | ||
| 5 | use App::Netdisco::Worker::Plugin; | ||
| 6 | use aliased 'App::Netdisco::Worker::Status'; | ||
| 7 | |||
| 8 | use App::Netdisco::Util::DNS 'hostname_from_ip'; | ||
| 9 | use App::Netdisco::Util::Statistics 'pretty_version'; | ||
| 10 | use NetAddr::IP::Lite ':lower'; | ||
| 11 | |||
| 12 | register_worker({ phase => 'check' }, sub { | ||
| 13 | my ($job, $workerconf) = @_; | ||
| 14 | my $name = $job->extra; | ||
| 15 | my $ports = $job->port; | ||
| 16 | |||
| 17 | return Status->error('Missing or invalid device IP (-d).') | ||
| 18 | unless $job->device; | ||
| 19 | my $devip = $job->device->ip; | ||
| 20 | |||
| 21 | return Status->error('Missing or invalid device name (-e).') | ||
| 22 | unless $name | ||
| 23 | and $name =~ m/^[[:print:]]+$/ | ||
| 24 | and $name !~ m/[[:space:]]/; | ||
| 25 | |||
| 26 | my $ip = NetAddr::IP::Lite->new($devip); | ||
| 27 | return Status->error('Missing or invalid device IP (-d).') | ||
| 28 | unless ($ip and $ip->addr ne '0.0.0.0'); | ||
| 29 | |||
| 30 | return Status->error('Missing or invalid number of device ports (-p).') | ||
| 31 | unless $ports | ||
| 32 | and $ports =~ m/^[[:digit:]]+$/; | ||
| 33 | |||
| 34 | return Status->done('Pseudo Devive can be added'); | ||
| 35 | }); | ||
| 36 | |||
| 37 | register_worker({ phase => 'main' }, sub { | ||
| 38 | my ($job, $workerconf) = @_; | ||
| 39 | my $devip = $job->device->ip; | ||
| 40 | my $name = $job->extra; | ||
| 41 | my $ports = $job->port; | ||
| 42 | |||
| 43 | schema('netdisco')->txn_do(sub { | ||
| 44 | my $device = schema('netdisco')->resultset('Device') | ||
| 45 | ->create({ | ||
| 46 | ip => $devip, | ||
| 47 | dns => (hostname_from_ip($devip) || ''), | ||
| 48 | name => $name, | ||
| 49 | vendor => 'netdisco', | ||
| 50 | model => 'pseudodevice', | ||
| 51 | num_ports => $ports, | ||
| 52 | os => 'netdisco', | ||
| 53 | os_ver => pretty_version($App::Netdisco::VERSION, 3), | ||
| 54 | layers => '00000100', | ||
| 55 | last_discover => \'LOCALTIMESTAMP', | ||
| 56 | is_pseudo => \'true', | ||
| 57 | }); | ||
| 58 | return unless $device; | ||
| 59 | |||
| 60 | $device->ports->populate([ | ||
| 61 | [qw/port type descr/], | ||
| 62 | map {["Port$_", 'other', "Port$_"]} @{[1 .. $ports]}, | ||
| 63 | ]); | ||
| 64 | |||
| 65 | # device_ip table is used to show whether topo is "broken" | ||
| 66 | schema('netdisco')->resultset('DeviceIp') | ||
| 67 | ->create({ | ||
| 68 | ip => $devip, | ||
| 69 | alias => $devip, | ||
| 70 | vrf => '', | ||
| 71 | }); | ||
| 72 | }); | ||
| 73 | |||
| 74 | return Status->done( | ||
| 75 | sprintf "Pseudo Devive %s (%s) added", $devip, $name); | ||
| 76 | }); | ||
| 77 | |||
| 78 | true; |