- renamed state to instantiation
[plcapi.git] / PLC / Slices.py
1 from types import StringTypes
2 import time
3
4 from PLC.Faults import *
5 from PLC.Parameter import Parameter
6 from PLC.Debug import profile
7 from PLC.Table import Row, Table
8 from PLC.SliceInstantiations import SliceInstantiations
9 import PLC.Persons
10
11 class Slice(Row):
12     """
13     Representation of a row in the slices table. To use, optionally
14     instantiate with a dict of values. Update as you would a
15     dict. Commit to the database with sync().To use, instantiate
16     with a dict of values.
17     """
18
19     fields = {
20         'slice_id': Parameter(int, "Slice type"),
21         'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
22         'name': Parameter(str, "Slice name", max = 32),
23         'instantiation': Parameter(str, "Slice instantiation state"),
24         'url': Parameter(str, "URL further describing this slice", max = 254),
25         'description': Parameter(str, "Slice description", max = 2048),
26         'max_nodes': Parameter(int, "Maximum number of nodes that can be assigned to this slice"),
27         'creator_person_id': Parameter(int, "Identifier of the account that created this slice"),
28         'created': Parameter(int, "Date and time when slice was created, in seconds since UNIX epoch"),
29         'expires': Parameter(int, "Date and time when slice expires, in seconds since UNIX epoch"),
30         'node_ids': Parameter([int], "List of nodes in this slice"),
31         'person_ids': Parameter([int], "List of accounts that can use this slice"),
32         'attribute_ids': Parameter([int], "List of slice attributes"),
33         }
34
35     def __init__(self, api, fields):
36         Row.__init__(self, fields)
37         self.api = api
38
39     def validate_name(self, name):
40         # N.B.: Responsibility of the caller to ensure that login_base
41         # portion of the slice name corresponds to a valid site, if
42         # desired.
43         conflicts = Slices(self.api, [name])
44         for slice_id, slice in conflicts.iteritems():
45             if 'slice_id' not in self or self['slice_id'] != slice_id:
46                 raise PLCInvalidArgument, "Slice name already in use"
47
48         return name
49
50     def validate_instantiation(self, instantiation):
51         instantiations = SliceInstantiations(self.api)
52         if instantiation not in instantiations:
53             raise PLCInvalidArgument, "No such instantiation state"
54
55         return state
56
57     def validate_expires(self, expires):
58         # N.B.: Responsibility of the caller to ensure that expires is
59         # not too far into the future.
60         if expires < time.time():
61             raise PLCInvalidArgument, "Expiration date must be in the future"
62
63         return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(expires))
64
65     def validate_creator_person_id(self, person_id):
66         persons = PLC.Persons.Persons(self.api, [person_id])
67         if not persons:
68             raise PLCInvalidArgument, "Invalid creator"
69
70         return person_id
71
72     def sync(self, commit = True):
73         """
74         Flush changes back to the database.
75         """
76
77         try:
78             if not self['name']:
79                 raise KeyError
80         except KeyError:
81             raise PLCInvalidArgument, "Slice name must be specified"
82
83         self.validate()
84
85         # Fetch a new slice_id if necessary
86         if 'slice_id' not in self:
87             # N.B.: Responsibility of the caller to ensure that
88             # max_slices is not exceeded.
89             rows = self.api.db.selectall("SELECT NEXTVAL('slices_slice_id_seq') AS slice_id")
90             if not rows:
91                 raise PLCDBError, "Unable to fetch new slice_id"
92             self['slice_id'] = rows[0]['slice_id']
93             insert = True
94         else:
95             insert = False
96
97         # Filter out fields that cannot be set or updated directly
98         slices_fields = self.api.db.fields('slices')
99         fields = dict(filter(lambda (key, value): key in slices_fields,
100                              self.items()))
101         for ro_field in 'created',:
102             if ro_field in fields:
103                 del fields[ro_field]
104
105         # Parameterize for safety
106         keys = fields.keys()
107         values = [self.api.db.param(key, value) for (key, value) in fields.items()]
108
109         if insert:
110             # Insert new row in slices table
111             sql = "INSERT INTO slices (%s) VALUES (%s)" % \
112                   (", ".join(keys), ", ".join(values))
113         else:
114             # Update existing row in slices table
115             columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
116             sql = "UPDATE slices SET " + \
117                   ", ".join(columns) + \
118                   " WHERE slice_id = %(slice_id)d"
119
120         self.api.db.do(sql, fields)
121
122         if commit:
123             self.api.db.commit()
124
125     def delete(self, commit = True):
126         """
127         Delete existing slice.
128         """
129
130         assert 'slice_id' in self
131
132         # Clean up miscellaneous join tables
133         for table in ['slice_node', 'slice_person', 'slice_attribute']:
134             self.api.db.do("DELETE FROM %s" \
135                            " WHERE slice_id = %d" % \
136                            (table, self['slice_id']), self)
137
138         # Mark as deleted
139         self['is_deleted'] = True
140         self.sync(commit)
141
142 class Slices(Table):
143     """
144     Representation of row(s) from the slices table in the
145     database.
146     """
147
148     def __init__(self, api, slice_id_or_name_list = None, fields = Slice.fields):
149         self.api = api
150
151         sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
152               ", ".join(fields)
153
154         if slice_id_or_name_list:
155             # Separate the list into integers and strings
156             slice_ids = filter(lambda slice_id: isinstance(slice_id, (int, long)),
157                                slice_id_or_name_list)
158             names = filter(lambda name: isinstance(name, StringTypes),
159                            slice_id_or_name_list)
160             sql += " AND (False"
161             if slice_ids:
162                 sql += " OR slice_id IN (%s)" % ", ".join(map(str, slice_ids))
163             if names:
164                 sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
165             sql += ")"
166
167         rows = self.api.db.selectall(sql)
168
169         for row in rows:
170             self[row['slice_id']] = slice = Slice(api, row)
171             for aggregate in 'person_ids', 'slice_ids', 'attribute_ids':
172                 if not slice.has_key(aggregate) or slice[aggregate] is None:
173                     slice[aggregate] = []
174                 else:
175                     slice[aggregate] = map(int, slice[aggregate].split(','))