cfd71b241dd460628f753cd984088d8e673a37fd
[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( decode_base64 encode_base64 );
31 use Storable qw(thaw);
32
33
34 use vars qw( %info );
35
36 my $php = 'php -q ';
37
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',
44                            default => '' },
45   'tree_id'           => { label   => 'Graph Tree ID (optional)',
46                            default => '' },
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/)',
50                            default => '' },
51   'import_freq'       => { label   => 'Minimum minutes between graph imports',
52                            default => '5' },
53   'max_graph_size'    => { label   => 'Maximum size per graph (MB)',
54                            default => '5' },
55   'delete_graphs'     => { label   => 'Delete associated graphs and data sources when unprovisioning', 
56                            type    => 'checkbox',
57                          },
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   );
197   return ($queue,$error);
198 }
199
200 # routines run by queued jobs
201
202 sub ssh_insert {
203   my %opt = @_;
204   my $self = $opt{'self'};
205
206   # Option validation
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*$/;
211
212   # Add host to cacti
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;
220   $desc =~ s/'//g;
221   my $cmd = $php
222           . $opt{'script_path'} 
223           . q(add_device.php --description=')
224           . $desc
225           . q(' --ip=')
226           . $opt{'hostname'}
227           . q(' --template=)
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";
232   }
233   my $id = $1;
234
235   # Add host to tree
236   if ($opt{'tree_id'}) {
237     $cmd = $php
238          . $opt{'script_path'}
239          . q(add_tree.php --type=node --node-type=host --tree-id=)
240          . $opt{'tree_id'}
241          . q( --host-id=)
242          . $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";
246     }
247   }
248
249   # Get list of graph templates for new id
250   $cmd = $php
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)) };
255
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}},{
266       'gtid'          => $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],
271     });
272   }
273
274   my @gdefs = map {
275     ref($ginfo->{$_}) ? @{$ginfo->{$_}} : {'gtid' => $_}
276   } keys %$ginfo;
277   warn "Host ".$opt{'hostname'}." exported to cacti, but no graphs configured"
278     unless @gdefs;
279
280   # Create graphs
281   my $gerror = '';
282   foreach my $gdef (@gdefs) {
283     # validate graph info
284     my $gtid = $gdef->{'gtid'};
285     next unless $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'};
292     if ($isds) {
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'} =~ /'/;
301     }
302     next if $gerror;
303
304     # create the graph
305     $cmd = $php
306          . $opt{'script_path'}
307          . q(add_graphs.php --graph-type=)
308          . ($isds ? 'ds' : 'cg')
309          . q( --graph-template-id=)
310          . $gtid
311          . q( --host-id=)
312          . $id;
313     if ($isds) {
314       $cmd .= q( --snmp-query-id=)
315            .  $gdef->{'query_id'}
316            .  q( --snmp-query-type-id=)
317            .  $gdef->{'query_type_id'}
318            .  q( --snmp-field=')
319            .  $gdef->{'snmp_field'}
320            .  q(' --snmp-value=')
321            .  $gdef->{'snmp_value'}
322            .  q(');
323     }
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+)\)/;
328
329   } #foreach $gtid
330
331   # job fails, but partial export may have occurred
332   die $gerror . " Partial export occurred\n" if $gerror;
333
334   return '';
335 }
336
337 sub ssh_delete {
338   my %opt = @_;
339   my $cmd = $php
340           . $opt{'script_path'} 
341           . q(freeside_cacti.php --drop-device --ip=')
342           . $opt{'hostname'}
343           . q(');
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
348     if $response;
349   return '';
350 }
351
352 =head1 SUBROUTINES
353
354 =over 4
355
356 =item process_graphs JOB PARAM
357
358 Intended to be run as an FS::queue job.
359
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.
363
364 =back
365
366 =cut
367
368 sub process_graphs {
369   my $job = shift;
370   my $param = thaw(decode_base64(shift));
371
372   $job->update_statustext(10);
373   my $cachedir = $FS::UID::cache_dir . '/cacti-graphs/';
374
375   # load the service
376   my $svcnum = $param->{'svcnum'} || die "No svcnum specified";
377   my $svc = qsearchs({
378    'table'   => 'svc_broadband',
379    'hashref' => { 'svcnum' => $svcnum },
380   }) || die "Could not load svcnum $svcnum";
381
382   # load relevant FS::part_export::cacti object
383   my ($self) = $svc->cust_svc->part_svc->part_export('cacti');
384
385   $job->update_statustext(20);
386
387   my $oldAutoCommit = $FS::UID::AutoCommit;
388   local $FS::UID::AutoCommit = 0;
389   my $dbh = dbh;
390
391   # check for existing pages
392   my $now = time;
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',
398   });
399   if (@oldpages) {
400     #if pages are recent enough, do nothing and return
401     if ($oldpages[0]->imported > $self->exptime($now)) {
402       $job->update_statustext(100);
403       return '';
404     }
405     #delete old pages
406     foreach my $oldpage (@oldpages) {
407       my $error = $oldpage->delete;
408       if ($error) {
409         $dbh->rollback if $oldAutoCommit;
410         die $error;
411       }
412     }
413   }
414
415   $job->update_statustext(30);
416
417   # get list of graphs for this svc from cacti server
418   my $cmd = $php
419           . $self->option('script_path')
420           . q(freeside_cacti.php --get-graphs --ip=')
421           . $svc->ip_addr
422           . q(');
423   my @graphs = map { [ split(/\t/,$_) ] } 
424                  split(/\n/, ssh_cmd(
425                    'host'          => $self->machine,
426                    'user'          => $self->option('user'),
427                    'command'       => $cmd
428                  ));
429
430   $job->update_statustext(40);
431
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({
435     'rsh'       => 'ssh',
436     'verbose'   => 1,
437     'recursive' => 1,
438     'source'    => $self->option('graphs_path'),
439     'dest'      => $cachedir,
440     'include'   => [
441       (map { q('**graph_).${$_}[0].q(*.png') } @graphs),
442       (map { q('**thumb_).${$_}[0].q(.png') } @graphs),
443       q('*/'),
444       q('- *'),
445     ],
446   });
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;
450
451   $job->update_statustext(50);
452
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);
459   my $nographs = 1;
460   for (my $i = 0; $i <= $#graphs; $i++) {
461     my $graph = $graphs[$i];
462     my $thumbfile = $cachedir . 'graphs/thumb_' . $$graph[0] . '.png';
463     if (-e $thumbfile) {
464       if ( stat($thumbfile)->size() < $maxgraph ) {
465         $nographs = 0;
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;
472         my $nodetail = 1;
473         my $j = 1;
474         while (-e (my $graphfile = $cachedir.'graphs/graph_'.$$graph[0].'_'.$j.'.png')) {
475           if ( stat($graphfile)->size() < $maxgraph ) {
476             $nodetail = 0;
477             $graphhtml .= img_tag($graphfile);
478           }
479           unlink($graphfile);
480           $j++;
481         }
482         $graphhtml .= '<P>No detail graphs to display for this graph</P>'
483           if $nodetail;
484         my $newobj = new FS::cacti_page {
485           'exportnum' => $self->exportnum,
486           'svcnum'    => $svcnum,
487           'graphnum'  => $$graph[0],
488           'imported'  => $now,
489           'content'   => $graphhtml,
490         };
491         $error = $newobj->insert;
492         if ($error) {
493           $dbh->rollback if $oldAutoCommit;
494           die $error;
495         }
496       } else {
497         warn "File $thumbfile is too large, skipping";
498       }
499       unlink($thumbfile);
500     } else {
501       warn "File $thumbfile does not exist, skipping";
502     }
503     $job->update_statustext(49 + int($i / @graphs) * 50);
504   }
505   $svchtml .= '<P>No graphs to display for this service</P>'
506     if $nographs;
507   my $newobj = new FS::cacti_page {
508     'exportnum' => $self->exportnum,
509     'svcnum'    => $svcnum,
510     'graphnum'  => '',
511     'imported'  => $now,
512     'content'   => $svchtml,
513   };
514   $error  = $newobj->insert;
515   if ($error) {
516     $dbh->rollback if $oldAutoCommit;
517     die $error;
518   }
519
520   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
521
522   $job->update_statustext(100);
523   return '';
524 }
525
526 sub img_tag {
527   my $somefile = shift;
528   return q(<IMG SRC="data:image/png;base64,)
529        . encode_base64(slurp($somefile,binmode=>':raw'),'')
530        . qq(" STYLE="margin-bottom: 1em;"><BR>);
531 }
532
533 sub anchor_tag {
534   my ($svcnum, $graphnum, $contents) = @_;
535   return q(<A HREF="?svcnum=)
536        . $svcnum
537        . q(&graphnum=)
538        . $graphnum
539        . q(">)
540        . $contents
541        . q(</A>);
542 }
543
544 #this gets used by everything else
545 #fake false laziness, other ssh_cmds handle error/output differently
546 sub ssh_cmd {
547   use Net::OpenSSH;
548   my $opt = { @_ };
549   my $ssh = Net::OpenSSH->new($opt->{'user'}.'@'.$opt->{'host'});
550   die "Couldn't establish SSH connection: ". $ssh->error if $ssh->error;
551   my ($output, $errput) = $ssh->capture2($opt->{'command'});
552   die "Error running SSH command: ". $opt->{'command'}. ' ERROR: ' . $ssh->error if $ssh->error;
553   die $errput if $errput;
554   return $output;
555 }
556
557 =head1 METHODS
558
559 =over 4
560
561 =item cleanup
562
563 Removes all expired graphs for this export from the database.
564
565 =cut
566
567 sub cleanup {
568   my $self = shift;
569   my $oldAutoCommit = $FS::UID::AutoCommit;
570   local $FS::UID::AutoCommit = 0;
571   my $dbh = dbh;
572   my $sth = $dbh->prepare('DELETE FROM cacti_page WHERE exportnum = ? and imported <= ?') 
573     or do {
574       $dbh->rollback if $oldAutoCommit;
575       return $dbh->errstr;
576     };
577   $sth->execute($self->exportnum,$self->exptime)
578     or do {
579       $dbh->rollback if $oldAutoCommit;
580       return $dbh->errstr;
581     };
582   $dbh->commit or return $dbh->errstr if $oldAutoCommit;
583   return '';
584 }
585
586 =item exptime [ TIME ]
587
588 Accepts optional current time, defaults to actual current time.
589
590 Returns timestamp for the oldest possible non-expired graph import,
591 based on the import_freq option.
592
593 =cut
594
595 sub exptime {
596   my $self = shift;
597   my $now = shift || time;
598   return $now - 60 * ($self->option('import_freq') || 5);
599 }
600
601 =back
602
603 =head1 AUTHOR
604
605 Jonathan Prykop 
606 jonathan@freeside.biz
607
608 =head1 LICENSE AND COPYRIGHT
609
610 Copyright 2015 Freeside Internet Services      
611
612 This program is free software; you can redistribute it and/or 
613 modify it under the terms of the GNU General Public License 
614 as published by the Free Software Foundation.
615
616 =cut
617
618 1;
619
620