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

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