blib/lib/App/Netdisco/Util/Device.pm untested

filter: Statementstmt 0.0% 0 / 152 Branchbran 0.0% 0 / 84 Conditioncond 0.0% 0 / 112 MC/DCmcdc 0.0% 0 / 62 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 445 CC 43 SCAR 38.7
CC
43
Cov
0%
get_denied_actions
110.0
is_discoverable
90.0
get_device
72.0
CRAP 47.8
1 package App::Netdisco::Util::Device;
2  
3 use Dancer qw/:syntax :script/;
4 use Dancer::Plugin::DBIC 'schema';
5 use App::Netdisco::Util::Permission qw/acl_matches acl_matches_only/;
6  
7 use List::MoreUtils ();
8 use File::Spec::Functions qw(catdir catfile);
9 use File::Path 'make_path';
10 use Scalar::Util 'blessed';
11 use NetAddr::IP;
12  
13 use base 'Exporter';
14 our @EXPORT = ();
15 our @EXPORT_OK = qw/
16 get_device
17 delete_device
18 renumber_device
19 match_to_setting
20 is_discoverable is_discoverable_now
21 is_arpnipable is_arpnipable_now
22 is_macsuckable is_macsuckable_now
23 get_denied_actions
24 schedule_entry_denies
25 /;
26 our %EXPORT_TAGS = (all => \@EXPORT_OK);
27  
28 =head1 NAME
29  
30 App::Netdisco::Util::Device
31  
32 =head1 DESCRIPTION
33  
34 A set of helper subroutines to support parts of the Netdisco application.
35  
36 There are no default exports, however the C<:all> tag will export all
37 subroutines.
38  
39 =head1 EXPORT_OK
40  
41 =head2 get_device( $ip )
42  
43 Given an IP address, returns a L<DBIx::Class::Row> object for the Device in
44 the Netdisco database. The IP can be for any interface on the device.
45  
46 The address is resolved by C<DeviceIp-E<gt>resolve_alias>: a device's own address
47 in any VRF wins, else the one device the C<device_ip_resolved> view maps it to.
48  
49 If for any reason C<$ip> is already a C<DBIx::Class> Device object, then it is
50 simply returned. If C<$ip> can C<addr> or C<ip> then those methods are called
51 to get an IP address to locate in the database.
52  
53 If the device or interface IP is not known to Netdisco a new Device object is
54 created for the IP, and returned. This object is in-memory only and not yet
55 stored to the database.
56  
57 =cut
58  
59 sub get_device {
60 my $ip = shift;
61 return unless $ip;
62  
63 if (blessed $ip) {
64 return $ip if blessed $ip eq 'App::Netdisco::DB::Result::Device';
65  
66 if ($ip->can('addr')) {
67 $ip = $ip->addr;
68 }
69 elsif ($ip->can('ip')) {
70 $ip = $ip->ip;
71 }
72 else {
73 die sprintf 'unknown class %s passed to get_device', blessed $ip;
74 }
75 }
76  
77 die 'reference passed to get_device' if ref $ip;
78  
79 # in case the management IP of one device is in use on another device,
80 # we first try to get an exact match for the IP as mgmt interface.
81 my $owner = schema(vars->{'tenant'})->resultset('DeviceIp')->resolve_alias($ip);
82 $ip = $owner if defined $owner;
83  
84 return schema(vars->{'tenant'})->resultset('Device')->with_times
85 ->find_or_new({ip => $ip});
86 }
87  
88 =head2 delete_device( $ip, $archive? )
89  
90 Given an IP address, deletes the device from Netdisco, including all related
91 data such as logs and nodes. If the C<$archive> parameter is true, then nodes
92 will be maintained in an archive state.
93  
94 Returns true if the transaction completes, else returns false.
95  
96 =cut
97  
98 sub delete_device {
99 my ($ip, $archive) = @_;
100 my $device = get_device($ip) or return 0;
101 return 0 if not $device->in_storage;
102  
103 my $happy = 0;
104 schema(vars->{'tenant'})->txn_do(sub {
105 # will delete everything related too...
106 schema(vars->{'tenant'})->resultset('Device')
107 ->search({ ip => $device->ip })->delete({archive_nodes => $archive});
108  
109 $happy = 1;
110 });
111  
112 return $happy;
113 }
114  
115 =head2 renumber_device( $current_ip, $new_ip )
116  
117 Will update all records in Netdisco referring to the device with
118 C<$current_ip> to use C<$new_ip> instead, followed by renumbering the
119 device itself.
120  
121 Returns true if the transaction completes, else returns false.
122  
123 =cut
124  
125 sub renumber_device {
126 my ($ip, $new_ip) = @_;
127 my $device = get_device($ip) or return 0;
128 return 0 if not $device->in_storage;
129  
130 my $happy = 0;
131 schema(vars->{'tenant'})->txn_do(sub {
132 $device->renumber($new_ip)
133 or die "cannot renumber to: $new_ip"; # rollback
134  
135 schema(vars->{'tenant'})->resultset('UserLog')->create({
136 username => session('logged_in_user'),
137 userip => scalar eval {request->remote_address},
138 event => (sprintf "Renumber device %s to %s", $ip, $new_ip),
139 });
140  
141 $happy = 1;
142 });
143  
144 return $happy;
145 }
146  
147 =head2 match_to_setting( $type, $setting_name )
148  
149 Given a C<$type> (which may be any text value), returns true if any of the
150 list of regular expressions in C<$setting_name> is matched, otherwise returns
151 false.
152  
153 =cut
154  
155 sub match_to_setting {
156 my ($type, $setting_name) = @_;
157 return 0 unless $type and $setting_name;
158 return (scalar grep {$type =~ m/$_/}
159 @{setting($setting_name) || []});
160 }
161  
162 sub _bail_msg { debug $_[0]; return 0; }
163  
164 =head2 is_discoverable( $ip, [$device_type, \@device_capabilities]? )
165  
166 Given an IP address, returns C<true> if Netdisco on this host is permitted by
167 the local configuration to discover the device.
168  
169 The configuration items C<discover_no> and C<discover_only> are checked
170 against the given IP.
171  
172 If C<$device_type> is also given, then C<discover_no_type> will be checked.
173 Also respects C<discover_phones> and C<discover_waps> if either are set to
174 false.
175  
176 Also checks if the device is a pseudo device and no offline cache exists.
177  
178 Returns false if the host is not permitted to discover the target device.
179  
180 =cut
181  
182 sub is_discoverable {
183 my ($ip, $remote_type, $remote_cap) = @_;
184 my $device = get_device($ip) or return 0;
185 $remote_type ||= '';
186 $remote_cap ||= [];
187  
188 return _bail_msg("is_discoverable: $device is pseudo-device without offline cache")
189 if $device->is_pseudo and not $device->oids->count;
190  
191 return _bail_msg("is_discoverable: $device matches wap_platforms but discover_waps is not enabled")
192 if ((not setting('discover_waps')) and
193 match_to_setting($remote_type, 'wap_platforms'));
194  
195 return _bail_msg("is_discoverable: $device matches wap_capabilities but discover_waps is not enabled")
196 if ((not setting('discover_waps')) and
197 (scalar grep {match_to_setting($_, 'wap_capabilities')} @$remote_cap));
198  
199 return _bail_msg("is_discoverable: $device matches phone_platforms but discover_phones is not enabled")
200 if ((not setting('discover_phones')) and
201 match_to_setting($remote_type, 'phone_platforms'));
202  
203 return _bail_msg("is_discoverable: $device matches phone_capabilities but discover_phones is not enabled")
204 if ((not setting('discover_phones')) and
205 (scalar grep {match_to_setting($_, 'phone_capabilities')} @$remote_cap));
206  
207 return _bail_msg("is_discoverable: $device matched discover_no_type")
208 if (match_to_setting($remote_type, 'discover_no_type'));
209  
210 return _bail_msg("is_discoverable: $device matched discover_no")
211 if acl_matches($device, 'discover_no');
212  
213 return _bail_msg("is_discoverable: $device failed to match discover_only")
214 unless acl_matches_only($device, 'discover_only');
215  
216 return 1;
217 }
218  
219 =head2 is_discoverable_now( $ip, $device_type? )
220  
221 Same as C<is_discoverable>, but also compares the C<last_discover> field
222 of the C<device> to the C<discover_min_age> configuration.
223  
224 Returns false if the host is not permitted to discover the target device.
225  
226 =cut
227  
228 sub is_discoverable_now {
229 my ($ip, $remote_type) = @_;
230 my $device = get_device($ip) or return 0;
231  
232 if ($device->in_storage
233 and $device->since_last_discover and setting('discover_min_age')
234 and $device->since_last_discover < setting('discover_min_age')) {
235  
236 return _bail_msg("is_discoverable: $device last discover < discover_min_age");
237 }
238  
239 return is_discoverable(@_);
240 }
241  
242 =head2 is_arpnipable( $ip )
243  
244 Given an IP address, returns C<true> if Netdisco on this host is permitted by
245 the local configuration to arpnip the device.
246  
247 The configuration items C<arpnip_no> and C<arpnip_only> are checked
248 against the given IP.
249  
250 Also checks if the device reports layer 3 capability, or matches
251 C<force_arpnip> or C<ignore_layers>.
252  
253 Returns false if the host is not permitted to arpnip the target device.
254  
255 =cut
256  
257 sub is_arpnipable {
258 my $ip = shift;
259 my $device = get_device($ip) or return 0;
260  
261 return _bail_msg("is_arpnipable: $device has no layer 3 capability")
262 if ($device->in_storage() and not ($device->has_layer(3)
263 or acl_matches($device, 'force_arpnip')
264 or acl_matches($device, 'ignore_layers')));
265  
266 return _bail_msg("is_arpnipable: $device matched arpnip_no")
267 if acl_matches($device, 'arpnip_no');
268  
269 return _bail_msg("is_arpnipable: $device failed to match arpnip_only")
270 unless acl_matches_only($device, 'arpnip_only');
271  
272 return 1;
273 }
274  
275 =head2 is_arpnipable_now( $ip )
276  
277 Same as C<is_arpnipable>, but also compares the C<last_arpnip> field
278 of the C<device> to the C<arpnip_min_age> configuration.
279  
280 Returns false if the host is not permitted to arpnip the target device.
281  
282 =cut
283  
284 sub is_arpnipable_now {
285 my ($ip) = @_;
286 my $device = get_device($ip) or return 0;
287  
288 if ($device->in_storage
289 and $device->since_last_arpnip and setting('arpnip_min_age')
290 and $device->since_last_arpnip < setting('arpnip_min_age')) {
291  
292 return _bail_msg("is_arpnipable: $device last arpnip < arpnip_min_age");
293 }
294  
295 return is_arpnipable(@_);
296 }
297  
298 =head2 is_macsuckable( $ip )
299  
300 Given an IP address, returns C<true> if Netdisco on this host is permitted by
301 the local configuration to macsuck the device.
302  
303 The configuration items C<macsuck_no> and C<macsuck_only> are checked
304 against the given IP.
305  
306 Also checks if the device reports layer 2 capability, or matches
307 C<force_macsuck> or C<ignore_layers>.
308  
309 Returns false if the host is not permitted to macsuck the target device.
310  
311 =cut
312  
313 sub is_macsuckable {
314 my $ip = shift;
315 my $device = get_device($ip) or return 0;
316  
317 return _bail_msg("is_macsuckable: $device has no layer 2 capability")
318 if ($device->in_storage() and not ($device->has_layer(2)
319 or acl_matches($device, 'force_macsuck')
320 or acl_matches($device, 'ignore_layers')));
321  
322 return _bail_msg("is_macsuckable: $device matched macsuck_no")
323 if acl_matches($device, 'macsuck_no');
324  
325 return _bail_msg("is_macsuckable: $device matched macsuck_unsupported")
326 if acl_matches($device, 'macsuck_unsupported');
327  
328 return _bail_msg("is_macsuckable: $device failed to match macsuck_only")
329 unless acl_matches_only($device, 'macsuck_only');
330  
331 return 1;
332 }
333  
334 =head2 is_macsuckable_now( $ip )
335  
336 Same as C<is_macsuckable>, but also compares the C<last_macsuck> field
337 of the C<device> to the C<macsuck_min_age> configuration.
338  
339 Returns false if the host is not permitted to macsuck the target device.
340  
341 =cut
342  
343 sub is_macsuckable_now {
344 my ($ip) = @_;
345 my $device = get_device($ip) or return 0;
346  
347 if ($device->in_storage
348 and $device->since_last_macsuck and setting('macsuck_min_age')
349 and $device->since_last_macsuck < setting('macsuck_min_age')) {
350  
351 return _bail_msg("is_macsuckable: $device last macsuck < macsuck_min_age");
352 }
353  
354 return is_macsuckable(@_);
355 }
356  
357 =head2 get_denied_actions( $device )
358  
359 Checks configured ACLs for the device on this backend and returns list
360 of actions which are denied.
361  
362 =cut
363  
364 sub get_denied_actions {
365 my $device = shift;
366 my @badactions = ();
367 return @badactions unless $device;
368 $device = get_device($device); # might be no-op but is done in is_* anyway
369  
370 if ($device->is_pseudo) {
371 # always let pseudo devices do contact|location|portname|snapshot|delete
372 # and additionally if there's a snapshot cache, is_discoverable will let
373 # them do all other discover and high prio actions
374 push @badactions, ('discover', grep { $_ !~ m/^(?:contact|location|portname|snapshot|delete)$/ }
375 @{ setting('job_prio')->{high} })
376 if not is_discoverable($device);
377 }
378 else {
379 # #1335 always let delete run
380 push @badactions, ('discover', grep { $_ !~ m/^(?:delete)$/ }
381 @{ setting('job_prio')->{high} })
382 if not is_discoverable($device);
383 }
384  
385 push @badactions, (qw/macsuck nbtstat/)
386 if not is_macsuckable($device);
387  
388 push @badactions, 'arpnip'
389 if not is_arpnipable($device);
390  
391 # add pseudo-actions for schedule entries with ACLs
392 my $schedule = setting('schedule') || {};
393 foreach my $label (keys %$schedule) {
394 my $sched = $schedule->{$label} || next;
395 next unless $sched->{only} or $sched->{no};
396  
397 my $action = $sched->{action} || $label;
398 my $pseudo_action = "scheduled-$label";
399  
400 # if this action is denied in global config then schedule should not run
401 if (scalar grep {$_ eq $action} @badactions) {
402 push @badactions, $pseudo_action;
403 next;
404 }
405  
406 push @badactions, $pseudo_action
407 if schedule_entry_denies($device, $sched);
408 }
409  
410 return List::MoreUtils::uniq @badactions;
411 }
412  
413 =head2 schedule_entry_denies( $device, $entry )
414  
415 Given a Device row and a C<schedule> entry, returns true when the entry's
416 C<device>, C<only> or C<no> leave the device out.
417  
418 A C<device> that is not a single valid range, or is C<0.0.0.0/0>, limits
419 nothing; C<only> and C<no> still apply.
420  
421 =cut
422  
423 # shared by the skip list (get_denied_actions) and the scheduler job, which
424 # filters itself because a worker beside a dedicated scheduler has no schedule
425 sub schedule_entry_denies {
426 my ($device, $sched) = @_;
427  
428 my $net = ($sched->{device} ? NetAddr::IP->new($sched->{device}) : undef);
429 undef $net if $net and ($net->num == 0 or $net->addr eq '0.0.0.0');
430  
431 return 1 if $net and not acl_matches_only($device, $net->cidr);
432 return 1 if $sched->{no} and acl_matches($device, $sched->{no});
433 return 1 if $sched->{only} and not acl_matches_only($device, $sched->{only});
434 return 0;
435 }
436  
437 1;