blob: fbacb67c831129ecfff409fa6c304c3167f0276f [file] [log] [blame]
Tony Mackc59fcaf2013-06-10 11:14:04 -04001import time
Tony Mack0553f282013-06-10 22:54:50 -04002import traceback
Tony Mack70780e92013-06-30 12:46:16 -04003import commands
Sapan Bhatia66f4e612013-07-02 12:12:38 -04004import threading
5
Tony Mackc59fcaf2013-06-10 11:14:04 -04006from datetime import datetime
Tony Mack79a49c82013-06-15 23:51:57 -04007from collections import defaultdict
Tony Mackc59fcaf2013-06-10 11:14:04 -04008from core.models import *
9from django.db.models import F, Q
10from openstack.manager import OpenStackManager
Sapan Bhatia43c3a772013-07-03 11:19:07 -040011from util.logger import Logger, logging, logger
Tony Mack5c0c4552013-07-03 09:36:51 -040012#from timeout import timeout
Tony Mackc59fcaf2013-06-10 11:14:04 -040013
14
Tony Mack79a49c82013-06-15 23:51:57 -040015logger = Logger(logfile='observer.log', level=logging.INFO)
16
Tony Mackc59fcaf2013-06-10 11:14:04 -040017class OpenStackObserver:
18
19 def __init__(self):
Tony Mack0553f282013-06-10 22:54:50 -040020 self.manager = OpenStackManager()
Sapan Bhatia66f4e612013-07-02 12:12:38 -040021 # The Condition object that gets signalled by Feefie events
22 self.event_cond = threading.Condition()
23
24 def wait_for_event(self, timeout):
25 self.event_cond.acquire()
26 self.event_cond.wait(timeout)
27 self.event_cond.release()
28
29 def wake_up(self):
Sapan Bhatia43c3a772013-07-03 11:19:07 -040030 logger.info('Wake up routine called. Event cond %r'%self.event_cond)
Sapan Bhatia66f4e612013-07-02 12:12:38 -040031 self.event_cond.acquire()
32 self.event_cond.notify()
33 self.event_cond.release()
Tony Mack0553f282013-06-10 22:54:50 -040034
35 def run(self):
36 if not self.manager.enabled or not self.manager.has_openstack:
37 return
38 while True:
39 try:
Sapan Bhatia43c3a772013-07-03 11:19:07 -040040 logger.info('Observer run loop')
Tony Mack6795fbe2013-06-11 10:10:24 -040041 #self.sync_roles()
Sapan Bhatia43c3a772013-07-03 11:19:07 -040042 logger.info('Calling sync tenants')
Tony Mack0553f282013-06-10 22:54:50 -040043 self.sync_tenants()
44 self.sync_users()
Tony Mack79a49c82013-06-15 23:51:57 -040045 self.sync_user_tenant_roles()
Tony Mack2bd5b412013-06-11 21:05:06 -040046 self.sync_slivers()
Tony Mack79a49c82013-06-15 23:51:57 -040047 self.sync_sliver_ips()
Sapan Bhatia43c3a772013-07-03 11:19:07 -040048 logger.info('Calling sync external routes')
Tony Mack16f51e02013-07-01 10:33:29 -040049 self.sync_external_routes()
Sapan Bhatia43c3a772013-07-03 11:19:07 -040050 self.wait_for_event(timeout=300)
51 logger.info('Observer woken up')
Tony Mack0553f282013-06-10 22:54:50 -040052 except:
53 traceback.print_exc()
Tony Mackc59fcaf2013-06-10 11:14:04 -040054
Tony Mackf8d4a462013-06-10 23:25:30 -040055 def sync_roles(self):
56 """
57 save all role that don't already exist in keystone. Remove keystone roles that
58 don't exist in planetstack
59 """
60 # sync all roles that don't already in keystone
61 keystone_roles = self.manager.driver.shell.keystone.roles.findall()
62 keystone_role_names = [kr.name for kr in keystone_roles]
63 pending_roles = Role.objects.all()
64 pending_role_names = [r.role_type for r in pending_roles]
65 for role in pending_roles:
66 if role.role_type not in keystone_role_names:
Tony Mack79a49c82013-06-15 23:51:57 -040067 try:
68 self.manager.save_role(role)
69 logger.info("save role: %s" % (role))
70 except:
71 logger.log_exc("save role failed: %s" % role)
72 traceback.print_exc()
Tony Mackf8d4a462013-06-10 23:25:30 -040073
Tony Mack79a49c82013-06-15 23:51:57 -040074 # don't delete roles for now
75 """
76 # delete keystone roles that don't exist in planetstack
Tony Mackf8d4a462013-06-10 23:25:30 -040077 for keystone_role in keystone_roles:
78 if keystone_role.name == 'admin':
79 continue
80 if keystone_role.name not in pending_role_names:
Tony Mack79a49c82013-06-15 23:51:57 -040081 try:
82 self.manager.driver.delete_role({id: keystone_role.id})
83 except:
84 traceback.print_exc()
85 """
Tony Mackf8d4a462013-06-10 23:25:30 -040086
Tony Mackdb9be932013-06-10 13:42:42 -040087 def sync_tenants(self):
Tony Mackc59fcaf2013-06-10 11:14:04 -040088 """
Tony Mackdb9be932013-06-10 13:42:42 -040089 Save all sites and sliceswhere enacted < updated or enacted == None.
90 Remove sites and slices that no don't exist in openstack db if they
91 have an enacted time (enacted != None).
Tony Mackc59fcaf2013-06-10 11:14:04 -040092 """
93 # get all sites that need to be synced (enacted < updated or enacted is None)
94 pending_sites = Site.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
95 for site in pending_sites:
Tony Mack79a49c82013-06-15 23:51:57 -040096 try:
97 self.manager.save_site(site)
98 logger.info("saved site %s" % site)
99 except:
100 logger.log_exc("save site failed: %s" % site)
Tony Mackc59fcaf2013-06-10 11:14:04 -0400101
Tony Mackc59fcaf2013-06-10 11:14:04 -0400102 # get all slices that need to be synced (enacted < updated or enacted is None)
103 pending_slices = Slice.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
104 for slice in pending_slices:
Tony Mack79a49c82013-06-15 23:51:57 -0400105 try:
106 self.manager.init_caller(slice.creator, slice.creator.site.login_base)
107 self.manager.save_slice(slice)
108 logger.info("saved slice %s" % slice)
109 except:
110 logger.log_exc("save slice failed: %s" % slice)
Tony Mackc59fcaf2013-06-10 11:14:04 -0400111
Tony Mackdb9be932013-06-10 13:42:42 -0400112 # get all sites that where enacted != null. We can assume these sites
113 # have previously been synced and need to be checed for deletion.
114 sites = Site.objects.filter(enacted__isnull=False)
115 site_dict = {}
116 for site in sites:
117 site_dict[site.login_base] = site
118
Tony Mackc59fcaf2013-06-10 11:14:04 -0400119 # get all slices that where enacted != null. We can assume these slices
120 # have previously been synced and need to be checed for deletion.
121 slices = Slice.objects.filter(enacted__isnull=False)
122 slice_dict = {}
123 for slice in slices:
124 slice_dict[slice.name] = slice
125
126 # delete keystone tenants that don't have a site record
127 tenants = self.manager.driver.shell.keystone.tenants.findall()
Tony Mack79a49c82013-06-15 23:51:57 -0400128 system_tenants = ['admin','service']
Tony Mackc59fcaf2013-06-10 11:14:04 -0400129 for tenant in tenants:
Tony Mack586d5c92013-06-20 12:04:30 -0400130 if tenant.name in system_tenants:
Tony Mackdb9be932013-06-10 13:42:42 -0400131 continue
132 if tenant.name not in site_dict and tenant.name not in slice_dict:
Tony Mack79a49c82013-06-15 23:51:57 -0400133 try:
134 self.manager.driver.delete_tenant(tenant.id)
135 logger.info("deleted tenant: %s" % (tenant))
136 except:
137 logger.log_exc("delete tenant failed: %s" % tenant)
Tony Mackdb9be932013-06-10 13:42:42 -0400138
Tony Mackc59fcaf2013-06-10 11:14:04 -0400139
140 def sync_users(self):
141 """
142 save all users where enacted < updated or enacted == None. Remove users that
143 no don't exist in openstack db if they have an enacted time (enacted != None).
144 """
145 # get all users that need to be synced (enacted < updated or enacted is None)
146 pending_users = User.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
147 for user in pending_users:
Tony Mack79a49c82013-06-15 23:51:57 -0400148 try:
149 self.manager.save_user(user)
150 logger.info("saved user: %s" % (user))
151 except:
152 logger.log_exc("save user failed: %s" %user)
Tony Mackc59fcaf2013-06-10 11:14:04 -0400153
154 # get all users that where enacted != null. We can assume these users
155 # have previously been synced and need to be checed for deletion.
156 users = User.objects.filter(enacted__isnull=False)
157 user_dict = {}
158 for user in users:
159 user_dict[user.kuser_id] = user
160
161 # delete keystone users that don't have a user record
Tony Mack79a49c82013-06-15 23:51:57 -0400162 system_users = ['admin', 'nova', 'quantum', 'glance', 'cinder', 'swift', 'service']
Tony Mack0553f282013-06-10 22:54:50 -0400163 users = self.manager.driver.shell.keystone.users.findall()
Tony Mackc59fcaf2013-06-10 11:14:04 -0400164 for user in users:
Tony Mack79a49c82013-06-15 23:51:57 -0400165 if user.name in system_users:
Tony Mackdb9be932013-06-10 13:42:42 -0400166 continue
Tony Mackc59fcaf2013-06-10 11:14:04 -0400167 if user.id not in user_dict:
Tony Mack79a49c82013-06-15 23:51:57 -0400168 try:
169 #self.manager.driver.delete_user(user.id)
170 logger.info("deleted user: %s" % user)
171 except:
172 logger.log_exc("delete user failed: %s" % user)
173
174
175 def sync_user_tenant_roles(self):
176 """
177 Save all site privileges and slice memberships wheree enacted < updated or
178 enacted == None. Remove ones that don't exist in openstack db if they have
179 an enacted time (enacted != None).
180 """
181 # sync site privileges
182 pending_site_privileges = SitePrivilege.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
183 for site_priv in pending_site_privileges:
184 try:
185 self.manager.save_site_privilege(site_priv)
186 logger.info("saved site privilege: %s" % (site_priv))
187 except: logger.log_exc("save site privilege failed: %s " % site_priv)
188
189 # sync slice memberships
190 pending_slice_memberships = SliceMembership.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
191 for slice_memb in pending_slice_memberships:
192 try:
193 self.manager.save_slice_membership(slice_memb)
194 logger.info("saved slice membership: %s" % (slice_memb))
195 except: logger.log_exc("save slice membership failed: %s" % slice_memb)
196
197 # get all site privileges and slice memberships that have been enacted
198 user_tenant_roles = defaultdict(list)
199 for site_priv in SitePrivilege.objects.filter(enacted__isnull=False):
200 user_tenant_roles[(site_priv.user.kuser_id, site_priv.site.tenant_id)].append(site_priv.role.role)
201 for slice_memb in SliceMembership.objects.filter(enacted__isnull=False):
202 user_tenant_roles[(slice_memb.user.kuser_id, slice_memb.slice.tenant_id)].append(slice_memb.role.role)
203
204 # Some user tenant role aren't stored in planetstack but they must be preserved.
205 # Role that fall in this category are
206 # 1. Never remove a user's role that their home site
207 # 2. Never remove a user's role at a slice they've created.
208 # Keep track of all roles that must be preserved.
209 users = User.objects.all()
210 preserved_roles = {}
211 for user in users:
212 tenant_ids = [s['tenant_id'] for s in user.slices.values()]
213 tenant_ids.append(user.site.tenant_id)
214 preserved_roles[user.kuser_id] = tenant_ids
215
216
217 # begin removing user tenant roles from keystone. This is stored in the
218 # Metadata table.
219 for metadata in self.manager.driver.shell.keystone_db.get_metadata():
220 # skip admin roles
221 if metadata.user_id == self.manager.driver.admin_user.id:
222 continue
223 # skip preserved tenant ids
224 if metadata.user_id in preserved_roles and \
225 metadata.tenant_id in preserved_roles[metadata.user_id]:
226 continue
227 # get roles for user at this tenant
228 user_tenant_role_ids = user_tenant_roles.get((metadata.user_id, metadata.tenant_id), [])
229
230 if user_tenant_role_ids:
231 # The user has roles at the tenant. Check if roles need to
232 # be updated.
233 user_keystone_role_ids = metadata.data.get('roles', [])
234 for role_id in user_keystone_role_ids:
235 if role_id not in user_tenant_role_ids:
236 user_keystone_role_ids.pop(user_keystone_role_ids.index(role_id))
237 else:
238 # The user has no roles at this tenant.
239 metadata.data['roles'] = []
240 #session.add(metadata)
241 logger.info("pruning metadata for %s at %s" % (metadata.user_id, metadata.tenant_id))
242
Tony Mackc59fcaf2013-06-10 11:14:04 -0400243 def sync_slivers(self):
244 """
245 save all slivers where enacted < updated or enacted == None. Remove slivers that
246 no don't exist in openstack db if they have an enacted time (enacted != None).
247 """
248 # get all users that need to be synced (enacted < updated or enacted is None)
249 pending_slivers = Sliver.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
250 for sliver in pending_slivers:
Tony Mack9b7a8bd2013-06-24 15:08:01 -0400251 if sliver.creator:
Tony Mack79a49c82013-06-15 23:51:57 -0400252 try:
253 # update manager context
254 self.manager.init_caller(sliver.creator, sliver.slice.name)
255 self.manager.save_sliver(sliver)
Tony Macke3f8d862013-07-01 20:40:55 -0400256 logger.info("saved sliver: %s" % (sliver))
Tony Mack79a49c82013-06-15 23:51:57 -0400257 except:
258 logger.log_exc("save sliver failed: %s" % sliver)
Tony Mackc59fcaf2013-06-10 11:14:04 -0400259
Tony Mackaa8ad5f2013-06-24 13:50:06 -0400260 # get all slivers where enacted != null. We can assume these users
Tony Mackc59fcaf2013-06-10 11:14:04 -0400261 # have previously been synced and need to be checed for deletion.
262 slivers = Sliver.objects.filter(enacted__isnull=False)
263 sliver_dict = {}
264 for sliver in slivers:
265 sliver_dict[sliver.instance_id] = sliver
266
267 # delete sliver that don't have a sliver record
268 ctx = self.manager.driver.shell.nova_db.ctx
269 instances = self.manager.driver.shell.nova_db.instance_get_all(ctx)
270 for instance in instances:
Tony Mackaa8ad5f2013-06-24 13:50:06 -0400271 if instance.uuid not in sliver_dict:
Tony Mack79a49c82013-06-15 23:51:57 -0400272 try:
273 # lookup tenant and update context
274 tenant = self.manager.driver.shell.keystone.tenants.find(id=instance.project_id)
275 self.manager.init_admin(tenant=tenant.name)
Tony Mackaa8ad5f2013-06-24 13:50:06 -0400276 self.manager.driver.destroy_instance(instance.uuid)
Tony Mack79a49c82013-06-15 23:51:57 -0400277 logger.info("destroyed sliver: %s" % (instance))
278 except:
279 logger.log_exc("destroy sliver failed: %s" % instance)
280
281
282 def sync_sliver_ips(self):
283 # fill in null ip addresses
284 slivers = Sliver.objects.filter(ip=None)
285 for sliver in slivers:
286 # update connection
287 self.manager.init_admin(tenant=sliver.slice.name)
Tony Mack70780e92013-06-30 12:46:16 -0400288 servers = self.manager.driver.shell.nova.servers.findall(id=sliver.instance_id)
Tony Mack79a49c82013-06-15 23:51:57 -0400289 if not servers:
290 continue
291 server = servers[0]
292 ips = server.addresses.get(sliver.slice.name, [])
293 if not ips:
294 continue
295 sliver.ip = ips[0]['addr']
296 sliver.save()
297 logger.info("saved sliver ip: %s %s" % (sliver, ips[0]))
Tony Mack70780e92013-06-30 12:46:16 -0400298
299 def sync_external_routes(self):
300 routes = self.manager.driver.get_external_routes()
Tony Mack16f51e02013-07-01 10:33:29 -0400301 subnets = self.manager.driver.shell.quantum.list_subnets()['subnets']
Tony Mack70780e92013-06-30 12:46:16 -0400302 for subnet in subnets:
Tony Mack16f51e02013-07-01 10:33:29 -0400303 try:
304 self.manager.driver.add_external_route(subnet, routes)
305 except:
306 logger.log_exc("failed to add external route for subnet %s" % subnet)
Tony Mack70780e92013-06-30 12:46:16 -0400307