updated fields
[plcapi.git] / PLC / PCUs.py
1 #
2 # Functions for interacting with the pcus table in the database
3 #
4 # Mark Huang <mlhuang@cs.princeton.edu>
5 # Copyright (C) 2006 The Trustees of Princeton University
6 #
7
8 from PLC.Faults import *
9 from PLC.Parameter import Parameter
10 from PLC.Filter import Filter
11 from PLC.Debug import profile
12 from PLC.Table import Row, Table
13 from PLC.Storage.AlchemyObject import AlchemyObj
14 from PLC.Interfaces import valid_ip, Interface, Interfaces
15 from PLC.Nodes import Node, Nodes
16
17 class PCU(AlchemyObj):
18     """
19     Representation of a row in the pcus table. To use,
20     instantiate with a dict of values.
21     """
22
23     tablename = 'pcus'
24     join_tables = ['pcu_node']
25     fields = {
26         'pcu_id': Parameter(int, "PCU identifier", primary_key=True),
27         'site_id': Parameter(int, "Identifier of site where PCU is located"),
28         'hostname': Parameter(str, "PCU hostname", max = 254),
29         'ip': Parameter(str, "PCU IP address", max = 254),
30         'protocol': Parameter(str, "PCU protocol, e.g. ssh, https, telnet", max = 16, nullok = True),
31         'username': Parameter(str, "PCU username", max = 254, nullok = True),
32         'password': Parameter(str, "PCU username", max = 254, nullok = True),
33         'notes': Parameter(str, "Miscellaneous notes", max = 254, nullok = True),
34         'model': Parameter(str, "PCU model string", max = 32, nullok = True),
35         'node_ids': Parameter([int], "List of nodes that this PCU controls"),
36         'ports': Parameter([int], "List of the port numbers that each node is connected to", ro=True),
37         'last_updated': Parameter(int, "Date and time when node entry was created"),
38         }
39
40     def validate_ip(self, ip):
41         if not valid_ip(ip):
42             raise PLCInvalidArgument, "Invalid IP address " + ip
43         return ip
44
45     validate_last_updated = Row.validate_timestamp
46
47     def update_timestamp(self, col_name, commit = True):
48         """
49         Update col_name field with current time
50         """
51
52         assert 'pcu_id' in self
53         assert self.table_name
54
55         self.api.db.do("UPDATE %s SET %s = CURRENT_TIMESTAMP " % (self.table_name, col_name) + \
56                        " where pcu_id = %d" % (self['pcu_id']) )
57         self.sync(commit)
58
59     def update_last_updated(self, commit = True):
60         self.update_timestamp('last_updated', commit)
61
62     def add_node(self, node, port, commit = True):
63         """
64         Add node to existing PCU.
65         """
66
67         assert 'pcu_id' in self
68         assert isinstance(node, Node)
69         assert isinstance(port, (int, long))
70         assert 'node_id' in node
71
72         pcu_id = self['pcu_id']
73         node_id = node['node_id']
74
75         if node_id not in self['node_ids'] and port not in self['ports']:
76             self.api.db.do("INSERT INTO pcu_node (pcu_id, node_id, port)" \
77                            " VALUES(%(pcu_id)d, %(node_id)d, %(port)d)",
78                            locals())
79
80             if commit:
81                 self.api.db.commit()
82
83             self['node_ids'].append(node_id)
84             self['ports'].append(port)
85
86     def remove_node(self, node, commit = True):
87         """
88         Remove node from existing PCU.
89         """
90
91         assert 'pcu_id' in self
92         assert isinstance(node, Node)
93         assert 'node_id' in node
94
95         pcu_id = self['pcu_id']
96         node_id = node['node_id']
97
98         if node_id in self['node_ids']:
99             i = self['node_ids'].index(node_id)
100             port = self['ports'][i]
101
102             self.api.db.do("DELETE FROM pcu_node" \
103                            " WHERE pcu_id = %(pcu_id)d" \
104                            " AND node_id = %(node_id)d",
105                            locals())
106
107             if commit:
108                 self.api.db.commit()
109
110             self['node_ids'].remove(node_id)
111             self['ports'].remove(port)
112
113     def sync(self, insert=False, validate=True):
114         AlchemyObj.sync(self, insert, validate):
115         if insert == True or 'id' not in self:
116             AlchemyObj.insert(self, dict(self))
117         else:
118             AlchemyObj.delete(self, dict(self))
119                 
120 class PCUs(list):
121     """
122     Representation of row(s) from the pcus table in the
123     database.
124     """
125
126     def __init__(self, api, pcu_filter = None, columns = None):
127         if not pcu_filter:
128             pcus = PCU().select()
129         elif isinstance(pcu_filter, int):
130             pcus = PCU().select(filter={'id': pcu_filter})
131         elif isinstance(pcu_filter, (list, tuple, set, int, long)):
132             pcus = PCU().select(filter={'pcu_id': pcu_filter})
133         elif isinstance(pcu_filter, dict):
134             pcus= PCU().select(filter=pcu_filter)
135         else:
136             raise PLCInvalidArgument, "Wrong pcu filter %r"%pcu_filter
137             sql += " AND (%s) %s" % pcu_filter.sql(api)
138
139         for pcu in pcus:
140             self.append(pcu)