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