2b989a0b0c5c6f3cbb0b25aa0395c466a759b77c
[freeside.git] / FS / FS / part_export / cacti.pm
1 package FS::part_export::cacti;
2
3 =pod
4
5 =head1 NAME
6
7 FS::part_export::cacti
8
9 =head1 SYNOPSIS
10
11 Cacti integration for Freeside
12
13 =head1 DESCRIPTION
14
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.
17
18 =cut
19
20 use strict;
21
22 use base qw( FS::part_export );
23 use FS::Record qw( qsearchs qsearch );
24 use FS::UID qw( dbh );
25 use FS::cacti_page;
26
27 use File::Rsync;
28 use File::Slurp qw( slurp );
29 use File::stat;
30 use MIME::Base64 qw( encode_base64 );
31
32 use vars qw( %info );
33
34 my $php = 'php -q ';
35
36 tie my %options, 'Tie::IxHash',
37   'user'              => { label   => 'User Name',
38                            default => 'freeside' },
39   'script_path'       => { label   => 'Script Path',
40                            default => '/usr/share/cacti/cli/' },
41   'template_id'       => { label   => 'Host Template ID',
42                            default => '' },
43   'tree_id'           => { label   => 'Graph Tree ID (optional)',
44                            default => '' },
45   'description'       => { label   => 'Description (can use tokens $contact, $ip_addr and $description)',
46                            default => 'Freeside $contact $description $ip_addr' },
47   'graphs_path'       => { label   => 'Graph Export Directory (user@host:/path/to/graphs/)',
48                            default => '' },
49   'import_freq'       => { label   => 'Minimum minutes between graph imports',
50                            default => '5' },
51   'max_graph_size'    => { label   => 'Maximum size per graph (MB)',
52                            default => '5' },
53   'delete_graphs'     => { label   => 'Delete associated graphs and data sources when unprovisioning', 
54                            type    => 'checkbox',
55                          },
56   'include_path'      => { label   => 'Path to cacti include dir (relative to script_path)',
57                            default => '../site/include/' },
58   'cacti_graph_template_id'  => { 
59     'label'    => 'Graph Template',
60     'type'     => 'custom',
61     'multiple' => 1,
62   },
63   'cacti_snmp_query_id'      => { 
64     'label'    => 'SNMP Query ID',
65     'type'     => 'custom',
66     'multiple' => 1,
67   },
68   'cacti_snmp_query_type_id' => { 
69     'label'    => 'SNMP Query Type ID',
70     'type'     => 'custom',
71     'multiple' => 1,
72   },
73   'cacti_snmp_field'         => { 
74     'label'    => 'SNMP Field',
75     'type'     => 'custom',
76     'multiple' => 1,
77   },
78   'cacti_snmp_value'         => { 
79     'label'    => 'SNMP Value',
80     'type'     => 'custom',
81     'multiple' => 1,
82   },
83 ;
84
85 %info = (
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,
90   'notes'                => <<'END',
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.
93 END
94 );
95
96 # standard hooks for provisioning/unprovisioning service
97
98 sub _export_insert {
99   my ($self, $svc_broadband) = @_;
100   my ($q,$error) = _insert_queue($self, $svc_broadband);
101   return $error;
102 }
103
104 sub _export_delete {
105   my ($self, $svc_broadband) = @_;
106   my $oldAutoCommit = $FS::UID::AutoCommit;
107   local $FS::UID::AutoCommit = 0;
108   my $dbh = dbh;
109   foreach my $page (qsearch('cacti_page',{ svcnum => $svc_broadband->svcnum })) {
110     my $error = $page->delete;
111     if ($error) {
112       $dbh->rollback if $oldAutoCommit;
113       return $error;
114     }
115   }
116   my ($q,$error) = _delete_queue($self, $svc_broadband);
117   if ($error) {
118     $dbh->rollback if $oldAutoCommit;
119     return $error;
120   }
121   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
122   return '';
123 }
124
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;
131   my $dbh = dbh;
132   my ($dq, $iq, $error);
133   ($dq,$error) = _delete_queue($self,$old);
134   if ($error) {
135     $dbh->rollback if $oldAutoCommit;
136     return $error;
137   }
138   ($iq,$error) = _insert_queue($self,$new);
139   if ($error) {
140     $dbh->rollback if $oldAutoCommit;
141     return $error;
142   }
143   $error = $iq->depend_insert($dq->jobnum);
144   if ($error) {
145     $dbh->rollback if $oldAutoCommit;
146     return $error;
147   }
148   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
149   return '';
150 }
151
152 sub _export_suspend {
153   return '';
154 }
155
156 sub _export_unsuspend {
157   return '';
158 }
159
160 # create queued jobs
161
162 sub _insert_queue {
163   my ($self, $svc_broadband) = @_;
164   my $queue = new FS::queue {
165     'svcnum' => $svc_broadband->svcnum,
166     'job'    => "FS::part_export::cacti::ssh_insert",
167   };
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,
179     'self'        => $self
180   );
181   return ($queue,$error);
182 }
183
184 sub _delete_queue {
185   my ($self, $svc_broadband) = @_;
186   my $queue = new FS::queue {
187     'svcnum' => $svc_broadband->svcnum,
188     'job'    => "FS::part_export::cacti::ssh_delete",
189   };
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'),
196     'include_path'  => $self->option('include_path'),
197   );
198   return ($queue,$error);
199 }
200
201 # routines run by queued jobs
202
203 sub ssh_insert {
204   my %opt = @_;
205   my $self = $opt{'self'};
206
207   # Option validation
208   die "Non-numerical Host Template ID, check export configuration\n"
209     unless $opt{'template_id'} =~ /^\d+$/;
210   die "Non-numerical Graph Tree ID, check export configuration\n"
211     unless $opt{'tree_id'} =~ /^\d*$/;
212
213   # Add host to cacti
214   my $desc = $opt{'description'};
215   $desc =~ s/\$ip_addr/$opt{'hostname'}/g;
216   $desc =~ s/\$description/$opt{'svc_desc'}/g;
217   $desc =~ s/\$contact/$opt{'contact'}/g;
218 #for some reason, device names with apostrophes fail to export graphs in Cacti
219 #just removing them for now, someday maybe dig to figure out why
220 #  $desc =~ s/'/'\\''/g;
221   $desc =~ s/'//g;
222   my $cmd = $php
223           . trailslash($opt{'script_path'})
224           . q(add_device.php --description=')
225           . $desc
226           . q(' --ip=')
227           . $opt{'hostname'}
228           . q(' --template=)
229           . $opt{'template_id'};
230   my $response = ssh_cmd(%opt, 'command' => $cmd);
231   unless ( $response =~ /Success - new device-id: \((\d+)\)/ ) {
232     die "Error adding device: $response";
233   }
234   my $id = $1;
235
236   # Add host to tree
237   if ($opt{'tree_id'}) {
238     $cmd = $php
239          . trailslash($opt{'script_path'})
240          . q(add_tree.php --type=node --node-type=host --tree-id=)
241          . $opt{'tree_id'}
242          . q( --host-id=)
243          . $id;
244     $response = ssh_cmd(%opt, 'command' => $cmd);
245     unless ( $response =~ /Added Node node-id: \((\d+)\)/ ) {
246       die "Host added, but error adding host to tree: $response";
247     }
248   }
249
250   # Get list of graph templates for new id
251   $cmd = $php
252        . trailslash($opt{'script_path'}) 
253        . q(freeside_cacti.php --get-graph-templates --host-template=)
254        . $opt{'template_id'};
255   $cmd .= q( --include-path=') . $self->option('include_path') . q(')
256     if $self->option('include_path');
257   my $ginfo = { map { $_ ? ($_ => undef) : () } split(/\n/,ssh_cmd(%opt, 'command' => $cmd)) };
258
259   # Add extra config info
260   my @xtragid = split("\n", $self->option('cacti_graph_template_id'));
261   my @query_id = split("\n", $self->option('cacti_snmp_query_id'));
262   my @query_type_id = split("\n", $self->option('cacti_snmp_query_type_id'));
263   my @snmp_field = split("\n", $self->option('cacti_snmp_field'));
264   my @snmp_value = split("\n", $self->option('cacti_snmp_value'));
265   for (my $i = 0; $i < @xtragid; $i++) {
266     my $gtid = $xtragid[$i];
267     $ginfo->{$gtid} ||= [];
268     push(@{$ginfo->{$gtid}},{
269       'gtid'          => $gtid,
270       'query_id'      => $query_id[$i],
271       'query_type_id' => $query_type_id[$i],
272       'snmp_field'    => $snmp_field[$i],
273       'snmp_value'    => $snmp_value[$i],
274     });
275   }
276
277   my @gdefs = map {
278     ref($ginfo->{$_}) ? @{$ginfo->{$_}} : {'gtid' => $_}
279   } keys %$ginfo;
280   warn "Host ".$opt{'hostname'}." exported to cacti, but no graphs configured"
281     unless @gdefs;
282
283   # Create graphs
284   my $gerror = '';
285   foreach my $gdef (@gdefs) {
286     # validate graph info
287     my $gtid = $gdef->{'gtid'};
288     next unless $gtid;
289     $gerror .= " Bad graph template: $gtid"
290       unless $gtid =~ /^\d+$/;
291     my $isds = $gdef->{'query_id'} 
292             || $gdef->{'query_type_id'} 
293             || $gdef->{'snmp_field'} 
294             || $gdef->{'snmp_value'};
295     if ($isds) {
296       $gerror .= " Bad SNMP Query Id: " . $gdef->{'query_id'}
297         unless $gdef->{'query_id'} =~ /^\d+$/;
298       $gerror .= " Bad SNMP Query Type Id: " . $gdef->{'query_type_id'}
299         unless $gdef->{'query_type_id'} =~ /^\d+$/;
300       $gerror .= " SNMP Field cannot contain apostrophe"
301         if $gdef->{'snmp_field'} =~ /'/;
302       $gerror .= " SNMP Value cannot contain apostrophe"
303         if $gdef->{'snmp_value'} =~ /'/;
304     }
305     next if $gerror;
306
307     # create the graph
308     $cmd = $php
309          . trailslash($opt{'script_path'})
310          . q(add_graphs.php --graph-type=)
311          . ($isds ? 'ds' : 'cg')
312          . q( --graph-template-id=)
313          . $gtid
314          . q( --host-id=)
315          . $id;
316     if ($isds) {
317       $cmd .= q( --snmp-query-id=)
318            .  $gdef->{'query_id'}
319            .  q( --snmp-query-type-id=)
320            .  $gdef->{'query_type_id'}
321            .  q( --snmp-field=')
322            .  $gdef->{'snmp_field'}
323            .  q(' --snmp-value=')
324            .  $gdef->{'snmp_value'}
325            .  q(');
326     }
327     $response = ssh_cmd(%opt, 'command' => $cmd);
328     #might be more than one graph added, just testing success
329     $gerror .= "Error creating graph $gtid: $response"
330       unless $response =~ /Graph Added - graph-id: \((\d+)\)/;
331
332   } #foreach $gtid
333
334   # job fails, but partial export may have occurred
335   die $gerror . " Partial export occurred\n" if $gerror;
336
337   return '';
338 }
339
340 sub ssh_delete {
341   my %opt = @_;
342   my $cmd = $php
343           . trailslash($opt{'script_path'}) 
344           . q(freeside_cacti.php --drop-device --ip=')
345           . $opt{'hostname'}
346           . q(');
347   $cmd .= q( --delete-graphs)
348     if $opt{'delete_graphs'};
349   $cmd .= q( --include-path=') . $opt{'include_path'} . q(')
350     if $opt{'include_path'};
351   my $response = ssh_cmd(%opt, 'command' => $cmd);
352   die "Error removing from cacti: " . $response
353     if $response;
354   return '';
355 }
356
357 =head1 SUBROUTINES
358
359 =over 4
360
361 =item process_graphs JOB PARAM
362
363 Intended to be run as an FS::queue job.
364
365 Copies graphs for a single service from Cacti export directory to FS cache,
366 generates basic html pages for this service with base64-encoded graphs embedded, 
367 and stores the generated pages in the database.
368
369 =back
370
371 =cut
372
373 sub process_graphs {
374   my ($job,$param) = @_;
375
376   $job->update_statustext(10);
377   my $cachedir = trailslash($FS::UID::cache_dir,'cache.'.$FS::UID::datasrc,'cacti-graphs');
378
379   # load the service
380   my $svcnum = $param->{'svcnum'} || die "No svcnum specified";
381   my $svc = qsearchs({
382    'table'   => 'svc_broadband',
383    'hashref' => { 'svcnum' => $svcnum },
384   }) || die "Could not load svcnum $svcnum";
385
386   # load relevant FS::part_export::cacti object
387   my ($self) = $svc->cust_svc->part_svc->part_export('cacti');
388
389   $job->update_statustext(20);
390
391   my $oldAutoCommit = $FS::UID::AutoCommit;
392   local $FS::UID::AutoCommit = 0;
393   my $dbh = dbh;
394
395   # check for existing pages
396   my $now = time;
397   my @oldpages = qsearch({
398     'table'    => 'cacti_page',
399     'hashref'  => { 'svcnum' => $svcnum, 'exportnum' => $self->exportnum },
400     'select'   => 'cacti_pagenum, exportnum, svcnum, graphnum, imported', #no need to load old content
401     'order_by' => 'ORDER BY graphnum',
402   });
403   if (@oldpages) {
404     #if pages are recent enough, do nothing and return
405     if ($oldpages[0]->imported > $self->exptime($now)) {
406       $job->update_statustext(100);
407       return '';
408     }
409     #delete old pages
410     foreach my $oldpage (@oldpages) {
411       my $error = $oldpage->delete;
412       if ($error) {
413         $dbh->rollback if $oldAutoCommit;
414         die $error;
415       }
416     }
417   }
418
419   $job->update_statustext(30);
420
421   # get list of graphs for this svc from cacti server
422   my $cmd = $php
423           . trailslash($self->option('script_path'))
424           . q(freeside_cacti.php --get-graphs --ip=')
425           . $svc->ip_addr
426           . q(');
427   $cmd .= q( --include-path=') . $self->option('include_path') . q(')
428     if $self->option('include_path');
429   my @graphs = map { [ split(/\t/,$_) ] } 
430                  split(/\n/, ssh_cmd(
431                    'host'          => $self->machine,
432                    'user'          => $self->option('user'),
433                    'command'       => $cmd
434                  ));
435
436   $job->update_statustext(40);
437
438   # copy graphs from cacti server to cache
439   # requires version 2.6.4 of rsync, released March 2005
440   my $rsync = File::Rsync->new({
441     'rsh'       => 'ssh',
442     'verbose'   => 1,
443     'recursive' => 1,
444     'quote-src' => 1,
445     'quote-dst' => 1,
446     'source'    => trailslash($self->option('graphs_path')),
447     'dest'      => $cachedir,
448     'include'   => [
449       (map { q('**graph_).${$_}[0].q(*.png') } @graphs),
450       (map { q('**thumb_).${$_}[0].q(.png') } @graphs),
451       q('*/'),
452       q('- *'),
453     ],
454   });
455   #don't know why a regular $rsync->exec isn't doing includes right, but this does
456   my $rscmd = join(' ',@{$rsync->getcmd()});
457   my $error = system($rscmd);
458   die "rsync ($rscmd) failed with exit status $error" if $error;
459
460   $job->update_statustext(50);
461
462   # create html file contents
463   my $svchead = q(<!-- UPDATED ) . $now . qq( -->)
464               . '<H2 STYLE="margin-top: 0;">Service #' . $svcnum . '</H2>'
465               . q(<P>Last updated ) . scalar(localtime($now)) . q(</P>);
466   my $svchtml = $svchead;
467   my $maxgraph = 1024 * 1024 * ($self->options('max_graph_size') || 5);
468   my $nographs = 1;
469   for (my $i = 0; $i <= $#graphs; $i++) {
470     my $graph = $graphs[$i];
471     my $thumbfile = $cachedir . 'graphs/thumb_' . $$graph[0] . '.png';
472     if (-e $thumbfile) {
473       if ( stat($thumbfile)->size() < $maxgraph ) {
474         $nographs = 0;
475         # add graph to main file
476         my $graphhead = q(<H3>) . $$graph[1] . q(</H3>);
477         $svchtml .= $graphhead;
478         $svchtml .= anchor_tag( $svcnum, $$graph[0], img_tag($thumbfile) );
479         # create graph details file
480         my $graphhtml = $svchead . $graphhead;
481         my $nodetail = 1;
482         my $j = 1;
483         while (-e (my $graphfile = $cachedir.'graphs/graph_'.$$graph[0].'_'.$j.'.png')) {
484           if ( stat($graphfile)->size() < $maxgraph ) {
485             $nodetail = 0;
486             $graphhtml .= img_tag($graphfile);
487           }
488           unlink($graphfile);
489           $j++;
490         }
491         $graphhtml .= '<P>No detail graphs to display for this graph</P>'
492           if $nodetail;
493         my $newobj = new FS::cacti_page {
494           'exportnum' => $self->exportnum,
495           'svcnum'    => $svcnum,
496           'graphnum'  => $$graph[0],
497           'imported'  => $now,
498           'content'   => $graphhtml,
499         };
500         $error = $newobj->insert;
501         if ($error) {
502           $dbh->rollback if $oldAutoCommit;
503           die $error;
504         }
505       } else {
506         $svchtml .= qq(<P STYLE="color: #FF0000">File $thumbfile is too large, skipping</P>);
507       }
508       unlink($thumbfile);
509     } else {
510       $svchtml .= qq(<P STYLE="color: #FF0000">Error loading graph: $$graph[0]</P>);
511     }
512     $job->update_statustext(49 + int($i / @graphs) * 50);
513   }
514   $svchtml .= '<P>No graphs to display for this service</P>'
515     if $nographs;
516   my $newobj = new FS::cacti_page {
517     'exportnum' => $self->exportnum,
518     'svcnum'    => $svcnum,
519     'graphnum'  => '',
520     'imported'  => $now,
521     'content'   => $svchtml,
522   };
523   $error  = $newobj->insert;
524   if ($error) {
525     $dbh->rollback if $oldAutoCommit;
526     die $error;
527   }
528
529   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
530
531   $job->update_statustext(100);
532   return '';
533 }
534
535 sub img_tag {
536   my $somefile = shift;
537   return q(<IMG SRC="data:image/png;base64,)
538        . encode_base64(slurp($somefile,binmode=>':raw'),'')
539        . qq(" STYLE="margin-bottom: 1em;"><BR>);
540 }
541
542 sub anchor_tag {
543   my ($svcnum, $graphnum, $contents) = @_;
544   return q(<A HREF="?svcnum=)
545        . $svcnum
546        . q(&graphnum=)
547        . $graphnum
548        . q(">)
549        . $contents
550        . q(</A>);
551 }
552
553 #this gets used by everything else
554 #fake false laziness, other ssh_cmds handle error/output differently
555 sub ssh_cmd {
556   use Net::OpenSSH;
557   my $opt = { @_ };
558   my $ssh = Net::OpenSSH->new($opt->{'user'}.'@'.$opt->{'host'});
559   die "Couldn't establish SSH connection: ". $ssh->error if $ssh->error;
560   my ($output, $errput) = $ssh->capture2($opt->{'command'});
561   die "Error running SSH command: ". $opt->{'command'}. ' ERROR: ' . $ssh->error if $ssh->error;
562   die $errput if $errput;
563   return $output;
564 }
565
566 #there's probably a better place to put this?
567 #makes sure there's a trailing slash between/after input
568 #doesn't add leading slashes
569 sub trailslash {
570   my @paths = @_;
571   my $out = '';
572   foreach my $path (@paths) {
573     $out .= $path;
574     $out .= '/' unless $out =~ /\/$/;
575   }
576   return $out;
577 }
578
579 =head1 METHODS
580
581 =over 4
582
583 =item cleanup
584
585 Removes all expired graphs for this export from the database.
586
587 =cut
588
589 sub cleanup {
590   my $self = shift;
591   my $oldAutoCommit = $FS::UID::AutoCommit;
592   local $FS::UID::AutoCommit = 0;
593   my $dbh = dbh;
594   my $sth = $dbh->prepare('DELETE FROM cacti_page WHERE exportnum = ? and imported <= ?') 
595     or do {
596       $dbh->rollback if $oldAutoCommit;
597       return $dbh->errstr;
598     };
599   $sth->execute($self->exportnum,$self->exptime)
600     or do {
601       $dbh->rollback if $oldAutoCommit;
602       return $dbh->errstr;
603     };
604   $dbh->commit or return $dbh->errstr if $oldAutoCommit;
605   return '';
606 }
607
608 =item exptime [ TIME ]
609
610 Accepts optional current time, defaults to actual current time.
611
612 Returns timestamp for the oldest possible non-expired graph import,
613 based on the import_freq option.
614
615 =cut
616
617 sub exptime {
618   my $self = shift;
619   my $now = shift || time;
620   return $now - 60 * ($self->option('import_freq') || 5);
621 }
622
623 =back
624
625 =head1 AUTHOR
626
627 Jonathan Prykop 
628 jonathan@freeside.biz
629
630 =cut
631
632 1;
633
634