1 package FS::part_export::cacti;
11 Cacti integration for Freeside
15 This module in particular handles FS::part_export object creation for Cacti integration;
16 consult any existing L<FS::part_export> documentation for details on how that works.
22 use base qw( FS::part_export );
23 use FS::Record qw( qsearchs qsearch );
24 use FS::UID qw( dbh );
28 use File::Slurp qw( slurp );
30 use MIME::Base64 qw( decode_base64 encode_base64 );
31 use Storable qw(thaw);
38 tie my %options, 'Tie::IxHash',
39 'user' => { label => 'User Name',
40 default => 'freeside' },
41 'script_path' => { label => 'Script Path',
42 default => '/usr/share/cacti/cli/' },
43 'template_id' => { label => 'Host Template ID',
45 'tree_id' => { label => 'Graph Tree ID (optional)',
47 'description' => { label => 'Description (can use tokens $contact, $ip_addr and $description)',
48 default => 'Freeside $contact $description $ip_addr' },
49 'graphs_path' => { label => 'Graph Export Directory (user@host:/path/to/graphs/)',
51 'import_freq' => { label => 'Minimum minutes between graph imports',
53 'max_graph_size' => { label => 'Maximum size per graph (MB)',
55 'delete_graphs' => { label => 'Delete associated graphs and data sources when unprovisioning',
58 'cacti_graph_template_id' => {
59 'label' => 'Graph Template',
63 'cacti_snmp_query_id' => {
64 'label' => 'SNMP Query ID',
68 'cacti_snmp_query_type_id' => {
69 'label' => 'SNMP Query Type ID',
73 'cacti_snmp_field' => {
74 'label' => 'SNMP Field',
78 'cacti_snmp_value' => {
79 'label' => 'SNMP Value',
86 'svc' => 'svc_broadband',
87 'desc' => 'Export service to cacti server, for svc_broadband services',
88 'post_config_element' => '/edit/elements/part_export/cacti.html',
89 'options' => \%options,
91 Add service to cacti upon provisioning, for broadband services.<BR>
92 See <A HREF="http://www.freeside.biz/mediawiki/index.php/Freeside:4:Documentation:Cacti#Connecting_Cacti_To_Freeside">documentation</A> for details.
96 # standard hooks for provisioning/unprovisioning service
99 my ($self, $svc_broadband) = @_;
100 my ($q,$error) = _insert_queue($self, $svc_broadband);
105 my ($self, $svc_broadband) = @_;
106 my $oldAutoCommit = $FS::UID::AutoCommit;
107 local $FS::UID::AutoCommit = 0;
109 foreach my $page (qsearch('cacti_page',{ svcnum => $svc_broadband->svcnum })) {
110 my $error = $page->delete;
112 $dbh->rollback if $oldAutoCommit;
116 my ($q,$error) = _delete_queue($self, $svc_broadband);
118 $dbh->rollback if $oldAutoCommit;
121 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
125 sub _export_replace {
126 my($self, $new, $old) = @_;
127 return '' if $new->ip_addr eq $old->ip_addr; #important part didn't change
128 #delete old then insert new, with second job dependant on the first
129 my $oldAutoCommit = $FS::UID::AutoCommit;
130 local $FS::UID::AutoCommit = 0;
132 my ($dq, $iq, $error);
133 ($dq,$error) = _delete_queue($self,$old);
135 $dbh->rollback if $oldAutoCommit;
138 ($iq,$error) = _insert_queue($self,$new);
140 $dbh->rollback if $oldAutoCommit;
143 $error = $iq->depend_insert($dq->jobnum);
145 $dbh->rollback if $oldAutoCommit;
148 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
152 sub _export_suspend {
156 sub _export_unsuspend {
163 my ($self, $svc_broadband) = @_;
164 my $queue = new FS::queue {
165 'svcnum' => $svc_broadband->svcnum,
166 'job' => "FS::part_export::cacti::ssh_insert",
168 my $error = $queue->insert(
169 'host' => $self->machine,
170 'user' => $self->option('user'),
171 'hostname' => $svc_broadband->ip_addr,
172 'script_path' => $self->option('script_path'),
173 'template_id' => $self->option('template_id'),
174 'tree_id' => $self->option('tree_id'),
175 'description' => $self->option('description'),
176 'svc_desc' => $svc_broadband->description,
177 'contact' => $svc_broadband->cust_main->contact,
178 'svcnum' => $svc_broadband->svcnum,
181 return ($queue,$error);
185 my ($self, $svc_broadband) = @_;
186 my $queue = new FS::queue {
187 'svcnum' => $svc_broadband->svcnum,
188 'job' => "FS::part_export::cacti::ssh_delete",
190 my $error = $queue->insert(
191 'host' => $self->machine,
192 'user' => $self->option('user'),
193 'hostname' => $svc_broadband->ip_addr,
194 'script_path' => $self->option('script_path'),
195 'delete_graphs' => $self->option('delete_graphs'),
197 return ($queue,$error);
200 # routines run by queued jobs
204 my $self = $opt{'self'};
207 die "Non-numerical Host Template ID, check export configuration\n"
208 unless $opt{'template_id'} =~ /^\d+$/;
209 die "Non-numerical Graph Tree ID, check export configuration\n"
210 unless $opt{'tree_id'} =~ /^\d*$/;
213 my $desc = $opt{'description'};
214 $desc =~ s/\$ip_addr/$opt{'hostname'}/g;
215 $desc =~ s/\$description/$opt{'svc_desc'}/g;
216 $desc =~ s/\$contact/$opt{'contact'}/g;
217 #for some reason, device names with apostrophes fail to export graphs in Cacti
218 #just removing them for now, someday maybe dig to figure out why
219 # $desc =~ s/'/'\\''/g;
222 . $opt{'script_path'}
223 . q(add_device.php --description=')
228 . $opt{'template_id'};
229 my $response = ssh_cmd(%opt, 'command' => $cmd);
230 unless ( $response =~ /Success - new device-id: \((\d+)\)/ ) {
231 die "Error adding device: $response";
236 if ($opt{'tree_id'}) {
238 . $opt{'script_path'}
239 . q(add_tree.php --type=node --node-type=host --tree-id=)
243 $response = ssh_cmd(%opt, 'command' => $cmd);
244 unless ( $response =~ /Added Node node-id: \((\d+)\)/ ) {
245 die "Host added, but error adding host to tree: $response";
249 # Get list of graph templates for new id
251 . $opt{'script_path'}
252 . q(freeside_cacti.php --get-graph-templates --host-template=)
253 . $opt{'template_id'};
254 my $ginfo = { map { $_ ? ($_ => undef) : () } split(/\n/,ssh_cmd(%opt, 'command' => $cmd)) };
256 # Add extra config info
257 my @xtragid = split("\n", $self->option('cacti_graph_template_id'));
258 my @query_id = split("\n", $self->option('cacti_snmp_query_id'));
259 my @query_type_id = split("\n", $self->option('cacti_snmp_query_type_id'));
260 my @snmp_field = split("\n", $self->option('cacti_snmp_field'));
261 my @snmp_value = split("\n", $self->option('cacti_snmp_value'));
262 for (my $i = 0; $i < @xtragid; $i++) {
263 my $gtid = $xtragid[$i];
264 $ginfo->{$gtid} ||= [];
265 push(@{$ginfo->{$gtid}},{
267 'query_id' => $query_id[$i],
268 'query_type_id' => $query_type_id[$i],
269 'snmp_field' => $snmp_field[$i],
270 'snmp_value' => $snmp_value[$i],
275 ref($ginfo->{$_}) ? @{$ginfo->{$_}} : {'gtid' => $_}
277 warn "Host ".$opt{'hostname'}." exported to cacti, but no graphs configured"
282 foreach my $gdef (@gdefs) {
283 # validate graph info
284 my $gtid = $gdef->{'gtid'};
286 $gerror .= " Bad graph template: $gtid"
287 unless $gtid =~ /^\d+$/;
288 my $isds = $gdef->{'query_id'}
289 || $gdef->{'query_type_id'}
290 || $gdef->{'snmp_field'}
291 || $gdef->{'snmp_value'};
293 $gerror .= " Bad SNMP Query Id: " . $gdef->{'query_id'}
294 unless $gdef->{'query_id'} =~ /^\d+$/;
295 $gerror .= " Bad SNMP Query Type Id: " . $gdef->{'query_type_id'}
296 unless $gdef->{'query_type_id'} =~ /^\d+$/;
297 $gerror .= " SNMP Field cannot contain apostrophe"
298 if $gdef->{'snmp_field'} =~ /'/;
299 $gerror .= " SNMP Value cannot contain apostrophe"
300 if $gdef->{'snmp_value'} =~ /'/;
306 . $opt{'script_path'}
307 . q(add_graphs.php --graph-type=)
308 . ($isds ? 'ds' : 'cg')
309 . q( --graph-template-id=)
314 $cmd .= q( --snmp-query-id=)
315 . $gdef->{'query_id'}
316 . q( --snmp-query-type-id=)
317 . $gdef->{'query_type_id'}
319 . $gdef->{'snmp_field'}
320 . q(' --snmp-value=')
321 . $gdef->{'snmp_value'}
324 $response = ssh_cmd(%opt, 'command' => $cmd);
325 #might be more than one graph added, just testing success
326 $gerror .= "Error creating graph $gtid: $response"
327 unless $response =~ /Graph Added - graph-id: \((\d+)\)/;
331 # job fails, but partial export may have occurred
332 die $gerror . " Partial export occurred\n" if $gerror;
340 . $opt{'script_path'}
341 . q(freeside_cacti.php --drop-device --ip=')
344 $cmd .= q( --delete-graphs)
345 if $opt{'delete_graphs'};
346 my $response = ssh_cmd(%opt, 'command' => $cmd);
347 die "Error removing from cacti: " . $response
356 =item process_graphs JOB PARAM
358 Intended to be run as an FS::queue job.
360 Copies graphs for a single service from Cacti export directory to FS cache,
361 generates basic html pages for this service with base64-encoded graphs embedded,
362 and stores the generated pages in the database.
370 my $param = thaw(decode_base64(shift));
372 $job->update_statustext(10);
373 my $cachedir = $FS::UID::cache_dir . '/cacti-graphs/';
376 my $svcnum = $param->{'svcnum'} || die "No svcnum specified";
378 'table' => 'svc_broadband',
379 'hashref' => { 'svcnum' => $svcnum },
380 }) || die "Could not load svcnum $svcnum";
382 # load relevant FS::part_export::cacti object
383 my ($self) = $svc->cust_svc->part_svc->part_export('cacti');
385 $job->update_statustext(20);
387 my $oldAutoCommit = $FS::UID::AutoCommit;
388 local $FS::UID::AutoCommit = 0;
391 # check for existing pages
393 my @oldpages = qsearch({
394 'table' => 'cacti_page',
395 'hashref' => { 'svcnum' => $svcnum, 'exportnum' => $self->exportnum },
396 'select' => 'cacti_pagenum, exportnum, svcnum, graphnum, imported', #no need to load old content
397 'order_by' => 'ORDER BY graphnum',
400 #if pages are recent enough, do nothing and return
401 if ($oldpages[0]->imported > $self->exptime($now)) {
402 $job->update_statustext(100);
406 foreach my $oldpage (@oldpages) {
407 my $error = $oldpage->delete;
409 $dbh->rollback if $oldAutoCommit;
415 $job->update_statustext(30);
417 # get list of graphs for this svc from cacti server
419 . $self->option('script_path')
420 . q(freeside_cacti.php --get-graphs --ip=')
423 my @graphs = map { [ split(/\t/,$_) ] }
425 'host' => $self->machine,
426 'user' => $self->option('user'),
430 $job->update_statustext(40);
432 # copy graphs from cacti server to cache
433 # requires version 2.6.4 of rsync, released March 2005
434 my $rsync = File::Rsync->new({
438 'source' => $self->option('graphs_path'),
441 (map { q('**graph_).${$_}[0].q(*.png') } @graphs),
442 (map { q('**thumb_).${$_}[0].q(.png') } @graphs),
447 #don't know why a regular $rsync->exec isn't doing includes right, but this does
448 my $error = system(join(' ',@{$rsync->getcmd()}));
449 die "rsync failed with exit status $error" if $error;
451 $job->update_statustext(50);
453 # create html file contents
454 my $svchead = q(<!-- UPDATED ) . $now . qq( -->)
455 . '<H2 STYLE="margin-top: 0;">Service #' . $svcnum . '</H2>'
456 . q(<P>Last updated ) . scalar(localtime($now)) . q(</P>);
457 my $svchtml = $svchead;
458 my $maxgraph = 1024 * 1024 * ($self->options('max_graph_size') || 5);
460 for (my $i = 0; $i <= $#graphs; $i++) {
461 my $graph = $graphs[$i];
462 my $thumbfile = $cachedir . 'graphs/thumb_' . $$graph[0] . '.png';
464 if ( stat($thumbfile)->size() < $maxgraph ) {
466 # add graph to main file
467 my $graphhead = q(<H3>) . $$graph[1] . q(</H3>);
468 $svchtml .= $graphhead;
469 $svchtml .= anchor_tag( $svcnum, $$graph[0], img_tag($thumbfile) );
470 # create graph details file
471 my $graphhtml = $svchead . $graphhead;
474 while (-e (my $graphfile = $cachedir.'graphs/graph_'.$$graph[0].'_'.$j.'.png')) {
475 if ( stat($graphfile)->size() < $maxgraph ) {
477 $graphhtml .= img_tag($graphfile);
482 $graphhtml .= '<P>No detail graphs to display for this graph</P>'
484 my $newobj = new FS::cacti_page {
485 'exportnum' => $self->exportnum,
487 'graphnum' => $$graph[0],
489 'content' => $graphhtml,
491 $error = $newobj->insert;
493 $dbh->rollback if $oldAutoCommit;
499 $job->update_statustext(49 + int($i / @graphs) * 50);
501 $svchtml .= '<P>No graphs to display for this service</P>'
503 my $newobj = new FS::cacti_page {
504 'exportnum' => $self->exportnum,
508 'content' => $svchtml,
510 $error = $newobj->insert;
512 $dbh->rollback if $oldAutoCommit;
516 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
518 $job->update_statustext(100);
523 my $somefile = shift;
524 return q(<IMG SRC="data:image/png;base64,)
525 . encode_base64(slurp($somefile,binmode=>':raw'),'')
526 . qq(" STYLE="margin-bottom: 1em;"><BR>);
530 my ($svcnum, $graphnum, $contents) = @_;
531 return q(<A HREF="?svcnum=)
540 #this gets used by everything else
541 #fake false laziness, other ssh_cmds handle error/output differently
545 my $ssh = Net::OpenSSH->new($opt->{'user'}.'@'.$opt->{'host'});
546 die "Couldn't establish SSH connection: ". $ssh->error if $ssh->error;
547 my ($output, $errput) = $ssh->capture2($opt->{'command'});
548 die "Error running SSH command: ". $opt->{'command'}. ' ERROR: ' . $ssh->error if $ssh->error;
549 die $errput if $errput;
559 Removes all expired graphs for this export from the database.
565 my $oldAutoCommit = $FS::UID::AutoCommit;
566 local $FS::UID::AutoCommit = 0;
568 my $sth = $dbh->prepare('DELETE FROM cacti_page WHERE exportnum = ? and imported <= ?')
570 $dbh->rollback if $oldAutoCommit;
573 $sth->execute($self->exportnum,$self->exptime)
575 $dbh->rollback if $oldAutoCommit;
578 $dbh->commit or return $dbh->errstr if $oldAutoCommit;
582 =item exptime [ TIME ]
584 Accepts optional current time, defaults to actual current time.
586 Returns timestamp for the oldest possible non-expired graph import,
587 based on the import_freq option.
593 my $now = shift || time;
594 return $now - 60 * ($self->option('import_freq') || 5);
602 jonathan@freeside.biz
604 =head1 LICENSE AND COPYRIGHT
606 Copyright 2015 Freeside Internet Services
608 This program is free software; you can redistribute it and/or
609 modify it under the terms of the GNU General Public License
610 as published by the Free Software Foundation.