blib/lib/App/Netdisco/Configuration.pm untested

filter: Statementstmt 0.0% 0 / 298 Branchbran 0.0% 0 / 122 Conditioncond 0.0% 0 / 151 MC/DCmcdc 0.0% 0 / 86 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 681 CC 4 SCAR 12.8
CC
4
Cov
0%
BEGIN
12.0
BEGIN
6.0
normalize_snmp_charset
2.0
CRAP 3.6
1 package App::Netdisco::Configuration;
2  
3 use App::Netdisco::Environment;
4 use App::Netdisco::Util::DeviceAuth ();
5 use App::Netdisco::Util::Configuration 'parse_params_to_config';
6 use Dancer ':script';
7  
8 use Try::Tiny;
9 use FindBin;
10 use File::Spec;
11 use Path::Class 'dir';
12 use Net::Domain 'hostdomain';
13 use AnyEvent::Loop; # avoid EV
14 use File::ShareDir 'dist_dir';
15 use URI::Based;
16  
17 BEGIN {
18 if (setting('include_paths') and ref [] eq ref setting('include_paths')) {
19 # stuff useful locations into @INC
20 push @{setting('include_paths')},
21 dir(($ENV{NETDISCO_HOME} || $ENV{HOME}), 'nd-site-local', 'lib')->stringify
22 if (setting('site_local_files'));
23 unshift @INC, @{setting('include_paths')};
24 }
25 }
26  
27 BEGIN {
28 no warnings 'redefine';
29 use SNMP;
30  
31 # hardware exception on macOS at least when translateObj
32 # gets something like '.0.0' passed as arg
33  
34 my $orig_translate = *SNMP::translateObj{'CODE'};
35 *SNMP::translateObj = sub {
36 my $arg = $_[0];
37 return undef unless defined $arg and $arg !~ m/^[.0]+$/;
38 return $orig_translate->(@_);
39 };
40 }
41  
42 # bring in any configuration from NETDISCO_WITH_CONFIGURATION environment
43 # can be overriden by command-line or scheduled job subaction/extra
44 parse_params_to_config($ENV{NETDISCO_WITH_CONFIGURATION});
45  
46 # set up database schema config from simple config vars
47 if (ref {} eq ref setting('database')) {
48 # override from env for docker
49  
50 setting('database')->{name} =
51 ($ENV{NETDISCO_DB_NAME} || $ENV{NETDISCO_DBNAME} || $ENV{PGDATABASE} || setting('database')->{name});
52  
53 setting('database')->{host} =
54 ($ENV{NETDISCO_DB_HOST} || $ENV{PGHOST} || setting('database')->{host});
55  
56 my $portnum = ($ENV{NETDISCO_DB_PORT} || $ENV{PGPORT});
57 setting('database')->{host} .= (';port='. $portnum)
58 if (setting('database')->{host} and $portnum);
59 # at one time we required the user to add port=
60 setting('database')->{host} =~ s/port=port=/port=/ if $portnum;
61  
62 setting('database')->{user} =
63 ($ENV{NETDISCO_DB_USER} || $ENV{PGUSER} || setting('database')->{user});
64  
65 setting('database')->{pass} =
66 ($ENV{NETDISCO_DB_PASS} || $ENV{PGPASSWORD} || setting('database')->{pass});
67  
68 my $name = setting('database')->{name};
69 my $host = setting('database')->{host};
70 my $user = setting('database')->{user};
71 my $pass = setting('database')->{pass};
72  
73 my $dsn = sprintf 'dbi:Pg:dbname=%s', ($name || '');
74 $dsn .= ";host=${host}" if $host;
75  
76 # set up the netdisco schema now we have access to the config
77 # but only if it doesn't exist from an earlier config style
78 setting('plugins')->{DBIC}->{'default'} ||= {
79 dsn => $dsn,
80 user => $user,
81 password => $pass,
82 options => {
83 AutoCommit => 1,
84 RaiseError => 1,
85 auto_savepoint => 1,
86 pg_enable_utf8 => 1,
87 },
88 schema_class => 'App::Netdisco::DB',
89 };
90  
91 foreach my $c (@{setting('tenant_databases')}) {
92 my $schema = $c->{tag} or next;
93 next if exists setting('plugins')->{DBIC}->{$schema};
94  
95 my $name = $c->{name} || $c->{tag};
96 my $host = $c->{host};
97 my $user = $c->{user};
98 my $pass = $c->{pass};
99  
100 my $dsn = "dbi:Pg:dbname=${name}";
101 $dsn .= ";host=${host}" if $host;
102  
103 setting('plugins')->{DBIC}->{$schema} = {
104 dsn => $dsn,
105 user => $user,
106 password => $pass,
107 options => {
108 AutoCommit => 1,
109 RaiseError => 1,
110 auto_savepoint => 1,
111 pg_enable_utf8 => 1,
112 },
113 schema_class => 'App::Netdisco::DB',
114 };
115 }
116  
117 # and support tenancies by setting what the default schema points to
118 setting('plugins')->{DBIC}->{'netdisco'}->{'alias'} = 'default';
119  
120 # allow override of the default tenancy
121 setting('plugins')->{DBIC}->{'default'}
122 = setting('plugins')->{DBIC}->{$ENV{NETDISCO_DB_TENANT}}
123 if $ENV{NETDISCO_DB_TENANT}
124 and $ENV{NETDISCO_DB_TENANT} ne 'netdisco'
125 and exists setting('plugins')->{DBIC}->{$ENV{NETDISCO_DB_TENANT}};
126  
127 # activate environment variables so that "psql" can be called
128 # and also used by python worklets to connect (to avoid reparsing config)
129 # must happen after tenants as this rewrites env if NETDISCO_DB_TENANT in play
130 my $default = setting('plugins')->{DBIC}->{'default'};
131 if ($default->{dsn} =~ m/dbname=([^;]+)/) {
132 $ENV{PGDATABASE} = $1;
133 $ENV{NETDISCO_DB_NAME} = $ENV{PGDATABASE};
134 }
135 if ($default->{dsn} =~ m/host=([^;]+)/) {
136 $ENV{PGHOST} = $1;
137 $ENV{NETDISCO_DB_HOST} = $ENV{PGHOST};
138 }
139 if ($default->{dsn} =~ m/port=(\d+)/) {
140 $ENV{PGPORT} = $1;
141 $ENV{NETDISCO_DB_PORT} = $ENV{PGPORT};
142 }
143 $ENV{PGUSER} = $default->{user};
144 $ENV{NETDISCO_DB_USER} = $ENV{PGUSER};
145 $ENV{PGPASSWORD} = $default->{password};
146 $ENV{NETDISCO_DB_PASS} = $ENV{PGPASSWORD};
147 $ENV{PGCLIENTENCODING} = 'UTF8';
148  
149 foreach my $c (@{setting('external_databases')}) {
150 my $schema = delete $c->{tag} or next;
151 next if exists setting('plugins')->{DBIC}->{$schema};
152 setting('plugins')->{DBIC}->{$schema} = $c;
153 setting('plugins')->{DBIC}->{$schema}->{schema_class}
154 ||= 'App::Netdisco::GenericDB';
155 }
156 }
157  
158 # always set this
159 $ENV{DBIC_TRACE_PROFILE} = 'console';
160  
161 # override from env for docker
162 config->{'community'} = ($ENV{NETDISCO_RO_COMMUNITY} ?
163 [split ',', $ENV{NETDISCO_RO_COMMUNITY}] : config->{'community'});
164 config->{'community_rw'} = ($ENV{NETDISCO_RW_COMMUNITY} ?
165 [split ',', $ENV{NETDISCO_RW_COMMUNITY}] : config->{'community_rw'});
166  
167 # if snmp_auth and device_auth not set, add defaults to community{_rw}
168 if ((setting('snmp_auth') and 0 == scalar @{ setting('snmp_auth') })
169 and (setting('device_auth') and 0 == scalar @{ setting('device_auth') })) {
170 config->{'community'} = [ @{setting('community')}, 'public' ];
171 config->{'community_rw'} = [ @{setting('community_rw')}, 'private' ];
172 }
173 # fix up device_auth (or create it from old snmp_auth and community settings)
174 # also imports legacy sshcollector config
175 config->{'device_auth'}
176 = [ App::Netdisco::Util::DeviceAuth::fixup_device_auth() ];
177  
178 # defaults for workers
179 setting('workers')->{queue} ||= 'PostgreSQL';
180 if ($ENV{ND2_SINGLE_WORKER}) {
181 setting('workers')->{tasks} = 1;
182 delete setting('workers')->{queues};
183 delete config->{'schedule'};
184 }
185  
186 if ($ENV{NETDISCO_NO_SCHEDULER}) {
187 delete config->{'schedule'};
188 }
189  
190 # force skipped DNS resolution, if unset
191 setting('dns')->{hosts_file} ||= '/etc/hosts';
192 setting('dns')->{no} ||= ['fe80::/64','169.254.0.0/16'];
193  
194 # set max outstanding requests for AnyEvent::DNS
195 $ENV{'PERL_ANYEVENT_MAX_OUTSTANDING_DNS'}
196 = setting('dns')->{max_outstanding} || 50;
197 $ENV{'PERL_ANYEVENT_HOSTS'} = setting('dns')->{hosts_file};
198  
199 # load /etc/hosts
200 setting('dns')->{'ETCHOSTS'} = {};
201 {
202 # AE::DNS::EtcHosts only works for A/AAAA/SRV, but we want PTR.
203 # this loads+parses /etc/hosts file using AE. dirty hack.
204 use AnyEvent::Loop;
205 use AnyEvent::Socket 'format_address';
206 use AnyEvent::DNS::EtcHosts;
207 AnyEvent::DNS::EtcHosts::_load_hosts_unless(sub{},AE::cv);
208 no AnyEvent::DNS::EtcHosts; # unimport
209  
210 setting('dns')->{'ETCHOSTS'}->{$_} =
211 [ map { [ $_ ? (format_address $_->[0]) : '' ] }
212 @{ $AnyEvent::DNS::EtcHosts::HOSTS{ $_ } } ]
213 for keys %AnyEvent::DNS::EtcHosts::HOSTS;
214 }
215  
216 # override from env for docker
217 if ($ENV{NETDISCO_DOMAIN}) {
218 if ($ENV{NETDISCO_DOMAIN} eq 'discover') {
219 delete $ENV{NETDISCO_DOMAIN};
220 if (! setting('domain_suffix')) {
221 info 'resolving domain name...';
222 config->{'domain_suffix'} = hostdomain;
223 }
224 }
225 else {
226 config->{'domain_suffix'} = $ENV{NETDISCO_DOMAIN};
227 }
228 }
229  
230 # override SNMP bulkwalk from environment
231 config->{'bulkwalk_off'} = true
232 if (exists $ENV{NETDISCO_SNMP_BULKWALK_OFF} and $ENV{NETDISCO_SNMP_BULKWALK_OFF});
233  
234 # check user's port_control_reasons
235  
236 config->{'port_control_reasons'} =
237 config->{'port_control_reasons'} || config->{'system_port_control_reasons'};
238  
239 # convert domain_suffix from scalar or list to regexp
240  
241 config->{'domain_suffix'} = [setting('domain_suffix')]
242 if ref [] ne ref setting('domain_suffix');
243  
244 if (scalar @{ setting('domain_suffix') }) {
245 my @suffixes = map { (ref qr// eq ref $_) ? $_ : quotemeta }
246 @{ setting('domain_suffix') };
247 my $buildref = '(?:'. (join '|', @suffixes) .')$';
248 config->{'domain_suffix'} = qr/$buildref/;
249 }
250 else {
251 config->{'domain_suffix'} = qr//;
252 }
253  
254 # convert expire_devices from single to dict
255  
256 if (q{} eq ref setting('expire_devices')) {
257 config->{'expire_devices'}
258 = { 'group:__ANY__' => setting('expire_devices') };
259 }
260  
261 # convert tacacs from single to lists
262  
263 if (ref {} eq ref setting('tacacs')
264 and exists setting('tacacs')->{'key'}) {
265  
266 config->{'tacacs'} = [
267 Host => setting('tacacs')->{'server'},
268 Key => setting('tacacs')->{'key'} || setting('tacacs')->{'secret'},
269 Port => (setting('tacacs')->{'port'} || 'tacacs'),
270 Timeout => (setting('tacacs')->{'timeout'} || 15),
271 ];
272 }
273 elsif (ref [] eq ref setting('tacacs')) {
274 my @newservers = ();
275 foreach my $server (@{ setting('tacacs') }) {
276 push @newservers, [
277 Host => $server->{'server'},
278 Key => $server->{'key'} || $server->{'secret'},
279 Port => ($server->{'port'} || 'tacacs'),
280 Timeout => ($server->{'timeout'} || 15),
281 ];
282 }
283 config->{'tacacs'} = [ @newservers ];
284 }
285  
286 # support unordered dictionaries as if they were a single item list
287  
288 if (ref {} eq ref setting('device_identity')) {
289 config->{'device_identity'} = [ setting('device_identity') ];
290 }
291 else { config->{'device_identity'} ||= [] }
292  
293 if (ref {} eq ref setting('macsuck_no_deviceport')) {
294 config->{'macsuck_no_deviceports'} = [ setting('macsuck_no_deviceport') ];
295 }
296 if (ref {} eq ref setting('macsuck_no_deviceports')) {
297 config->{'macsuck_no_deviceports'} = [ setting('macsuck_no_deviceports') ];
298 }
299 else { config->{'macsuck_no_deviceports'} ||= [] }
300  
301 if (ref {} eq ref setting('hide_deviceports')) {
302 config->{'hide_deviceports'} = [ setting('hide_deviceports') ];
303 }
304 else { config->{'hide_deviceports'} ||= [] }
305  
306 if (ref {} eq ref setting('ignore_deviceports')) {
307 config->{'ignore_deviceports'} = [ setting('ignore_deviceports') ];
308 }
309 else { config->{'ignore_deviceports'} ||= [] }
310  
311 normalize_snmp_charset();
312  
313 sub normalize_snmp_charset {
314 config->{'snmp_charset'}
315 = App::Netdisco::Util::Configuration::snmp_charset_maps(config->{'snmp_charset'});
316 }
317  
318 # copy old ignore_* into new settings
319 if (scalar @{ config->{'ignore_interfaces'} }) {
320 config->{'host_groups'}->{'__IGNORE_INTERFACES__'}
321 = [ map { ($_ !~ m/^port:/) ? "port:$_" : $_ } @{ config->{'ignore_interfaces'} } ];
322 }
323 if (scalar @{ config->{'ignore_interface_types'} }) {
324 config->{'host_groups'}->{'__IGNORE_INTERFACE_TYPES__'}
325 = [ map { ($_ !~ m/^type:/) ? "type:$_" : $_ } @{ config->{'ignore_interface_types'} } ];
326 }
327 if (scalar @{ config->{'ignore_notpresent_types'} }) {
328 config->{'host_groups'}->{'__NOTPRESENT_TYPES__'}
329 = [ map { ($_ !~ m/^type:/) ? "type:$_" : $_ } @{ config->{'ignore_notpresent_types'} } ];
330 }
331  
332 # copy devices_no and devices_only into others
333 foreach my $name (qw/devices_no devices_only
334 discover_no macsuck_no arpnip_no nbtstat_no
335 discover_only macsuck_only arpnip_only nbtstat_only/) {
336 config->{$name} ||= [];
337 config->{$name} = [setting($name)] if ref [] ne ref setting($name);
338 }
339 foreach my $name (qw/discover_no macsuck_no arpnip_no nbtstat_no/) {
340 push @{setting($name)}, @{ setting('devices_no') };
341 }
342 foreach my $name (qw/discover_only macsuck_only arpnip_only nbtstat_only/) {
343 push @{setting($name)}, @{ setting('devices_only') };
344 }
345  
346 # skip_neighbor_queue is an undocumented inverse override of queue_neighbors
347 config->{'queue_neighbors'} = ! setting('skip_neighbor_queue')
348 if exists config->{'skip_neighbor_queue'};
349  
350 # legacy config item names
351  
352 # rename snmp_field_protection to just be field_protection
353 config->{'field_protection'} = config->{'snmp_field_protection'}
354 if exists config->{'snmp_field_protection'};
355  
356 # if user has previously configured too_many_devices away from 1000 default,
357 # then copy it into netmap->max_devices
358 config->{'netmap'}->{'max_devices'} =
359 config->{'sidebar_defaults'}->{'device_netmap'}->{'too_many_devices'}->{'default'}
360 if config->{'sidebar_defaults'}->{'device_netmap'}->{'too_many_devices'}->{'default'}
361 and config->{'sidebar_defaults'}->{'device_netmap'}->{'too_many_devices'}->{'default'} != 1000;
362 delete config->{'sidebar_defaults'}->{'device_netmap'}->{'too_many_devices'};
363  
364 # netmap settings moved into a netmap tree. These names are gone from
365 # config.yml, so exists() means the site set them, and being explicit they win
366 # over the too_many_devices fallback above.
367 config->{'netmap'}->{'max_devices'} =
368 config->{'netmap_performance_limit_max_devices'}
369 if exists config->{'netmap_performance_limit_max_devices'};
370  
371 config->{'netmap'}->{'custom_fields'} = config->{'netmap_custom_fields'}
372 if exists config->{'netmap_custom_fields'};
373  
374 config->{'devport_vlan_limit'} =
375 config->{'deviceport_vlan_membership_threshold'}
376 if setting('deviceport_vlan_membership_threshold')
377 and not setting('devport_vlan_limit');
378 delete config->{'deviceport_vlan_membership_threshold'};
379  
380 # portctl_native_vlan used to be called vlanctl
381 config->{'portctl_native_vlan'} ||= config->{'vlanctl'};
382 delete config->{'vlanctl'};
383  
384 config->{'schedule'} = config->{'housekeeping'}
385 if setting('housekeeping') and not setting('schedule');
386 delete config->{'housekeeping'};
387  
388 # used to have separate types of worker
389 if (exists setting('workers')->{interactives}
390 or exists setting('workers')->{pollers}) {
391  
392 setting('workers')->{tasks} ||=
393 (setting('workers')->{pollers} || 0)
394 + (setting('workers')->{interactives} || 0);
395  
396 delete setting('workers')->{pollers};
397 delete setting('workers')->{interactives};
398 }
399  
400 # allow container orchestrators to pin worker count via env (e.g. scheduler pod sets this to 0)
401 if (exists $ENV{NETDISCO_WORKERS_TASKS}) {
402 setting('workers')->{tasks} = int($ENV{NETDISCO_WORKERS_TASKS});
403  
404 # a pod pinned to no workers must not start the reserved ones either
405 delete setting('workers')->{queues} if not setting('workers')->{tasks};
406 }
407  
408 # moved the timeout setting
409 setting('workers')->{'timeout'} = setting('timeout')
410 if defined setting('timeout')
411 and !defined setting('workers')->{'timeout'};
412  
413 # 0 for workers max_deferrals and retry_after is like disabling
414 # but we need to fake it with special values
415 setting('workers')->{'max_deferrals'} ||= (2**30);
416 setting('workers')->{'retry_after'} ||= '100 years';
417  
418 # schedule expire used to be called expiry
419 setting('schedule')->{expire} ||= setting('schedule')->{expiry}
420 if setting('schedule') and exists setting('schedule')->{expiry};
421 delete config->{'schedule'}->{'expiry'} if setting('schedule');
422  
423 # upgrade reports config from hash to list
424 if (setting('reports') and ref {} eq ref setting('reports')) {
425 config->{'reports'} = [ map {{
426 tag => $_,
427 %{ setting('reports')->{$_} }
428 }} keys %{ setting('reports') } ];
429 }
430  
431 # add system_reports onto reports
432 config->{'reports'} = [ @{setting('system_reports')}, @{setting('reports')} ];
433  
434 # upgrade bare bind_params to dict
435 foreach my $r ( @{setting('reports')} ) {
436 next unless exists $r->{bind_params};
437 my $new_bind_params = [ map {ref $_ ? $_ : {param => $_}} @{ $r->{bind_params} } ];
438 $r->{'bind_params'} = $new_bind_params;
439 }
440  
441 # set swagger ui location
442 #config->{plugins}->{Swagger}->{ui_dir} =
443 #dir(dist_dir('App-Netdisco'), 'share', 'public', 'swagger-ui')->absolute;
444  
445 # setup helpers for when request->uri_for() isn't available
446 # (for example when inside swagger_path())
447 config->{url_base}
448 = URI::Based->new((config->{path} eq '/') ? '' : config->{path});
449 config->{api_base}
450 = config->{url_base}->with('/api/v1')->path;
451  
452 # device custom_fields with snmp_object creates a hook
453 my @new_dcf = ();
454 my @new_hooks = @{ setting('hooks') };
455  
456 foreach my $field (@{ setting('custom_fields')->{'device'} }) {
457 next unless $field->{'name'};
458  
459 if (not exists $field->{'snmp_object'} or not $field->{'snmp_object'}) {
460 push @new_dcf, $field;
461 next;
462 }
463  
464 # snmp_object implies JSON content in the field
465 $field->{'json_list'} = true;
466 # snmp_object implies user should not edit in the web
467 $field->{'editable'} = false;
468  
469 push @new_hooks, {
470 type => 'exec',
471 event => 'discover',
472 with => {
473 # get JSON format of the snmp_object
474 cmd => (sprintf q![%% ndo %%] show -d '[%% ip %%]' -e %s --quiet!
475 # this jq will: promote null to [], promote bare string to ["str"], collapse obj to list
476 .q! | jq -cjM '. // [] | if type=="string" then [.] else . end | [ .[] ] | sort'!
477 # send the JSON output into device custom_field (action inline)
478 .q! | [%% ndo %%] %s --enqueue -d '[%% ip %%]' -e '@-' --quiet!,
479 $field->{'snmp_object'}, ('cf_'. $field->{'name'})),
480 },
481 filter => {
482 no => $field->{'no'},
483 only => $field->{'only'},
484 },
485 };
486 push @new_dcf, $field;
487 }
488  
489 # #1040 change with-nodes to be job hook
490 foreach my $action (qw(macsuck arpnip)) {
491 push @new_hooks, {
492 type => 'exec',
493 event => 'new_device',
494 with => {
495 cmd => (sprintf q![%% ndo %%] %s --enqueue -d '[%% ip %%]' --quiet!, $action)
496 }
497 };
498 }
499  
500 config->{'hooks'} = \@new_hooks;
501 config->{'custom_fields'}->{'device'} = \@new_dcf;
502  
503 true;