Checked in a missing changeset
[plstackapi.git] / planetstack / core / api / slices.py
1 import re
2 from types import StringTypes
3 from django.contrib.auth import authenticate
4 from openstack.manager import OpenStackManager
5 from core.models import Slice
6 from core.api.sites import _get_sites
7
8 def _get_slices(filter):
9     if isinstance(filter, StringTypes) and filter.isdigit():
10         filter = int(filter)
11     if isinstance(filter, int):
12         slices = Slice.objects.filter(id=filter)
13     elif isinstance(filter, StringTypes):
14         slices = Slice.objects.filter(name=filter)
15     elif isinstance(filter, dict):
16         slices = Slice.objects.filter(**filter)
17     else:
18         slices = []
19     return slices
20     
21  
22 def add_slice(auth, fields):
23     user = authenticate(username=auth.get('username'),
24                         password=auth.get('password'))
25     auth['tenant'] = user.site.login_base
26
27     login_base = fields['name'][:fields['name'].find('_')]
28     sites = _get_sites(login_base) 
29     if sites: fields['site'] = sites[0]     
30     slice = Slice(**fields)
31     slice.os_manager = OpenStackManager(auth=auth, caller = user) 
32     slice.save()
33     return slice
34
35 def update_slice(auth, id, **fields):
36     user = authenticate(username=auth.get('username'),
37                         password=auth.get('password'))
38     auth['tenant'] = user.site.login_base
39
40     slices = _get_slices(id)
41     if not slices:
42         return
43     slice = slices[0]
44     sites = _get_sites(fields.get('site'))
45     if sites: fields['site'] = sites[0]
46
47     slice.os_manager = OpenStackManager(auth=auth, caller = user)
48     for (k,v) in fields.items():
49         setattr(slice, k, v)
50     slice.save()
51
52     return slice 
53
54 def delete_slice(auth, filter={}):
55     user = authenticate(username=auth.get('username'),
56                         password=auth.get('password'))
57     auth['tenant'] = user.site.login_base
58     slices = _get_slices(filter)
59     for slice in slices:
60         slice.os_manager = OpenStackManager(auth=auth, caller = user) 
61         slice.delete()
62     return 1
63
64 def get_slices(auth, filter={}):
65     user = authenticate(username=auth.get('username'),
66                         password=auth.get('password'))
67     if 'site' in filter:
68         sites = _get_sites(filter.get('site'))
69         if sites: filter['site'] = sites[0]
70     slices = _get_slices(filter)
71     return slices             
72         
73
74