- Merge from PlanetLab Europe
[plcapi.git] / PLC / Slices.py
1 from types import StringTypes
2 import time
3 import re
4
5 from PLC.Faults import *
6 from PLC.Parameter import Parameter
7 from PLC.Filter import Filter
8 from PLC.Debug import profile
9 from PLC.Table import Row, Table
10 from PLC.SliceInstantiations import SliceInstantiation, SliceInstantiations
11 from PLC.Nodes import Node
12 from PLC.Persons import Person, Persons
13
14 class Slice(Row):
15     """
16     Representation of a row in the slices table. To use, optionally
17     instantiate with a dict of values. Update as you would a
18     dict. Commit to the database with sync().To use, instantiate
19     with a dict of values.
20     """
21
22     table_name = 'slices'
23     primary_key = 'slice_id'
24     join_tables = ['slice_node', 'slice_person', 'slice_attribute', 'peer_slice', 'node_slice_whitelist']
25     fields = {
26         'slice_id': Parameter(int, "Slice identifier"),
27         'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
28         'name': Parameter(str, "Slice name", max = 32),
29         'instantiation': Parameter(str, "Slice instantiation state"),
30         'url': Parameter(str, "URL further describing this slice", max = 254, nullok = True),
31         'description': Parameter(str, "Slice description", max = 2048, nullok = True),
32         'max_nodes': Parameter(int, "Maximum number of nodes that can be assigned to this slice"),
33         'creator_person_id': Parameter(int, "Identifier of the account that created this slice"),
34         'created': Parameter(int, "Date and time when slice was created, in seconds since UNIX epoch", ro = True),
35         'expires': Parameter(int, "Date and time when slice expires, in seconds since UNIX epoch"),
36         'node_ids': Parameter([int], "List of nodes in this slice", ro = True),
37         'person_ids': Parameter([int], "List of accounts that can use this slice", ro = True),
38         'slice_attribute_ids': Parameter([int], "List of slice attributes", ro = True),
39         'peer_id': Parameter(int, "Peer to which this slice belongs", nullok = True),
40         'peer_slice_id': Parameter(int, "Foreign slice identifier at peer", nullok = True),
41         }
42     # for Cache
43     class_key = 'name'
44     foreign_fields = ['instantiation', 'url', 'description', 'max_nodes', 'expires']
45     foreign_xrefs = [
46         {'field': 'node_ids' ,         'class': 'Node',   'table': 'slice_node' },
47         {'field': 'person_ids',        'class': 'Person', 'table': 'slice_person'},
48         {'field': 'creator_person_id', 'class': 'Person', 'table': 'unused-on-direct-refs'},
49         {'field': 'site_id',           'class': 'Site',   'table': 'unused-on-direct-refs'},
50     ]
51     # forget about this one, it is read-only anyway
52     # handling it causes Cache to re-sync all over again 
53     # 'created'
54
55     def validate_name(self, name):
56         # N.B.: Responsibility of the caller to ensure that login_base
57         # portion of the slice name corresponds to a valid site, if
58         # desired.
59
60         # 1. Lowercase.
61         # 2. Begins with login_base (letters or numbers).
62         # 3. Then single underscore after login_base.
63         # 4. Then letters, numbers, or underscores.
64         good_name = r'^[a-z0-9]+_[a-zA-Z0-9_]+$'
65         if not name or \
66            not re.match(good_name, name):
67             raise PLCInvalidArgument, "Invalid slice name"
68
69         conflicts = Slices(self.api, [name])
70         for slice in conflicts:
71             if 'slice_id' not in self or self['slice_id'] != slice['slice_id']:
72                 raise PLCInvalidArgument, "Slice name already in use, %s"%name
73
74         return name
75
76     def validate_instantiation(self, instantiation):
77         instantiations = [row['instantiation'] for row in SliceInstantiations(self.api)]
78         if instantiation not in instantiations:
79             raise PLCInvalidArgument, "No such instantiation state"
80
81         return instantiation
82
83     validate_created = Row.validate_timestamp
84
85     def validate_expires(self, expires):
86         # N.B.: Responsibility of the caller to ensure that expires is
87         # not too far into the future.
88         check_future = not ('is_deleted' in self and self['is_deleted'])
89         return Row.validate_timestamp(self, expires, check_future = check_future)
90
91     add_person = Row.add_object(Person, 'slice_person')
92     remove_person = Row.remove_object(Person, 'slice_person')
93
94     add_node = Row.add_object(Node, 'slice_node')
95     remove_node = Row.remove_object(Node, 'slice_node')
96
97     add_to_node_whitelist = Row.add_object(Node, 'node_slice_whitelist')
98     delete_from_node_whitelist = Row.remove_object(Node, 'node_slice_whitelist')
99
100     def sync(self, commit = True):
101         """
102         Add or update a slice.
103         """
104
105         # Before a new slice is added, delete expired slices
106         if 'slice_id' not in self:
107             expired = Slices(self.api, expires = -int(time.time()))
108             for slice in expired:
109                 slice.delete(commit)
110
111         Row.sync(self, commit)
112
113     def delete(self, commit = True):
114         """
115         Delete existing slice.
116         """
117
118         assert 'slice_id' in self
119
120         # Clean up miscellaneous join tables
121         for table in self.join_tables:
122             self.api.db.do("DELETE FROM %s WHERE slice_id = %d" % \
123                            (table, self['slice_id']))
124
125         # Mark as deleted
126         self['is_deleted'] = True
127         self.sync(commit)
128
129 class Slices(Table):
130     """
131     Representation of row(s) from the slices table in the
132     database.
133     """
134
135     def __init__(self, api, slice_filter = None, columns = None, expires = int(time.time())):
136         Table.__init__(self, api, Slice, columns)
137
138         sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
139               ", ".join(self.columns)
140
141         if expires is not None:
142             if expires >= 0:
143                 sql += " AND expires > %d" % expires
144             else:
145                 expires = -expires
146                 sql += " AND expires < %d" % expires
147
148         if slice_filter is not None:
149             if isinstance(slice_filter, (list, tuple, set)):
150                 # Separate the list into integers and strings
151                 ints = filter(lambda x: isinstance(x, (int, long)), slice_filter)
152                 strs = filter(lambda x: isinstance(x, StringTypes), slice_filter)
153                 slice_filter = Filter(Slice.fields, {'slice_id': ints, 'name': strs})
154                 sql += " AND (%s)" % slice_filter.sql(api, "OR")
155             elif isinstance(slice_filter, dict):
156                 slice_filter = Filter(Slice.fields, slice_filter)
157                 sql += " AND (%s)" % slice_filter.sql(api, "AND")
158             elif isinstance (slice_filter, StringTypes):
159                 slice_filter = Filter(Slice.fields, {'name':[slice_filter]})
160                 sql += " AND (%s)" % slice_filter.sql(api, "AND")
161             elif isinstance (slice_filter, int):
162                 slice_filter = Filter(Slice.fields, {'slice_id':[slice_filter]})
163                 sql += " AND (%s)" % slice_filter.sql(api, "AND")
164             else:
165                 raise PLCInvalidArgument, "Wrong slice filter %r"%slice_filter
166
167         self.selectall(sql)