from types import StringTypes
import time
+import re
from PLC.Faults import *
from PLC.Parameter import Parameter
from PLC.Debug import profile
from PLC.Table import Row, Table
from PLC.SliceInstantiations import SliceInstantiations
+from PLC.Nodes import Node, Nodes
import PLC.Persons
class Slice(Row):
with a dict of values.
"""
+ table_name = 'slices'
+ primary_key = 'slice_id'
fields = {
- 'slice_id': Parameter(int, "Slice type"),
+ 'slice_id': Parameter(int, "Slice identifier"),
'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
'name': Parameter(str, "Slice name", max = 32),
'instantiation': Parameter(str, "Slice instantiation state"),
'expires': Parameter(int, "Date and time when slice expires, in seconds since UNIX epoch"),
'node_ids': Parameter([int], "List of nodes in this slice", ro = True),
'person_ids': Parameter([int], "List of accounts that can use this slice", ro = True),
- 'attribute_ids': Parameter([int], "List of slice attributes", ro = True),
+ 'slice_attribute_ids': Parameter([int], "List of slice attributes", ro = True),
}
- def __init__(self, api, fields):
- Row.__init__(self, fields)
- self.api = api
-
def validate_name(self, name):
# N.B.: Responsibility of the caller to ensure that login_base
# portion of the slice name corresponds to a valid site, if
# desired.
+
+ # 1. Lowercase.
+ # 2. Begins with login_base (only letters).
+ # 3. Then single underscore after login_base.
+ # 4. Then letters, numbers, or underscores.
+ good_name = r'^[a-z]+_[a-z0-9_]+$'
+ if not name or \
+ not re.match(good_name, name):
+ raise PLCInvalidArgument, "Invalid slice name"
+
conflicts = Slices(self.api, [name])
for slice_id, slice in conflicts.iteritems():
if 'slice_id' not in self or self['slice_id'] != slice_id:
if instantiation not in instantiations:
raise PLCInvalidArgument, "No such instantiation state"
- return state
+ return instantiation
def validate_expires(self, expires):
# N.B.: Responsibility of the caller to ensure that expires is
slice_id = self['slice_id']
person_id = person['person_id']
- self.api.db.do("INSERT INTO slice_person (person_id, slice_id)" \
- " VALUES(%(person_id)d, %(slice_id)d)",
- locals())
- if commit:
- self.api.db.commit()
+ if person_id not in self['person_ids']:
+ assert slice_id not in person['slice_ids']
- if 'person_ids' in self and person_id not in self['person_ids']:
- self['person_ids'].append(person_id)
+ self.api.db.do("INSERT INTO slice_person (person_id, slice_id)" \
+ " VALUES(%(person_id)d, %(slice_id)d)",
+ locals())
- if 'slice_ids' in person and slice_id not in person['slice_ids']:
+ if commit:
+ self.api.db.commit()
+
+ self['person_ids'].append(person_id)
person['slice_ids'].append(slice_id)
def remove_person(self, person, commit = True):
slice_id = self['slice_id']
person_id = person['person_id']
- self.api.db.do("DELETE FROM slice_person" \
- " WHERE person_id = %(person_id)d" \
- " AND slice_id = %(slice_id)d",
- locals())
- if commit:
- self.api.db.commit()
+ if person_id in self['person_ids']:
+ assert slice_id in person['slice_ids']
- if 'person_ids' in self and person_id in self['person_ids']:
- self['person_ids'].remove(person_id)
+ self.api.db.do("DELETE FROM slice_person" \
+ " WHERE person_id = %(person_id)d" \
+ " AND slice_id = %(slice_id)d",
+ locals())
- if 'slice_ids' in person and slice_id in person['slice_ids']:
+ if commit:
+ self.api.db.commit()
+
+ self['person_ids'].remove(person_id)
person['slice_ids'].remove(slice_id)
def add_node(self, node, commit = True):
"""
assert 'slice_id' in self
- assert isinstance(node, PLC.Nodes.Node)
+ assert isinstance(node, Node)
assert 'node_id' in node
slice_id = self['slice_id']
node_id = node['node_id']
- self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
- " VALUES(%(node_id)d, %(slice_id)d)",
- locals())
- if commit:
- self.api.db.commit()
+ if node_id not in self['node_ids']:
+ assert slice_id not in node['slice_ids']
- if 'node_ids' in self and node_id not in self['node_ids']:
- self['node_ids'].append(node_id)
+ self.api.db.do("INSERT INTO slice_node (node_id, slice_id)" \
+ " VALUES(%(node_id)d, %(slice_id)d)",
+ locals())
+
+ if commit:
+ self.api.db.commit()
- if 'slice_ids' in node and slice_id not in node['slice_ids']:
+ self['node_ids'].append(node_id)
node['slice_ids'].append(slice_id)
def remove_node(self, node, commit = True):
"""
assert 'slice_id' in self
- assert isinstance(node, PLC.Nodes.Node)
+ assert isinstance(node, Node)
assert 'node_id' in node
slice_id = self['slice_id']
node_id = node['node_id']
- self.api.db.do("DELETE FROM slice_node" \
- " WHERE node_id = %(node_id)d" \
- " AND slice_id = %(slice_id)d",
- locals())
- if commit:
- self.api.db.commit()
+ if node_id in self['node_ids']:
+ assert slice_id in node['slice_ids']
- if 'node_ids' in self and node_id in self['node_ids']:
- self['node_ids'].remove(node_id)
+ self.api.db.do("DELETE FROM slice_node" \
+ " WHERE node_id = %(node_id)d" \
+ " AND slice_id = %(slice_id)d",
+ locals())
+
+ if commit:
+ self.api.db.commit()
- if 'slice_ids' in node and slice_id in node['slice_ids']:
+ self['node_ids'].remove(node_id)
node['slice_ids'].remove(slice_id)
def sync(self, commit = True):
"""
- Flush changes back to the database.
+ Add or update a slice.
"""
- try:
- if not self['name']:
- raise KeyError
- except KeyError:
- raise PLCInvalidArgument, "Slice name must be specified"
-
- self.validate()
-
- # Fetch a new slice_id if necessary
+ # Before a new slice is added, delete expired slices
if 'slice_id' not in self:
- # N.B.: Responsibility of the caller to ensure that
- # max_slices is not exceeded.
- rows = self.api.db.selectall("SELECT NEXTVAL('slices_slice_id_seq') AS slice_id")
- if not rows:
- raise PLCDBError, "Unable to fetch new slice_id"
- self['slice_id'] = rows[0]['slice_id']
- insert = True
- else:
- insert = False
-
- # Filter out fields that cannot be set or updated directly
- slices_fields = self.api.db.fields('slices')
- fields = dict(filter(lambda (key, value): \
- key in slices_fields and \
- (key not in self.fields or not self.fields[key].ro),
- self.items()))
-
- # Parameterize for safety
- keys = fields.keys()
- values = [self.api.db.param(key, value) for (key, value) in fields.items()]
-
- if insert:
- # Insert new row in slices table
- sql = "INSERT INTO slices (%s) VALUES (%s)" % \
- (", ".join(keys), ", ".join(values))
- else:
- # Update existing row in slices table
- columns = ["%s = %s" % (key, value) for (key, value) in zip(keys, values)]
- sql = "UPDATE slices SET " + \
- ", ".join(columns) + \
- " WHERE slice_id = %(slice_id)d"
-
- self.api.db.do(sql, fields)
-
- if commit:
- self.api.db.commit()
+ expired = Slices(self.api, expires = -int(time.time())).values()
+ for slice in expired:
+ slice.delete(commit)
+
+ Row.sync(self, commit)
def delete(self, commit = True):
"""
database.
"""
- def __init__(self, api, slice_id_or_name_list = None, fields = Slice.fields):
+ def __init__(self, api, slice_id_or_name_list = None, expires = int(time.time())):
self.api = api
sql = "SELECT %s FROM view_slices WHERE is_deleted IS False" % \
- ", ".join(fields)
+ ", ".join(Slice.fields)
+
+ if expires is not None:
+ if expires >= 0:
+ sql += " AND expires > %(expires)d"
+ else:
+ expires = -expires
+ sql += " AND expires < %(expires)d"
if slice_id_or_name_list:
# Separate the list into integers and strings
sql += " OR name IN (%s)" % ", ".join(api.db.quote(names))
sql += ")"
- rows = self.api.db.selectall(sql)
+ rows = self.api.db.selectall(sql, locals())
for row in rows:
self[row['slice_id']] = slice = Slice(api, row)
- for aggregate in 'person_ids', 'slice_ids', 'attribute_ids':
+ for aggregate in 'node_ids', 'person_ids', 'slice_attribute_ids':
if not slice.has_key(aggregate) or slice[aggregate] is None:
slice[aggregate] = []
else: