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