summaryrefslogtreecommitdiff
path: root/jrrd.js
blob: 91048752215285f9bd0491d51643de0a9f4187d7 (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

if(typeof jrrd == 'undefined') {
    var jrrd = {};
}

jrrd.downloadBinary = function(url) {
    var d = new MochiKit.Async.Deferred();

    $.ajax({
        url: url,
        dataType: 'text',
        cache: false,
        beforeSend: function(request) {
            try {
                request.overrideMimeType('text/plain; charset=x-user-defined');
            } catch(e) {
                // IE doesn't support overrideMimeType
            }
        },
        success: function(data) {
            try {
                d.callback(new BinaryFile(data));
            } catch(e) {
                d.errback(e);
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            // Special case for IE which handles binary data slightly
            // differently.
            if(textStatus == 'parsererror') {
                if (typeof xhr.responseBody != 'undefined') {
                    return this.success(xhr.responseBody);
                }
            }
            d.errback(new Error(xhr.status));
        }
    });
    return d;
};


jrrd.RrdQuery = function(rrd) {
    this.rrd = rrd;
};

jrrd.RrdQuery.prototype.getData = function(startTime, endTime, dsId) {
    var startTimestamp = startTime.getTime()/1000;
    var endTimestamp = endTime.getTime()/1000;

    if(dsId == null) {
        dsId = 0;
    }
    var ds = this.rrd.getDS(dsId);
    var consolidationFunc = 'AVERAGE';
    var lastUpdated = this.rrd.getLastUpdate();

    // If end time stamp is beyond the range of this rrd then reset it
    if(lastUpdated < endTimestamp) {
        endTimestamp = lastUpdated;
    }
    var bestRRA = null;
    for(var i=0; i<this.rrd.getNrRRAs(); i++) {
        // Look through all RRAs looking for the most suitable
        // data resolution.
        var rra = this.rrd.getRRA(i);

        if(rra.getCFName() != consolidationFunc) {
            continue;
        }
        bestRRA = rra;
        var step = rra.getStep();
        var rraRowCount = rra.getNrRows();
        var firstUpdated = lastUpdated - (rraRowCount - 1) * step;
        if(firstUpdated <= startTimestamp) {
            break;
        }
    }

    if(!bestRRA) {
        throw new Error('Unrecognised consolidation function: ' + consolidationFunc);
    }

    var startRow = rraRowCount - parseInt((lastUpdated - startTimestamp)/step) - 1;
    var endRow = rraRowCount - parseInt((lastUpdated - endTimestamp)/step) - 1;

    var flotData = [];
    var timestamp = firstUpdated + (startRow - 1) * step;
    var dsIndex = ds.getIdx();
    for (var i=startRow; i<=endRow; i++) {
        var val = bestRRA.getEl(i, dsIndex);
        flotData.push([timestamp*1000.0, val]);
        timestamp += step;
    }
    return {label: ds.getName(), data: flotData};
};


jrrd.RrdQueryRemote = function(url) {
    this.url = url;
    this.lastUpdate = 0;
    this._download = null;
};

jrrd.RrdQueryRemote.prototype.getData = function(startTime, endTime, dsId) {
    var endTimestamp = endTime.getTime()/1000;

    // Download the rrd if there has never been a download or if the last
    // completed download had a lastUpdated timestamp less than the requested
    // end time.
    // Don't start another download if one is already in progress.
    if(!this._download || (this._download.fired > -1 && this.lastUpdate < endTimestamp )) {
        this._download = jrrd.downloadBinary(this.url)
                .addCallback(
                    function(self, binary) {
                        // Upon successful download convert the resulting binary
                        // into an RRD file and pass it on to the next callback
                        // in the chain.
                        var rrd = new RRDFile(binary);
                        self.lastUpdate = rrd.getLastUpdate();
                        return rrd;
                    }, this);
    }

    // Set up a deferred which will call getData on the local RrdQuery object
    // returning a flot compatible data object to the caller.
    var ret = new MochiKit.Async.Deferred().addCallback(
        function(startTime, endTime, dsId, rrd) {
            return new jrrd.RrdQuery(rrd).getData(startTime, endTime, dsId);
        }, startTime, endTime, dsId);

    // Add a pair of callbacks to the current download which will callback the
    // result which we setup above.
    this._download.addBoth(
        function(ret, res) {
            if(res instanceof Error) {
                ret.errback(res);
            } else {
                ret.callback(res);
            }
            return res;
        }, ret);

    return ret;
};


jrrd.RrdQueryDsProxy = function(rrdQuery, dsId) {
    this.rrdQuery = rrdQuery;
    this.dsId = dsId;
};

jrrd.RrdQueryDsProxy.prototype.getData = function(startTime, endTime) {
    return this.rrdQuery.getData(startTime, endTime, this.dsId);
};


jrrd.Chart = function(template, options) {
    this.template = template;
    this.options = options;
    this.data = [];
};

jrrd.Chart.prototype.addData = function(label, db) {
    this.data.push([label, db]);
};

jrrd.Chart.prototype.draw = function(startTime, endTime) {
    var results = [];
    for(var i=0; i<this.data.length; i++) {
        results.push(this.data[i][1].getData(startTime, endTime));
    }

    return MochiKit.Async.gatherResults(results)
            .addCallback(
                function(self, data) {
                    for(var i=0; i<data.length; i++) {
                        data[i].label = self.data[i][0];
                    }
                    var plot = $.plot(self.template, data, self.options);
                }, this)
            .addErrback(
                function(self, failure) {
                    self.template.text('error: ' + failure.message);
                }, this);
};