from types import StringTypes
+import time
+import re
+import datetime
from PLC.Faults import *
-from PLC.Parameter import Parameter
+from PLC.Parameter import Parameter, Mixed
from PLC.Debug import profile
-from PLC.Table import Row, Table
+from PLC.Nodes import Node
+from PLC.Persons import Person, Persons
+from PLC.SlicePersons import SlicePerson, SlicePersons
+from PLC.SliceNodes import SliceNode, SliceNodes
+from PLC.SliceTags import SliceTag, SliceTags
+from PLC.Timestamp import Timestamp
+from PLC.Storage.AlchemyObject import AlchemyObj
-class Slice(Row):
+class Slice(AlchemyObj):
"""
- Representation of a row in the slices table. To use, instantiate
+ Representation of a row in the slices table. To use, optionally
+ instantiate with a dict of values. Update as you would a
+ dict. Commit to the database with sync().To use, instantiate
with a dict of values.
"""
+ tablename = 'slices'
+
fields = {
- 'slice_id': Parameter(int, "Slice type"),
+ 'slice_id': Parameter(int, "Slice identifier", primary_key=True),
+ 'site_id': Parameter(int, "Identifier of the site to which this slice belongs"),
+ 'tenant_id': Parameter(int, "Keystone tenant identifier"),
+ 'name': Parameter(str, "Slice name", max = 32),
+ 'instantiation': Parameter(str, "Slice instantiation state", nullok=True),
+ 'url': Parameter(str, "URL further describing this slice", max = 254, nullok = True),
+ 'description': Parameter(str, "Slice description", max = 2048, nullok = True),
+ 'max_nodes': Parameter(int, "Maximum number of nodes that can be assigned to this slice"),
+ 'creator_person_id': Parameter(str, "Identifier of the account that created this slice"),
+ 'created': Parameter(datetime, "Date and time when slice was created, in seconds since UNIX epoch", ro = True),
+ 'expires': Parameter(datetime, "Date and time when slice expires, in seconds since UNIX epoch"),
+ 'node_ids': Parameter([str], "List of nodes in this slice", joined = True),
+ 'person_ids': Parameter([str], "List of accounts that can use this slice", joined = True),
+ 'slice_tag_ids': Parameter([int], "List of slice attributes", joined = True),
+ 'peer_id': Parameter(int, "Peer to which this slice belongs", nullok = True),
+ 'peer_slice_id': Parameter(int, "Foreign slice identifier at peer", nullok = True),
}
+ tags = {}
- def __init__(self, api, fields):
- self.api = api
- dict.__init__(fields)
+ 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.
- def commit(self):
- # XXX
- pass
+ # 1. Lowercase.
+ # 2. Begins with login_base (letters or numbers).
+ # 3. Then single underscore after login_base.
+ # 4. Then letters, numbers, or underscores.
+ good_name = r'^[a-z0-9]+_[a-zA-Z0-9_]+$'
+ if not name or \
+ not re.match(good_name, name):
+ raise PLCInvalidArgument, "Invalid slice name"
- def delete(self):
- # XXX
- pass
+ conflicts = Slices(self.api, [name])
+ for slice in conflicts:
+ if 'slice_id' not in self or self['slice_id'] != slice.slice_id:
+ raise PLCInvalidArgument, "Slice name already in use, %s"%name
-class Slices(Table):
+ return name
+
+ def validate_expires(self, expires):
+ # N.B.: Responsibility of the caller to ensure that expires is
+ # not too far into the future.
+ check_future = not ('is_deleted' in self and self['is_deleted'])
+ return Timestamp.sql_validate( expires, check_future = check_future)
+
+ #add_person = Row.add_object(Person, 'slice_person')
+ #remove_person = Row.remove_object(Person, 'slice_person')
+
+ #add_node = Row.add_object(Node, 'slice_node')
+ #remove_node = Row.remove_object(Node, 'slice_node')
+
+ #add_to_node_whitelist = Row.add_object(Node, 'node_slice_whitelist')
+ #delete_from_node_whitelist = Row.remove_object(Node, 'node_slice_whitelist')
+
+ def sync(self, commit = True, validate=True):
+ """
+ Add or update a slice.
+ """
+ # sync the nova record and the plc record
+ AlchemyObj.sync(self, commit=commit, validate=validate)
+ # create the nova record
+ nova_fields = ['enabled', 'name', 'description']
+ nova_can_update = lambda (field, value): field in nova_fields
+ nova_slice = dict(filter(nova_can_update, self.items()))
+ if 'slice_id' not in self:
+ # Before a new slice is added, delete expired slices
+ #expired = Slices(self.api, expires = -int(time.time()))
+ #for slice in expired:
+ # slice.delete(commit)
+ self.object = self.api.client_shell.keystone.tenants.create(**nova_slice)
+ self['tenant_id'] = self.object.id
+ AlchemyObj.insert(self, dict(self))
+ else:
+ self.object = self.api.client_shell.keystone.tenants.update(self['tenant_id'], **nova_slice)
+ AlchemyObj.update(self, {'slice_id': self['slice_id']}, dict(self))
+
+ def delete(self, commit = True):
+ """
+ Delete existing slice.
+ """
+ assert 'slice_id' in self
+ assert 'tenant_id' in self
+
+ # delete the nova object
+ tenant = self.api.client_shell.keystone.tenants.find(id=self['tenant_id'])
+ self.api.client_shell.keystone.tenants.delete(tenant)
+
+ # delete relationships
+ SlicePerson().delete(self, filter={'slice_id': self['slice_id']})
+ SliceNode().delete(self, filter={'slice_id': self['slice_id']})
+ SliceTag().delete(self, filter={'slice_id': self['slice_id']})
+
+ # delete slice
+ AlchemyObj.delete(self, dict(self))
+
+
+class Slices(list):
"""
Representation of row(s) from the slices table in the
database.
"""
- def __init__(self, api, slice_id_list = None):
- # XXX
- pass
+ def __init__(self, api, slice_filter = None, columns = None, expires = int(time.time())):
+
+ # the view that we're selecting upon: start with view_slices
+ if not slice_filter:
+ slices = Slice().select()
+ elif isinstance (slice_filter, StringTypes):
+ slices = Slice().select(filter={'name': slice_filter})
+ elif isinstance(slice_filter, dict):
+ slices = Slice().select(filter=slice_filter)
+ elif isinstance(slice_filter, (list, tuple, set)):
+ slices = Slice().select()
+ slices = [slice for slice in slices if slice.id in slice_filter]
+ else:
+ raise PLCInvalidArgument, "Wrong slice filter %r"%slice_filter
+
+ for slice in slices:
+ slice = Slice(api, object=slice)
+ if not columns or 'person_ids' in columns:
+ slice_persons = SlicePerson().select(filter={'slice_id': slice.id})
+ slice['person_ids'] = [rec.person_id for rec in slice_persons]
+
+ if not columns or 'node_ids' in columns:
+ slice_nodes = SliceNode().select(filter={'slice_id': slice.id})
+ slice['node_ids'] = [rec.node_id for rec in slice_nodes]
+
+ if not columns or 'slice_tag_ids' in columns:
+ slice_tags = SliceTag().select(filter={'slice_id': slice.id})
+ slice['slice_tag_ids'] = [rec.slice_tag_id for rec in slice_tags]
+
+ self.append(slice)