summaryrefslogtreecommitdiff
path: root/FS/FS/svc_port.pm
blob: db1f539b882bf92d7293663a61ba210c9f633a30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package FS::svc_port;

use strict;
use vars qw($conf $system $DEBUG $me );
use base qw( FS::svc_Common );
use FS::UID qw( driver_name );
use FS::Record qw( qsearch qsearchs
                   str2time_sql str2time_sql_closing concat_sql );
use FS::cust_svc;
use GD::Graph;
use GD::Graph::mixed;
use Date::Format qw(time2str);
use Data::Dumper;

$DEBUG = 1;
$me = '[FS::svc_port]';

FS::UID->install_callback( sub { 
  $conf = new FS::Conf;
  $system = $conf->config('network_monitoring_system');
} );

=head1 NAME

FS::svc_port - Object methods for svc_port records

=head1 SYNOPSIS

  use FS::svc_port;

  $record = new FS::svc_port \%hash;
  $record = new FS::svc_port { 'column' => 'value' };

  $error = $record->insert;

  $error = $new_record->replace($old_record);

  $error = $record->delete;

  $error = $record->check;

  $error = $record->suspend;

  $error = $record->unsuspend;

  $error = $record->cancel;

=head1 DESCRIPTION

An FS::svc_port object represents a router port.  FS::table_name inherits from
FS::svc_Common.  The following fields are currently supported:

=over 4

=item svcnum - 

=item serviceid - Torrus serviceid (in srvexport and reportfields tables)

=back

=head1 METHODS

=over 4

=item new HASHREF

Creates a new port.  To add the port to the database, see L<"insert">.

Note that this stores the hash reference, not a distinct copy of the hash it
points to.  You can ask the object for a copy with the I<hash> method.

=cut

sub table { 'svc_port'; }

sub table_info {
  {
    'name' => 'Port',
    #'name_plural' => 'Ports', #optional,
    #'longname_plural' => 'Ports', #optional
    'sorts' => [ 'svcnum', 'serviceid' ], # optional sort field (or arrayref of sort fields, main first)
    'display_weight' => 75,
    'cancel_weight'  => 10,
    'fields' => {
      'serviceid'         => 'Torrus serviceid',
    },
  };
}

=item search_sql STRING

Class method which returns an SQL fragment to search for the given string.

=cut

#or something more complicated if necessary
sub search_sql {
  my($class, $string) = @_;
  $class->search_sql_field('serviceid', $string);
}

=item label

Returns a meaningful identifier for this port

=cut

sub label {
  my $self = shift;
  $self->serviceid; #or something more complicated if necessary
}

=item insert

Adds this record to the database.  If there is an error, returns the error,
otherwise returns false.

The additional fields pkgnum and svcpart (see L<FS::cust_svc>) should be 
defined.  An FS::cust_svc record will be created and inserted.

=cut

sub insert {
  my $self = shift;
  my $error;

  $error = $self->SUPER::insert;
  return $error if $error;

  '';
}

=item delete

Delete this record from the database.

=cut

sub delete {
  my $self = shift;
  my $error;

  $error = $self->SUPER::delete;
  return $error if $error;

  '';
}


=item replace OLD_RECORD

Replaces the OLD_RECORD with this one in the database.  If there is an error,
returns the error, otherwise returns false.

=cut

sub replace {
  my ( $new, $old ) = ( shift, shift );
  my $error;

  $error = $new->SUPER::replace($old);
  return $error if $error;

  '';
}

=item suspend

Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).

=item unsuspend

Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).

=item cancel

Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).

=item check

Checks all fields to make sure this is a valid port.  If there is
an error, returns the error, otherwise returns false.  Called by the insert
and repalce methods.

=cut

sub check {
  my $self = shift;

  my $x = $self->setfixed;
  return $x unless ref($x);
  my $part_svc = $x;

  my $error = $self->ut_textn('serviceid'); #too lenient?
  return $error if $error;

  $self->SUPER::check;
}

=item graph_png

Returns a PNG graph for this port.

The following options must be specified:

=over 4

=item start
=item end

=back

=cut

sub _format_bandwidth {
    my $self = shift;
    my $value = shift;
    my $space = shift;
    $space = ' ' if $space;

    my $suffix = '';

    warn "$me _format_bandwidth $value" if $DEBUG > 1;

    if ( $value >= 1000 && $value < 1000000 ) {
        $value = ($value/1000);
        $suffix = $space. "k";
    }
    elsif( $value >= 1000000 && $value < 1000000000 ) {
        $value = ($value/1000/1000);
        $suffix = $space . "M";
    }
    elsif( $value >= 1000000000 && $value < 1000000000000 ) {
        $value = ($value/1000/1000/1000);
        $suffix = $space . "G";
    }
    # and hopefully we don't have folks doing Tbps on a single port :)

    $value = sprintf("%.2f$suffix",$value) if $value >= 0;

    $value;
}

sub graph_png {
  my($self, %opt) = @_;
  my $serviceid = $self->serviceid;

  if($serviceid && $system eq 'Torrus_Internal') {
      my $start = -1;
      my $end = -1;
        my $now = time;

        $start = $opt{start} if $opt{start};
        $end = $opt{end} if $opt{end};

        return 'Invalid date range' if ($start < 0 || $start >= $end 
            || $end <= $start || $end < 0 || $end > $now || $start > $now
            || $end-$start > 86400*366 );

        my $_date = concat_sql([ 'srv_date', "' '", 'srv_time' ]);
        $_date = "CAST( $_date AS TIMESTAMP )" if driver_name =~ /^Pg/i;
        $_date = str2time_sql. $_date.  str2time_sql_closing;

        my $serviceid_sql = "('${serviceid}_IN','${serviceid}_OUT')";

        local($FS::Record::nowarn_classload) = 1;
        my @records = qsearch({
          'table'     => 'srvexport',
          'select'    => "*, $_date as _date",
          'extra_sql' => "where serviceid in $serviceid_sql
                            and $_date >= $start
                            and $_date <= $end",
          'order_by'  => "order by $_date asc",
        });

        if ( ! scalar(@records) ) {
          warn "$me no records returned for $serviceid\n";
          return ''; #should actually return a blank png (or, even better, the
                     # error message in the image)
        }

        warn "$me ". scalar(@records). " records returned for $serviceid\n"
          if $DEBUG;

        # assume data in DB is correct,
        # assume always _IN and _OUT pair, assume intvl = 300

        my @times;
        my @in;
        my @out;
        foreach my $rec ( @records ) {
            push @times, $rec->_date 
                unless grep { $_ eq $rec->_date } @times;
            push @in, $rec->value if $rec->serviceid =~ /_IN$/;
            push @out, $rec->value if $rec->serviceid =~ /_OUT$/;
        }

        my $timediff = $times[-1] - $times[0]; # they're sorted ascending

        my $y_min = 999999999999; # ~1Tbps
        my $y_max = 0;
        my $in_sum = 0;
        my $out_sum = 0;
        my $in_min = 999999999999;
        my $in_max = 0;
        my $out_min = 999999999999;
        my $out_max = 0;
        foreach my $in ( @in ) {
            $y_max = $in if $in > $y_max;
            $y_min = $in if $in < $y_min;
            $in_sum += $in;
            $in_max = $in if $in > $in_max;
            $in_min = $in if $in < $in_min;
        }
        foreach my $out ( @out ) {
            $y_max = $out if $out > $y_max;
            $y_min = $out if $out < $y_min;
            $out_sum += $out;
            $out_max = $out if $out > $out_max;
            $out_min = $out if $out < $out_min;
        }
        my $bwdiff = $y_max - $y_min;
        $in_min = $self->_format_bandwidth($in_min);
        $out_min = $self->_format_bandwidth($out_min);
        $in_max = $self->_format_bandwidth($in_max);
        $out_max = $self->_format_bandwidth($out_max);
        my $in_curr = $self->_format_bandwidth($in[-1]);
        my $out_curr = $self->_format_bandwidth($out[-1]);
        my $numsamples = scalar(@records)/2;
        my $in_avg = $self->_format_bandwidth($in_sum/$numsamples);
        my $out_avg = $self->_format_bandwidth($out_sum/$numsamples);

      warn "$me timediff=$timediff bwdiff=$bwdiff start=$start end=$end "
            . "in_min=$in_min out_min=$out_min in_max=$in_max "
            . "out_max=$out_max in_avg=$in_avg out_avg=$out_avg "
            . " # records = " . scalar(@records) . "\n\ntimes:\n" 
            . Dumper(@times) . "\n\nin:\n" . Dumper(@in) . "\n\nout:\n"
            . Dumper(@out) if $DEBUG > 1;

      my @data = ( \@times, \@in, \@out );

      # hardcoded size, colour, etc.
      my $graph = new GD::Graph::mixed(600,320);  #600,400
      $graph->set(
        types => ['area','lines'],
        dclrs => ['green','blue'],
        x_label => "(In Out)  Current: $in_curr $out_curr  Average: $in_avg $out_avg  Maximum: $in_max $out_max  Minimum: $in_min $out_min",
        x_tick_number => 'auto',
        x_number_format => sub {
            my $value = shift;
            if ( $timediff < 86401 ) { # one day
                $value = time2str("%a %H:%M",$value) 
            } elsif ( $timediff < 86401*7 ) { # one week
                $value = time2str("%d",$value) 
            } elsif ( $timediff < 86401*30 ) { # one month
                $value = time2str("Week %U",$value) 
            } elsif ( $timediff < 86401*366 ) { # one year
                $value = time2str("%b",$value)
            }
            $value;
        },
        y_number_format => sub {
            my $value = shift;
            $self->_format_bandwidth($value,1);
        },
        y_label => 'bps',
        legend_placement => 'BR',
        title => $self->serviceid,
      ) or return "can't create graph: ".$graph->error;
      
      $graph->set_text_clr('black') 
        or return "can't set text colour: ".$graph->error;
      $graph->set_legend(('In','Out')) 
        or return "can't set legend: ".$graph->error;

      my $gd = $graph->plot(\@data);
      return "graph error: ".$graph->error unless($gd);
      return $gd->png;
  }

  '';
}

=back

=head1 BUGS

=head1 SEE ALSO

L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
L<FS::cust_pkg>, schema.html from the base documentation.

=cut

1;