Setting tag plcapi-5.4-2
[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.Interfaces import valid_ip, Interface, Interfaces
14 from PLC.Nodes import Node, Nodes
15
16 class PCU(Row):
17     """
18     Representation of a row in the pcus table. To use,
19     instantiate with a dict of values.
20     """
21
22     table_name = 'pcus'
23     primary_key = 'pcu_id'
24     join_tables = ['pcu_node']
25     fields = {
26         'pcu_id': Parameter(int, "PCU identifier"),
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"),
37         'last_updated': Parameter(int, "Date and time when node entry was created", ro = True),
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 class PCUs(Table):
114     """
115     Representation of row(s) from the pcus table in the
116     database.
117     """
118
119     def __init__(self, api, pcu_filter = None, columns = None):
120         Table.__init__(self, api, PCU, columns)
121
122         sql = "SELECT %s FROM view_pcus WHERE True" % \
123               ", ".join(self.columns)
124
125         if pcu_filter is not None:
126             if isinstance(pcu_filter, (list, tuple, set, int, long)):
127                 pcu_filter = Filter(PCU.fields, {'pcu_id': pcu_filter})
128             elif isinstance(pcu_filter, dict):
129                 pcu_filter = Filter(PCU.fields, pcu_filter)
130             else:
131                 raise PLCInvalidArgument, "Wrong pcu filter %r"%pcu_filter
132             sql += " AND (%s) %s" % pcu_filter.sql(api)
133
134         self.selectall(sql)