aboutsummaryrefslogtreecommitdiffstats
path: root/tools/xen/lib/xend/XendDB.py
blob: 6a27e65b5828f8fb5fdb81f8ed93792a4d819174 (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
# Copyright (C) 2004 Mike Wray <mike.wray@hp.com>

import os
import os.path
import errno
import dircache
import time

import sxp
import XendRoot
xroot = XendRoot.instance()

class XendDB:
    """Persistence for Xend. Stores data in files and directories.
    """

    def __init__(self, path=None):
        self.dbpath = xroot.get_dbroot()
        if path:
            self.dbpath = os.path.join(self.dbpath, path)
        pass

    def filepath(self, path):
        return os.path.join(self.dbpath, path)
        
    def fetch(self, path):
        fpath = self.filepath(path)
        return self.fetchfile(fpath)

    def fetchfile(self, fpath):
        pin = sxp.Parser()
        fin = file(fpath, "rb")
        try:
            while 1:
                try:
                    buf = fin.read(1024)
                except IOError, ex:
                    if ex.errno == errno.EINTR:
                        continue
                    else:
                        raise
                pin.input(buf)
                if buf == '':
                    pin.input_eof()
                    break
        finally:
            fin.close()
        return pin.get_val()

    def save(self, path, sxpr):
        fpath = self.filepath(path)
        return self.savefile(fpath, sxpr)
    
    def savefile(self, fpath, sxpr):
        fdir = os.path.dirname(fpath)
        if not os.path.isdir(fdir):
            os.makedirs(fdir)
        fout = file(fpath, "wb+")
        try:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            fout.write("# %s %s\n" % (fpath, t))
            sxp.show(sxpr, out=fout)
        finally:
            fout.close()

    def fetchall(self, path):
        dpath = self.filepath(path)
        d = {}
        for k in dircache.listdir(dpath):
            try:
                v = self.fetchfile(os.path.join(dpath, k))
                d[k] = v
            except:
                pass
        return d

    def saveall(self, path, d):
        for (k, v) in d.items():
            self.save(os.path.join(path, k), v)

    def delete(self, path):
        dpath = self.filepath(path)
        os.unlink(dpath)

    def ls(self, path):
        dpath = self.filepath(path)
        return dircache.listdir(dpath)