File: File.pm

package info (click to toggle)
cricket 1.0.5-23
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,940 kB
  • sloc: perl: 8,276; ansic: 329; sh: 162; makefile: 60; sql: 16
file content (481 lines) | stat: -rw-r--r-- 13,011 bytes parent folder | download | duplicates (5)
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# -*- perl -*-

# RRD::File: a package for digging around in RRD files from Perl
#
#    Copyright (C) 1998 Jeff R. Allen and WebTV Networks, Inc.
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

package RRD::File;

use strict;
use Carp;
use Config;
use FileHandle;
use RRD::Format;

$RRD::File::gErr = "";
$RRD::File::gArch = $Config{'archname'};

# field setters/getters (gets value if no args, sets value and
# returns old value if it does have an arg)

sub file { shift->_getAndSet('file', @_) };
sub fh { shift->_getAndSet('fh', @_) };
sub fmt { shift->_getAndSet('format', @_) };
sub ds_cnt { shift->_getAndSet('ds_cnt', @_) };
sub rra_cnt { shift->_getAndSet('rra_cnt', @_) };
sub pdp_step { shift->_getAndSet('pdp_step', @_) };
sub cdp_xff { shift->_getAndSet('cdp_xff', @_) };
sub last_up { shift->_getAndSet('last_up', @_) };
# this is file property rather than an architecture format property
sub version { shift->_getAndSet('version', @_) };

sub _getAndSet {
    my($self, $field, $value) = @_;
    my($retval) = $self->{$field};
    $self->{$field} = $value if ($#_ >= 2);
    return $retval;
}

sub new {
    my($type) = shift;
    my(%p) = @_;
    my($self) = {};
    $self->{'file'} = $p{'-file'};
    $self->{'fh'} = undef;

    bless $self, $type;
    return $self;
}

sub open {
    my($self, $mode) = @_;
    $mode = "<" if (! defined($mode));

    my($file) = $self->file();
    return unless defined($file);

    my($fh) = new FileHandle;

    if (! $fh->open($mode . $file)) {
        $fh = undef;
    } else {
        binmode($fh);
    }

    $self->fh($fh);
    return $fh;
}

sub close {
    my($self) = @_;
    return unless $self->fh();
    $self->fh()->close();
    $self->fh(undef);
    return;
}

# Reading the RRD headers is quite efficient, since it's using stdio.
# we typically read a disk block starting at offset
# 0, then fetch all of the header stuff from there. On my Solaris
# machine truss shows that we make one 8k read for the header,
# then one 8k read per DS we want to dig into.

sub _readBlock {
    my($self, $off, $size) = @_;

    my($fh) = $self->fh();
    return undef unless $fh;

    $fh->seek($off, 0) unless (! defined($off));
    my($buf);
    if ($fh->read($buf, $size)) {
        return $buf;
    } else {
        return undef;
    }
}

sub _readNextBlock {
    my($self, $size) = @_;
    return $self->_readBlock(undef, $size);
}

sub loadHeader {
    my($self) = @_;
    my($fh) = $self->fh();

    my($fmt) = new RRD::Format;
    if (! $fmt->setArch($RRD::File::gArch)) {
        $RRD::File::gErr = "Architecture $RRD::File::gArch not supported yet.";
        return;
    }

    # save it for later use (esp by getDataOffset)
    $self->fmt($fmt);

    my($header) = $self->_readBlock(0, sizeof($fmt->format('statHead')));
    return undef unless (defined($header));

    # cdp_xff is only available with old format, but it's only
    # accessed byu callers when they know it's going to be set,
    # so it's OK if we set it tp undef here for new format RRD's.

    my($c, $v, $fc, $ds_cnt, $rra_cnt, $pdp_step, $cdp_xff) =
        unpack($fmt->format('statHead'), $header);

    $c = fixName($c);
    $v = fixName($v);

    if ($c ne $fmt->format('cookie') ||
        ("$fc" != $fmt->format('float_cookie'))) {
        $RRD::File::gErr = "Something is wrong with the header of this file.";
        return;
    }

    $self->version($v);
    # and save all the good stuff for later use
    $self->ds_cnt($ds_cnt);
    $self->rra_cnt($rra_cnt);
    $self->pdp_step($pdp_step);
    $self->cdp_xff($cdp_xff);

    my($i);
    foreach $i (0 .. $ds_cnt-1) {
        my(%def) = ();
        my($block) = $self->_readNextBlock(sizeof($fmt->format('dsDef')));
        croak("Could not read DS def $i") unless (defined($block));

        my($dsName, $dst, $ds_mrhb, $min_val, $max_val) =
	    unpack($fmt->format('dsDef'), $block);

        $dsName = fixName($dsName);
        $dst = fixName($dst);

        %def = ( 'dsName' => $dsName,
		 'dst' => $dst,
		 'ds_mrhb' => $ds_mrhb,
		 'min_val' => $min_val,
		 'max_val' => $max_val );

        push @{$self->{'ds_def'}}, \%def;
    }

    foreach $i (0 .. $rra_cnt-1) {
        my(%def) = ();
        my($block) = $self->_readNextBlock(sizeof($fmt->format('rraDef')));
        croak("Could not read RRA def $i") unless (defined($block));

        my($rraName, $row_cnt, $pdp_cnt, $cf) =
            unpack($fmt->format('rraDef'), $block);

        $rraName = fixName($rraName);
        $cf = fixName($cf);

        %def = ( 'rraName' => $rraName,
		 'cf' => $cf,
		 'row_cnt' => $row_cnt,
		 'pdp_cnt' => $pdp_cnt );

        push @{$self->{'rra_def'}}, \%def;
    }

    {
        my ($block);
        my ($last_up, $last_up_usec);
        if ($v eq "0001" || $v eq "0002" || $v eq "0003") {
           $block = $self->_readNextBlock(sizeof($fmt->format('liveHead')));
           croak("Could not read live header") unless (defined($block));
           $last_up = unpack($fmt->format('liveHead'), $block);
        } else {
           if (!defined($fmt->format('liveHead3'))) {
              $RRD::File::gErr =
                 "RRD file version " . $v . " not supported on this arch.";
              return;
           }
           $block = $self->_readNextBlock(sizeof($fmt->format('liveHead3')));
           croak("Could not read live header") unless (defined($block));
           ($last_up, $last_up_usec) = unpack($fmt->format('liveHead3'), $block);
        }
        $self->last_up($last_up);
    }

    foreach $i (0 .. $ds_cnt-1) {
        my(%def) = ();
        my($block) = $self->_readNextBlock(sizeof($fmt->format('pdpDef')));
        croak("Could not read PDP $i") unless (defined($block));

        my($last_ds, $unkn_sec, $value) =
            unpack($fmt->format('pdpDef'), $block);

        $last_ds = fixName($last_ds);

        %def = ('last_ds' => $last_ds,
                'value' => $value,
                'unkn_sec' => $unkn_sec );

        push @{$self->{'pdps'}}, \%def;
    }

    foreach $i (0 .. (($ds_cnt * $rra_cnt)-1)) {
        my(%def) = ();
        my($block) = $self->_readNextBlock(sizeof($fmt->format('cdpDef')));
        croak("Could not read CDP $i") unless (defined($block));

        my($value, $unkn_pdp) = unpack($fmt->format('cdpDef'), $block);

        %def = ( 'value' => $value,
		 'unkn_pdp' => $unkn_pdp );

        push @{$self->{'cdps'}}, \%def;
    }

    foreach $i (0 .. ($rra_cnt-1)) {
        my($block) = $self->_readNextBlock(sizeof($fmt->format('rraPtr')));
        croak("Could not read RRD cur $i") unless (defined($block));

        my($ptr) = unpack($fmt->format('rraPtr'), $block);
        push @{$self->{'rra_ptr'}}, $ptr;
    }

    return 1;
}

sub ds_def {
    my($self, $i) = @_;
    return $self->{'ds_def'}->[$i];
}

sub rra_def {
    my($self, $i) = @_;
    return $self->{'rra_def'}->[$i];
}

sub pdp {
    my($self, $i) = @_;
    return $self->{'pdps'}->[$i];
}

sub cdp {
    my($self, $i) = @_;
    return $self->{'cdps'}->[$i];
}

sub rra_ptr {
    my($self, $i) = @_;
    return $self->{'rra_ptr'}->[$i];
}

sub getDSRowValue {
    my($self, $rra, $row, $ds) = @_;
    my($ds_cnt) = $self->ds_cnt();
    my($rra_cnt) = $self->rra_cnt();
    if (!defined($ds) || $ds >= $self->ds_cnt()
       || !defined($rra) || $rra >= $self->rra_cnt()) {
        return;
    }
    my($fmt) = new RRD::Format;
    if (! $fmt->setArch($RRD::File::gArch)) {
        $RRD::File::gErr = "Architecture $RRD::File::gArch not supported yet.";
        return;
    }
    $self->fmt($fmt);

    # this gets us to the place in the file where the data starts.

    my($headerOffset) = $self->getDataOffset();

    # was there an error?
    return unless($headerOffset);
    # determine which row we want from the RRA
    my($numRows) = $self->rra_def($rra)->{row_cnt};
    my($wantedRow) = ($self->rra_ptr($rra) - $row);
    while($wantedRow < 0) {
        $wantedRow += $numRows;
    }

    my($elmSize) = sizeof($fmt->format('element'));
    my $rraOffset = 0;
    my $i;
    # jump over intervening rras
    for ($i = 0; $i < $rra; $i++)
    {
	$numRows = $self->rra_def($i)->{row_cnt};
	$rraOffset += $ds_cnt * $numRows * $elmSize;
    }

    my($dataOffset) = $rraOffset +
	$wantedRow * ($ds_cnt * $elmSize) + $ds * $elmSize;
    my($offset) = $headerOffset + $dataOffset;

    my($value) = $self->_readBlock($offset, $elmSize);

    if (defined($value)) {
        ($value) = unpack($fmt->format('element'), $value);
        return $value;
    } else {
        return;
    }
}

sub getDSCurrentValue {
    my($self, $ds) = @_;

    my($ds_cnt) = $self->ds_cnt();
    my($rra_cnt) = $self->rra_cnt();

    # check param, now that we have ds_cnt.
    if (!defined($ds) || $ds >= $self->ds_cnt()) {
        return;
    }

    my($fmt) = new RRD::Format;
    if (! $fmt->setArch($RRD::File::gArch)) {
        $RRD::File::gErr = "Architecture $RRD::File::gArch not supported yet.";
        return;
    }
    $self->fmt($fmt);

    # this gets us to the place in the file where the data starts. now
    # all we need to do is find our bit of data within the data area...

    my($headerOffset) = $self->getDataOffset();

    # was there an error?
    return unless ($headerOffset);

    # now, calculate the offset into the data area
    #   we want the current row in the first RRA.
    #   we want the column corresponding to the given ds.
    #   (see last bit of rrd_format.h
    #   if you want to try to understand this...)

    my($wantedRow) = $self->rra_ptr(0);
    my($elmSize) = sizeof($fmt->format('element'));
    my($rraOffset) = 0;     # this is because we only want the first RRA.
                            # eventually, we could compute this for an
                            # arbitrarty RRA.
    my($dataOffset) = $rraOffset +
	$wantedRow * ($ds_cnt * $elmSize) + $ds * $elmSize;
    my($offset) = $headerOffset + $dataOffset;

    my($value) = $self->_readBlock($offset, $elmSize);

    if (defined($value)) {
        ($value) = unpack($fmt->format('element'), $value);
        return $value;
    } else {
        return;
    }
}

sub getDataOffset {
    my($self) = @_;

    my($fmt) = $self->fmt();
    return unless (defined($fmt));

    my($ds_cnt) = $self->ds_cnt();
    my($rra_cnt) = $self->rra_cnt();

    my($lhSz) = ($self->version() ne "0003") ?
      sizeof($fmt->format('liveHead')) :
      sizeof($fmt->format('liveHead3'));

    return (sizeof($fmt->format('statHead')) +
	    $ds_cnt * sizeof($fmt->format('dsDef')) +
	    $rra_cnt * sizeof($fmt->format('rraDef')) +
	    $lhSz +
	    $ds_cnt * sizeof($fmt->format('pdpDef')) +
	    ($ds_cnt * $rra_cnt) * sizeof($fmt->format('cdpDef')) +
	    $rra_cnt * sizeof($fmt->format('rraPtr')));
}

sub getMeta {
    my($self) = @_;
    my($metaRef) = {};

    my($file) = $self->file();
    return $metaRef unless defined($file);

    # make the metafile name. Remove the .rrd (if there is one)
    # and append .meta
    $file =~ s/\.rrd$//;
    my($metaFile) = "$file.meta";

    if (CORE::open(META, "<$metaFile")) {
        while (<META>) {
            chomp;
            my($delim) = "\0";
            $delim = ":" if (! /\0/); # backwards compatiblity
            my($k, $v) = split(/$delim/, $_, 2);
            $metaRef->{$k} = $v;
        }
        CORE::close(META);
    }

    return $metaRef;
}

sub setMeta {
    my($self, $metaRef) = @_;

    my($file) = $self->file();
    return unless defined($file);

    # make the metafile name. Remove the .rrd (if there is one)
    # and append .meta
    $file =~ s/\.rrd$//;
    my($metaFile) = "$file.meta";

    if (CORE::open(META, ">$metaFile")) {
        my($k);
        foreach $k (keys(%{$metaRef})) {
            print META join("\0", $k, $metaRef->{$k}), "\n";
        }
        CORE::close(META);

        return 1;
    } else {
        return;
    }
}

sub fixName {
    my($str) = @_;

    # fix undefs (generated by old files) to be emtpy, so that
    # we don't get warnings in rrd-dump
    return "" unless defined ($str);

    # even though unpack gives us all the bytes, we only want the C
    # string.
    my($nul) = index($str, "\0");
    if ($nul != -1) {
        $str = substr($str, 0, $nul);
    }

    return $str;
}

1;

# Local Variables:
# mode: perl
# indent-tabs-mode: nil
# tab-width: 4
# perl-indent-level: 4
# End: