bunch of cleanups & fixes all over the place
[sfa.git] / sfa / util / genitable.py
1 # genitable.py
2 #
3 # implements support for geni records stored in db tables
4 #
5 # TODO: Use existing PLC database methods? or keep this separate?
6
7 ### $Id$
8 ### $URL$
9
10 import report
11
12 from pg import DB, ProgrammingError
13
14 from sfa.trust.gid import *
15 from sfa.util.record import *
16 from sfa.util.debug import *
17
18 class GeniTable:
19
20     GENI_TABLE_PREFIX = "sfa$"
21
22     def __init__(self, create=False, hrn="unspecified.default.registry", cninfo=None):
23
24         self.hrn = hrn
25
26         # pgsql doesn't like table names with "." in them, to replace it with "$"
27         self.tablename = GeniTable.GENI_TABLE_PREFIX + self.hrn.replace(".", "$")
28
29         # establish a connection to the pgsql server
30         self.cnx = DB(cninfo['dbname'], cninfo['address'], port=cninfo['port'], user=cninfo['user'], passwd=cninfo['password'])
31
32         # if asked to create the table, then create it
33         if create:
34             self.create()
35
36     def exists(self):
37         tableList = self.cnx.get_tables()
38         if 'public.' + self.tablename in tableList:
39             return True
40         if 'public."' + self.tablename + '"' in tableList:
41             return True
42         return False
43
44     def create(self):
45         
46         querystr = "CREATE TABLE " + self.tablename + " ( \
47                 key text, \
48                 hrn text, \
49                 gid text, \
50                 type text, \
51                 pointer integer, \
52                 date_created timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, \
53                 last_updated timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP);"
54         template = "CREATE INDEX %s_%s_idx ON %s (%s);"
55         indexes = [template % ( self.tablename, field, self.tablename, field) \
56                    for field in ['key', 'hrn', 'type','pointer']]
57         # IF EXISTS doenst exist in postgres < 8.2
58         try:
59             self.cnx.query('DROP TABLE IF EXISTS ' + self.tablename)
60         except ProgrammingError:
61             try:
62                 self.cnx.query('DROP TABLE ' + self.tablename)
63             except ProgrammingError:
64                 pass
65         
66         self.cnx.query(querystr)
67         for index in indexes:
68             self.cnx.query(index)
69
70     def remove(self, record):
71         query_str = "DELETE FROM " + self.tablename + " WHERE key = '" + record.get_key() + "'"
72         self.cnx.query(query_str)
73
74     def insert(self, record):
75         fieldnames = ["key"] + record.get_field_names()
76         fieldvals = record.get_field_value_strings(fieldnames)
77         query_str = "INSERT INTO " + self.tablename + \
78                        "(" + ",".join(fieldnames) + ") " + \
79                        "VALUES(" + ",".join(fieldvals) + ")"
80         #print query_str
81         self.cnx.query(query_str)
82
83     def update(self, record):
84         names = record.get_field_names()
85         pairs = []
86         for name in names:
87            val = record.get_field_value_string(name)
88            pairs.append(name + " = " + val)
89         update = ", ".join(pairs)
90
91         query_str = "UPDATE " + self.tablename+ " SET " + update + " WHERE key = '" + record.get_key() + "'"
92         #print query_str
93         self.cnx.query(query_str)
94
95     def find_dict(self, type, value, searchfield):
96         query_str = "SELECT * FROM " + self.tablename + " WHERE " + searchfield + " = '" + str(value) + "'"
97         dict_list = self.cnx.query(query_str).dictresult()
98         result_dict_list = []
99         for dict in dict_list:
100            if (type=="*") or (dict['type'] == type):
101                result_dict_list.append(dict)
102         return result_dict_list
103
104     def find(self, type, value, searchfield):
105         result_dict_list = self.find_dict(type, value, searchfield)
106         result_rec_list = []
107         for result in result_dict_list:
108             if result['type'] in ['authority']:
109                 result_rec_list.append(AuthorityRecord(dict=result))
110             elif result['type'] in ['node']:
111                 result_rec_list.append(NodeRecord(dict=result))
112             elif result['type'] in ['slice']:
113                 result_rec_list.append(SliceRecord(dict=result))
114             elif result['type'] in ['user']:
115                 result_rec_list.append(UserRecord(dict=result))
116             else:
117                 result_rec_list.append(GeniRecord(dict=result))
118         return result_rec_list
119
120     def resolve_dict(self, type, hrn):
121         return self.find_dict(type, hrn, "hrn")
122
123     def resolve(self, type, hrn):
124         return self.find(type, hrn, "hrn")
125
126     def list_dict(self):
127         query_str = "SELECT * FROM " + self.tablename
128         result_dict_list = self.cnx.query(query_str).dictresult()
129         return result_dict_list
130
131     def list(self):
132         result_dict_list = self.list_dict()
133         result_rec_list = []
134         for dict in result_dict_list:
135             result_rec_list.append(GeniRecord(dict=dict).as_dict())
136         return result_rec_list
137
138     @staticmethod
139     def geni_records_purge(cninfo):
140
141         cnx = DB(cninfo['dbname'], cninfo['address'], 
142                  port=cninfo['port'], user=cninfo['user'], passwd=cninfo['password'])
143         tableList = cnx.get_tables()
144         for table in tableList:
145             if table.startswith(GeniTable.GENI_TABLE_PREFIX) or \
146                     table.startswith('public.' + GeniTable.GENI_TABLE_PREFIX) or \
147                     table.startswith('public."' + GeniTable.GENI_TABLE_PREFIX):
148                 report.trace("dropping table " + table)
149                 cnx.query("DROP TABLE " + table)