/adei/ui

To get this branch, use:
bzr branch http://darksoft.org/webbzr/adei/ui

« back to all changes in this revision

Viewing changes to classes/readers/zeus.php

  • Committer: Suren A. Chilingaryan
  • Date: 2008-04-02 10:23:22 UTC
  • Revision ID: csa@dside.dyndns.org-20080402102322-okib92sicg2dx3o3
Initial import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?php
 
2
 
 
3
class ZEUSLogGroup extends LOGGROUP {
 
4
 var $table;
 
5
 
 
6
 function __construct(array &$info, ZEUS &$zeus, $flags = 0) {
 
7
    parent::__construct($info);
 
8
    
 
9
    if ($this->gid === false) $this->gid = 0;
 
10
    $this->table = "log" . $this->gid;
 
11
 }
 
12
}
 
13
 
 
14
class ZEUSData implements Iterator {
 
15
 var $zeus;
 
16
 var $stmt;
 
17
 var $row;
 
18
 
 
19
 function __construct(ZEUS &$zeus, PDOStatement &$stmt) {
 
20
    $this->zeus = &$zeus;
 
21
    $this->stmt = &$stmt;
 
22
 }
 
23
 
 
24
 function rewind() {
 
25
    try {
 
26
        $this->stmt->execute();
 
27
        $this->next();
 
28
    } catch(PDOException $e) {
 
29
        throw new ADEIException(translate("SQL request is failed with error") . ": " . $e->getMessage(), $e->getCode());
 
30
    }
 
31
 
 
32
 }
 
33
 
 
34
    // current element
 
35
 function current() {
 
36
    $kanz=(strlen($this->row["data"])-4)/8;
 
37
    $bform='d'.$kanz.'ist/Vlen';
 
38
    $blob = unpack($bform,strrev($this->row["data"]));
 
39
 
 
40
    $res = array();
 
41
    for ($i=0;$i<$kanz;$i++) {
 
42
        if (($kanz > 1)||(isset($blob["ist".($kanz-$i)]))) 
 
43
            $res[$i]=$blob["ist".($kanz-$i)];
 
44
        else 
 
45
            $res[$i]=$blob["ist"];
 
46
    }
 
47
    return $res;
 
48
 }
 
49
 
 
50
    // current key (PHP rounding to integer :()
 
51
 function key() {
 
52
    return $this->zeus->ExportUnixTime($this->row['ts']);
 
53
 }
 
54
 
 
55
    // advvance to next (and returns it or false)
 
56
 function next() {
 
57
    try {
 
58
//      do {
 
59
            $this->row = $this->stmt->fetch();
 
60
//      } while (($this->row)&&(strlen($this->row["data"]) < 12));
 
61
    } catch(PDOException $e) {
 
62
        throw new ADEIException(translate("SQL error") . ": " . $e->getMessage());
 
63
    }
 
64
 }
 
65
 
 
66
    // checks if there is current element
 
67
 function valid() {
 
68
    return $this->row?true:false;
 
69
 }
 
70
}
 
71
 
 
72
class ZEUS extends READER {
 
73
 var $db;
 
74
 
 
75
 function __construct(&$props) {
 
76
    parent::__construct($props);    
 
77
    $this->db = new DATABASE($this->server);
 
78
 }
 
79
    
 
80
 function CreateGroup(array &$ginfo = NULL, $flags = 0) {
 
81
    if (!$ginfo) $ginfo = $this->req->GetGroupInfo();
 
82
    return new ZEUSLogGroup($ginfo, $this);
 
83
 }
 
84
 
 
85
 function CheckGroup(LOGGROUP &$grp = NULL) {
 
86
    if ($grp) {
 
87
        if (!$grp instanceof ZEUSLogGroup)
 
88
            throw Exception(translate("Invalid LOGGROUP supplied"));
 
89
    } else {
 
90
        $grinfo = $this->req->GetGroupInfo();
 
91
        $grp = $this->CreateGroup($grinfo);
 
92
    }
 
93
    return $grp;
 
94
 }
 
95
 
 
96
/* ToDo: 
 
97
 *  1. Add checks (if it is really Zeus database)
 
98
 */
 
99
 function GetDatabaseList($flags = 0) {
 
100
    global $READER_DB;
 
101
 
 
102
 
 
103
    if ($flags&READER::LIST_ALL) return $this->db->GetDatabaseList();
 
104
    
 
105
    if ($this->req)
 
106
        $server = $this->req->GetServerConfig();
 
107
    else
 
108
        throw new ADEIException(translate("The data source server is not specified"));
 
109
 
 
110
 
 
111
    $filter = "";
 
112
    foreach ($server['database'] as $db) {
 
113
        if ($filter) $filter .= "|$db";
 
114
        else $filter = $db;
 
115
    }
 
116
    $filter = "/^(" . $filter . ")/";
 
117
    
 
118
    return $this->db->GetDatabaseList($filter);
 
119
 }
 
120
 
 
121
 function GetGroupInfo(LOGGROUP &$grp = NULL, $flags = 0) {
 
122
    if ($grp)
 
123
        $res = $this->db->Query("SELECT * FROM groups WHERE gid=" . $grp->gid);
 
124
    else
 
125
        $res = $this->db->Query("SELECT * FROM groups");
 
126
 
 
127
    $groups = array();
 
128
    if ($flags&READER::NEED_INFO) {
 
129
        foreach ($res as $row) {
 
130
            $gid = $row['gid'];
 
131
            $groups[$gid] = $row;
 
132
        
 
133
            $ginfo = array("db_group" => $gid);
 
134
            $grzeus = $this->CreateGroup($ginfo);
 
135
            
 
136
            $req = "MIN(ts), MAX(ts)";
 
137
            if ($flags&READER::NEED_COUNT) 
 
138
                $req .= ", COUNT(ts)";
 
139
 
 
140
            $valres = $this->db->Query("SELECT $req FROM " . $grzeus->table);
 
141
            $vals = $valres->fetch(PDO::FETCH_NUM);
 
142
            $valres = NULL;
 
143
            
 
144
            $groups[$gid]['__internal__'] = array();
 
145
 
 
146
            $groups[$gid]['first'] = $this->ExportUnixTime($vals[0]);
 
147
            if (($this->start_date)&&($this->start_date > $groups[$gid]['first'])) {
 
148
                $groups[$gid]['first'] = $this->start_date;
 
149
                $groups[$gid]['__internal__']['first'] = $this->ImportUnixTime($this->start_date);
 
150
            } else {
 
151
                $groups[$gid]['__internal__']['first'] = $vals[0];
 
152
            }
 
153
 
 
154
            $groups[$gid]['last'] = $this->ExportUnixTime($vals[1]);
 
155
            if (($this->end_date)&&($this->end_date < $groups[$gid]['last'])) {
 
156
                $groups[$gid]['last'] = $this->end_date;
 
157
                $groups[$gid]['__internal__']['last'] = $this->ImportUnixTime($this->end_date);
 
158
            } else {
 
159
                $groups[$gid]['__internal__']['last'] = $vals[1];
 
160
            }
 
161
 
 
162
            if ($flags&READER::NEED_COUNT) 
 
163
                $groups[$gid]['records'] = $vals[2];
 
164
 
 
165
            if ($flags&READER::NEED_ITEMINFO) {
 
166
                $groups[$gid]['items'] = $this->GetItemList($grzeus);
 
167
            }
 
168
 
 
169
        }
 
170
    } else {
 
171
        foreach ($res as $row) {
 
172
            $groups[$row['gid']] = $row;
 
173
        }
 
174
    }
 
175
    
 
176
    return $grp?$groups[$grp->gid]:$groups;
 
177
 }
 
178
 
 
179
 function GetExperimentList($flags = 0) {
 
180
    $resp = $this->db->query("SELECT `experiment`, `name`, `start`, `stop` FROM marker");
 
181
 
 
182
    $list = array();
 
183
    foreach ($resp as $row) {
 
184
        if (!preg_match("/[\w\d]/", $row['name'])) $row['name'] = _("No name");
 
185
            /* Read format */
 
186
            
 
187
        $item = array();
 
188
        $item['start'] = $row['start'];
 
189
        $item['stop'] = $row['stop'];
 
190
            
 
191
        if (preg_match("/[\w\d]/", $row['experiment'])) $have_exp = 1;
 
192
        else $have_exp = 0;
 
193
        if (preg_match("/[\w\d]/", $row['name'])) $have_name = 1;
 
194
        else $have_name = 0;
 
195
            
 
196
            
 
197
        if (($have_exp)&&($have_name)) $item['name'] = $row['experiment'] . ": " . $row['name'];
 
198
        else if ($have_exp) $item['name'] = $row['experiment'];
 
199
        else if ($have_name) $item['name'] = $row['name'];
 
200
        else $item['name'] = $item['start'] . " - " . $item['stop'];
 
201
            
 
202
        array_push($list, $item);
 
203
    }
 
204
 
 
205
    return $list;
 
206
 }
 
207
 
 
208
 function GetMaskList(LOGGROUP &$grp = NULL, $flags = 0) {
 
209
    $grp = $this->CheckGroup($grp);
 
210
 
 
211
    $list = array();
 
212
    
 
213
    $resp = $this->db->Query("SELECT `maskid`, `name` FROM masks WHERE gid=" . $grp->gid);
 
214
 
 
215
    foreach ($resp as $row) {
 
216
        if (!preg_match("/[\w\d]/", $row['name'])) $row['name'] = _("No name");
 
217
        $list[$row['maskid']] = $row;
 
218
    }
 
219
 
 
220
    return $list;
 
221
 }
 
222
 
 
223
 function GetItemList(LOGGROUP &$grp = NULL, MASK &$mask = NULL, $flags = 0) {
 
224
    $grp = $this->CheckGroup($grp);
 
225
    if (!$mask) $mask = $this->CreateMask($grp);
 
226
 
 
227
    $bids = array();
 
228
    $items = array();
 
229
    
 
230
    $resp = $this->db->Query("SELECT `id` FROM g2id WHERE gid=" . $grp->gid . " ORDER BY pos ASC");
 
231
    foreach ($resp as $row) {
 
232
        array_push($bids, $row[0]);
 
233
    }
 
234
 
 
235
    $pos = 0; $rpos = 0;
 
236
    foreach ($bids as $bid) {    
 
237
 
 
238
        $resp = $this->db->Query("SELECT length, name, itemnames FROM blocks WHERE bid=$bid");
 
239
        if ($resp) $res = $resp->fetch();
 
240
        else $res = false;
 
241
            
 
242
        $names = preg_split("/\r?\n/", $res[2]);
 
243
        for ($i = 0; $i < $res[0]; $i++, $pos++) {
 
244
            if (!$mask->Check($pos)) continue;
 
245
            
 
246
            $items[$rpos] = array(
 
247
                "id" => $pos,
 
248
                "group" => $res[1],
 
249
                "name" =>  $names[$i],
 
250
                "opc" => ""
 
251
            );
 
252
            if (!preg_match("/[\w\d]/", $items[$rpos]["name"])) {
 
253
                if (preg_match("/[\w\d]/", $items[$rpos]["group"])) {
 
254
                    $items[$rpos]["name"] = "item" . $i;
 
255
                } else {
 
256
                    $items[$rpos]["name"] = "item" . $pos;
 
257
                }
 
258
            }
 
259
            if (preg_match("/[\w\d]/", $items[$rpos]["group"])) {
 
260
                $items[$rpos]["name"] = $items[$rpos]["name"] . " [" . $items[$rpos]["group"] . "]";
 
261
            } 
 
262
            
 
263
            $rpos++;
 
264
        }
 
265
        unset($names);
 
266
    }
 
267
    
 
268
    return $items;
 
269
 }
 
270
 
 
271
    /* ZEUS time is a LabVIEW time */
 
272
 function ImportUnixTime($unix_time) {
 
273
    if (!$unix_time) return 0;
 
274
    return ($unix_time + (2082837600+7200));
 
275
 }
 
276
 
 
277
 function ExportUnixTime($zeus_time) {
 
278
    if (!$zeus_time) return false;
 
279
    return ($zeus_time - (2082837600+7200));
 
280
 
 
281
 }
 
282
 
 
283
 function GetGroupSize(LOGGROUP &$grp = NULL) {
 
284
    $grp = $this->CheckGroup($grp);
 
285
 
 
286
    $bids = array();
 
287
    
 
288
    try {    
 
289
        $resp = $this->db->Query("SELECT `id` FROM g2id WHERE gid=" . $grp->gid);
 
290
        foreach ($resp as $row) {
 
291
            array_push($bids, $row[0]);
 
292
        }
 
293
 
 
294
        $size = 0;
 
295
        foreach ($bids as $bid) {    
 
296
            $resp = $this->db->Query("SELECT `length` FROM `blocks` WHERE `bid`=$bid");
 
297
            if ($resp) $res = $resp->fetch();
 
298
            else $res = false;
 
299
            if ($res) $size += $res[0];
 
300
        }
 
301
    } catch (PDOException $e) {
 
302
        throw new Exception($e->getMessage());
 
303
    }
 
304
    
 
305
    return $size;
 
306
 }
 
307
 
 
308
    /* Between includes start point, but excludes end point */ 
 
309
 function GetData(LOGGROUP &$grp = NULL, $from = 0, $to = 0) {
 
310
    $grp = $this->CheckGroup($grp);
 
311
 
 
312
    if ((!$from)||(!$to)) {
 
313
        $ivl = $this->CreateInterval($grp);
 
314
        $ivl->Limit($from, $to);
 
315
        
 
316
        $from = $ivl->window_start;
 
317
        $to = dsMathPreciseAdd($ivl->window_start, $ivl->window_size);
 
318
    }
 
319
 
 
320
    $stmt = $this->db->Prepare("SELECT * FROM `" . $grp->table . "` WHERE `ts` BETWEEN " . $this->ImportUnixTime($from) . " and " . $this->ImportUnixTime($to));
 
321
    return new ZEUSData($this, $stmt);
 
322
 }
 
323
 
 
324
 function RemoveData(LOGGROUP &$grp, $time, $to = 0) {
 
325
    if ($to) {
 
326
        $this->db->Query("DELETE FROM `" . $grp->table . "` WHERE `ts` BETWEEN " . $this->ImportUnixTime($time) . " and " . $this->ImportUnixTime($to));
 
327
    } else {
 
328
        $dbtime = floor($this->ImportUnixTime($time));
 
329
        $this->db->Query("DELETE FROM `" . $grp->table . "` WHERE `ts` BETWEEN " . $dbtime . " and " . ($dbtime + 1));
 
330
    }
 
331
 }
 
332
 
 
333
 function PushData(LOGGROUP &$grp, $time, $data) {
 
334
    $dbtime = $this->ImportUnixTime($time);
 
335
    $size = sizeof($data['values']);
 
336
    
 
337
    $res = "";
 
338
    for ($i=$size;$i>0;$i--) $res .= pack("d", $data['values'][$i-1]);
 
339
    $res .= pack("V", $size);
 
340
    $blob = strrev($res);
 
341
 
 
342
/*    
 
343
    $kanz=(strlen($blob)-4)/8;
 
344
    $bform='d'.$kanz.'ist/Vlen';
 
345
    $blob = unpack($bform,strrev($blob));
 
346
 
 
347
    $res = array();
 
348
    for ($i=0;$i<$kanz;$i++) {
 
349
        if (($kanz > 1)||(isset($blob["ist".($kanz-$i)]))) 
 
350
            $res[$i]=$blob["ist".($kanz-$i)];
 
351
        else 
 
352
            $res[$i]=$blob["ist"];
 
353
    }
 
354
 
 
355
//    print date("c", $time) . ".  " . $res[7] . " = " . $data['values'][7] . "\n";
 
356
    
 
357
*/
 
358
 
 
359
    $dst = $this->db->Prepare("INSERT INTO " . $grp->table . " (ts,data) VALUES(?,?)");
 
360
    $dst->bindParam(1, $dbtime);
 
361
    $dst->bindParam(2, $blob, PDO::PARAM_LOB);
 
362
    $dst->execute();
 
363
 
 
364
 }
 
365
 
 
366
 function Backup(&$binfo, $flags = 0) {
 
367
     global $BACKUP_DB;
 
368
 
 
369
    if (is_array($dbinfo)) {
 
370
        $dbinfo = &$binfo;
 
371
    } else {
 
372
        $dbinfo = $BACKUP_DB;
 
373
        $dbinfo['database'] = $binfo;
 
374
    }   
 
375
    
 
376
    try {
 
377
        $zeus  = new ZEUS($dbinfo);
 
378
    } catch (ADEIException $e) {
 
379
        if ($flags&READER::BACKUP_FULL) {
 
380
            $tmpinfo = $dbinfo;
 
381
            unset($tmpinfo['database']);
 
382
 
 
383
            $zeus = new ZEUS($tmpinfo);
 
384
            $dblist = $zeus->db->ShowDatabases();
 
385
            
 
386
            foreach ($dblist as $row) {
 
387
                if (strtolower($row[0]) == strtolower($dbinfo['database'])) {
 
388
                    throw new ADEIException(translate("Broken or invalid database is specified for backup"));
 
389
                }
 
390
            }
 
391
 
 
392
            if ((strtolower($dbinfo['driver']) == "mysql")&&(strtolower($this->server['driver']) == "mysql")) {
 
393
                $cli = Database::GetConnectionString($this->server);
 
394
                $srv = Database::GetConnectionString($dbinfo);
 
395
 
 
396
                $zeus->db->CreateDatabase($dbinfo['database']);
 
397
                @system("mysqldump --compact $cli | mysql $srv", $res);
 
398
                if ($res) throw new ADEIException(translate("The initialization of the backup database is failed."));
 
399
                
 
400
                $zeus = new ZEUS($dbinfo);
 
401
            } else throw new ADEIException(translate("The initial backup database should setup manualy. The auto mode is only works for the MySQL at the moment"));
 
402
        } else throw $e;
 
403
    }
 
404
 
 
405
 
 
406
    $src_list = $this->GetGroupList(READER::NEED_INFO|READER::NEED_ITEMINFO);
 
407
    $dst_list = $zeus->GetGroupList(READER::NEED_INFO|READER::NEED_ITEMINFO);
 
408
    
 
409
    if ((sizeof($src_list) != sizeof($dst_list))||(sizeof($src_list['items'])!=sizeof($dst_list['items']))) {
 
410
        // or compare names (items by content not lenght, 'name', 'comment')
 
411
        throw new ADEIException(translate("The configuration of the current backup not in sync with the data source"));
 
412
    }
 
413
            
 
414
    
 
415
    $list = $this->req->GetGroupList();
 
416
    foreach ($list as $greq) {
 
417
        $grp = $greq->CreateGroup($this);
 
418
        
 
419
        if ($dst_list[$grp->gid]['__internal__']['last']) $from = $dst_list[$grp->gid]['__internal__']['last'];
 
420
        else $from = 0;
 
421
 
 
422
        if ($src_list[$grp->gid]['__internal__']['last']) $to = $src_list[$grp->gid]['__internal__']['last'];
 
423
        else $to = 0;
 
424
 
 
425
        if (abs(round($from) - round($to))<2) continue;
 
426
 
 
427
        if ($from > $to) 
 
428
            throw new ADEIException(translate("The backup had newer data than the source does"));
 
429
 
 
430
        try {
 
431
            $src = $this->db->Prepare("SELECT lid,ts,data FROM " . $grp->table . " WHERE `ts` > " . $from . " ORDER by lid ASC");
 
432
            if (!$src->execute()) {
 
433
                $einfo = $dst->errorInfo();
 
434
                throw new ADEIException("Failure while backing up group " . $grp->gid . ". SQL Error: " . $einfo[0] . ", Driver Error: " . $einfo[1] . ", Message: " . $einfo[2]);
 
435
            }
 
436
            $src->bindColumn(1, $lid);
 
437
            $src->bindColumn(2, $ts);
 
438
            $src->bindColumn(3, $data, PDO::PARAM_LOB);
 
439
            
 
440
            $dst = $zeus->db->Prepare("INSERT INTO " . $grp->table . " (lid,ts,data) VALUES (?, ?, ?)");
 
441
            $dst->bindParam(1, $lid);
 
442
            $dst->bindParam(2, $ts);
 
443
            $dst->bindParam(3, $data, PDO::PARAM_LOB);
 
444
        
 
445
            while ($src->fetch(PDO::FETCH_BOUND)) {
 
446
                if (!$dst->execute()) {
 
447
                    $einfo = $dst->errorInfo();
 
448
                    throw new ADEIException("Failure while backing up group " . $grp->gid . ", item " . $lid . "(" . date("r", ceil($this->ExportUnixTime($ts))) . ") SQL Error: " . $einfo[0] . ", Driver Error: " . $einfo[1] . ", Message: " . $einfo[2]);
 
449
                }
 
450
            }
 
451
        } catch(PDOException $e) {
 
452
            throw new ADEIException(translate("SQL request is failed with error") . ": " . $e->getMessage(), $e->getCode());
 
453
        }
 
454
    }
 
455
 }
 
456
}
 
457
 
 
458
?>
 
 
b'\\ No newline at end of file'