App-Netdisco

 view release on metacpan or  search on metacpan

lib/App/Netdisco/Web/Plugin/Device/SNMP.pm  view on Meta::CPAN

package App::Netdisco::Web::Plugin::Device::SNMP;

use strict;
use warnings;

use Dancer qw(:syntax);
use Dancer::Plugin::Ajax;
use Dancer::Plugin::DBIC;
use Dancer::Plugin::Swagger;
use Dancer::Plugin::Auth::Extensible;

use App::Netdisco::Web::Plugin;
use App::Netdisco::Util::SNMP 'decode_and_munge';
use Module::Load ();
use Try::Tiny;

register_device_tab({ tag => 'snmp', label => 'SNMP' });

get '/ajax/content/device/snmp' => require_login sub {
    my $device = try { schema(vars->{'tenant'})->resultset('Device')
                                   ->search_for_device( param('q') ) }
       or send_error('Bad Device', 404);

    template 'ajax/device/snmp.tt', { device => $device->ip },
      { layout => 'noop' };
};

ajax '/ajax/data/device/:ip/snmptree/:base' => require_login sub {
    my $device = try { schema(vars->{'tenant'})->resultset('Device')
                                         ->find( param('ip') ) }
       or send_error('Bad Device', 404);

    my $base = param('base');
    $base =~ m/^\.1(\.\d+)*$/ or send_error('Bad OID Base', 404);

    content_type 'application/json';

    return to_json [{
      text => 'No data for this device. Admins can request a snapshot in the Details tab.',
      children => \0,
      state => { disabled => \1 },
      icon => 'icon-search',
    }] unless $device->oids->count;

    # snapshot should run a loadmibs, but just in case that didn't happen...
    return to_json [{
      text => 'No MIB objects. Please run a loadmibs job.',
      children => \0,
      state => { disabled => \1 },
      icon => 'icon-search',
    }] unless schema(vars->{'tenant'})->resultset('SNMPObject')->count();

    my $items = _get_snmp_data($device->ip, $base);
    to_json $items;
};

ajax '/ajax/data/snmp/typeahead' => require_login sub {
    my $term = param('term') or return to_json [];

    my $device = param('ip');
    my $deviceonly = param('deviceonly');
    my ($mib, $leaf) = split m/::/, $term;

    my @found = schema(vars->{'tenant'})->resultset('SNMPObject')
      ->search({ -or => [ 'me.oid'  => $term,
                          'me.oid'  => { -like => ($term .'.%') },
                          -and => [(($mib and $leaf) ? ('me.mib' => $mib, 'me.leaf' => { -ilike => ($leaf .'%') })
                                                     : ('me.leaf' => { -ilike => ('%'. $term .'%') }))] ],
                (($device and $deviceonly) ? ('device_browser.ip' => $device, 'device_browser.value' => { -not => undef }) : ()) },
              { select => [\q{ me.mib || '::' || me.leaf }],
                as => ['qleaf'],
                join => 'device_browser',
                rows => 25, order_by => 'me.oid_parts' })
      ->get_column('qleaf')->all;



( run in 0.933 second using v1.01-cache-2.11-cpan-39bf76dae61 )