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