unset None fields, if allowed
[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: PCUs.py,v 1.6 2006/10/25 14:29:13 mlhuang Exp $
8 #
9
10 from PLC.Faults import *
11 from PLC.Parameter import Parameter
12 from PLC.Debug import profile
13 from PLC.Table import Row, Table
14 from PLC.NodeNetworks import valid_ip, NodeNetwork, NodeNetworks
15 from PLC.Nodes import Node, Nodes
16
17 class PCU(Row):
18     """
19     Representation of a row in the pcus table. To use,
20     instantiate with a dict of values.
21     """
22
23     table_name = 'pcus'
24     primary_key = 'pcu_id'
25     join_tables = ['pcu_node']
26     fields = {
27         'pcu_id': Parameter(int, "PCU identifier"),
28         'site_id': Parameter(int, "Identifier of site where PCU is located"),
29         'hostname': Parameter(str, "PCU hostname", max = 254),
30         'ip': Parameter(str, "PCU IP address", max = 254),
31         'protocol': Parameter(str, "PCU protocol, e.g. ssh, https, telnet", max = 16, nullok = True),
32         'username': Parameter(str, "PCU username", max = 254, nullok = True),
33         'password': Parameter(str, "PCU username", max = 254, nullok = True),
34         'notes': Parameter(str, "Miscellaneous notes", max = 254, nullok = True),
35         'model': Parameter(str, "PCU model string", max = 32, nullok = True),
36         'node_ids': Parameter([int], "List of nodes that this PCU controls", ro = True),
37         'ports': Parameter([int], "List of the port numbers that each node is connected to", 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     def add_node(self, node, port, commit = True):
46         """
47         Add node to existing PCU.
48         """
49
50         assert 'pcu_id' in self
51         assert isinstance(node, Node)
52         assert isinstance(port, (int, long))
53         assert 'node_id' in node
54
55         pcu_id = self['pcu_id']
56         node_id = node['node_id']
57
58         if node_id not in self['node_ids'] and port not in self['ports']:
59             self.api.db.do("INSERT INTO pcu_node (pcu_id, node_id, port)" \
60                            " VALUES(%(pcu_id)d, %(node_id)d, %(port)d)",
61                            locals())
62
63             if commit:
64                 self.api.db.commit()
65
66             self['node_ids'].append(node_id)
67             self['ports'].append(port)
68
69     def remove_node(self, node, commit = True):
70         """
71         Remove node from existing PCU.
72         """
73
74         assert 'pcu_id' in self
75         assert isinstance(node, Node)
76         assert 'node_id' in node
77
78         pcu_id = self['pcu_id']
79         node_id = node['node_id']
80
81         if node_id in self['node_ids']:
82             i = self['node_ids'].index(node_id)
83             port = self['ports'][i]
84
85             self.api.db.do("DELETE FROM pcu_node" \
86                            " WHERE pcu_id = %(pcu_id)d" \
87                            " AND node_id = %(node_id)d",
88                            locals())
89
90             if commit:
91                 self.api.db.commit()
92
93             self['node_ids'].remove(node_id)
94             self['ports'].remove(port)
95
96 class PCUs(Table):
97     """
98     Representation of row(s) from the pcus table in the
99     database.
100     """
101
102     def __init__(self, api, pcu_ids = None):
103         self.api = api
104
105         # N.B.: Node IDs returned may be deleted.
106         sql = "SELECT %s FROM view_pcus" % \
107               ", ".join(PCU.fields)
108
109         if pcu_ids:
110             sql += " WHERE pcu_id IN (%s)" % ", ".join(map(str, pcu_ids))
111
112         rows = self.api.db.selectall(sql)
113
114         for row in rows:
115             self[row['pcu_id']] = pcu = PCU(api, row)
116             for aggregate in ['node_ids', 'ports']:
117                 if not pcu.has_key(aggregate) or pcu[aggregate] is None:
118                     pcu[aggregate] = []
119                 else:
120                     pcu[aggregate] = map(int, pcu[aggregate].split(','))