Пример #1
0
    def handle(self, request, data):

        try:
        
            with transaction.atomic():

                curr_prjname = self.request.user.tenant_name

                q_args = {
                    'registration__regid' : int(data['regid']),
                    'project__projectname' : curr_prjname,
                    'flowstatus' : PSTATUS_RENEW_MEMB
                }                
                prj_reqs = PrjRequest.objects.filter(**q_args)
                if len(prj_reqs) == 0:
                    return True
                
                q_args = {
                    'registration__regid' : int(data['regid']),
                    'project__projectname' : curr_prjname
                }
                
                prj_exp = Expiration.objects.filter(**q_args)
                prj_exp.update(expdate=data['expiration'])
                
                #
                # Update the max expiration per user
                #
                user_reg = Registration.objects.get(regid=int(data['regid']))
                if data['expiration'] > user_reg.expdate:
                    user_reg.expdate = data['expiration']
                    user_reg.save()

                tmpres = EMail.objects.filter(registration=user_reg)
                user_mail = tmpres[0].email if len(tmpres) > 0 else None

                #
                # Clear requests
                #
                prj_reqs.delete()

            #
            # send notification to the user and cloud admin
            #
            noti_params = {
                'username' : user_reg.username,
                'project' : request.user.tenant_name,
                'expiration' : data['expiration'].strftime("%d %B %Y")
            }

            notifyUser(request=request, rcpt=user_mail, action=USER_RENEWED_TYPE,
                       context=noti_params, dst_user_id=user_reg.userid)
            notifyAdmin(request=request, action=USER_RENEWED_TYPE, context=noti_params)

        except:
            LOG.error("Cannot renew user", exc_info=True)
            exceptions.handle(request)
            return False
        
        return True
    def handle(self, request, data):

        try:
        
            with transaction.atomic():

                curr_prjname = self.request.user.tenant_name

                q_args = {
                    'registration__regid' : int(data['regid']),
                    'project__projectname' : curr_prjname,
                    'flowstatus' : PSTATUS_RENEW_MEMB
                }                
                prj_reqs = PrjRequest.objects.filter(**q_args)
                if len(prj_reqs) == 0:
                    return True
                
                q_args = {
                    'registration__regid' : int(data['regid']),
                    'project__projectname' : curr_prjname
                }
                
                prj_exp = Expiration.objects.filter(**q_args)
                prj_exp.update(expdate=data['expiration'])
                
                #
                # Update the max expiration per user
                #
                user_reg = Registration.objects.get(regid=int(data['regid']))
                if data['expiration'] > user_reg.expdate:
                    user_reg.expdate = data['expiration']
                    user_reg.save()

                tmpres = EMail.objects.filter(registration=user_reg)
                user_mail = tmpres[0].email if len(tmpres) > 0 else None

                #
                # Clear requests
                #
                prj_reqs.delete()

            #
            # send notification to the user and cloud admin
            #
            noti_params = {
                'username' : user_reg.username,
                'project' : request.user.tenant_name,
                'expiration' : data['expiration'].strftime("%d %B %Y")
            }

            notifyUser(request=request, rcpt=user_mail, action=USER_RENEWED_TYPE,
                       context=noti_params, dst_user_id=user_reg.userid)
            notifyAdmin(request=request, action=USER_RENEWED_TYPE, context=noti_params)

        except:
            LOG.error("Cannot renew user", exc_info=True)
            exceptions.handle(request)
            return False
        
        return True
Пример #3
0
    def handle(self, request, data):
    
        try:
        
            role_names = [ role['name'] for role in self.request.user.roles ]
            if not TENANTADMIN_ROLE in role_names:
                raise Exception(_('Permissions denied: cannot approve subscriptions'))
        
            with transaction.atomic():
            
                curr_prjname = self.request.user.tenant_name
                q_args = {
                    'registration__regid' : int(data['regid']),
                    'project__projectname' : curr_prjname
                }                
                prj_req = PrjRequest.objects.filter(**q_args)[0]
                
                member_id = prj_req.registration.userid
                tmpres = EMail.objects.filter(registration__userid=member_id)
                member_email = tmpres[0].email if tmpres else None
                project_name = prj_req.project.projectname
                user_name = prj_req.registration.username
                
                #
                # clear request
                #
                prj_req.delete()

            #
            # send notification to the user
            #
            noti_params = {
                'username': user_name,
                'project' : project_name,
                'notes' : data['reason']
            }

            notifyUser(request=self.request, rcpt=member_email, action=SUBSCR_NO_TYPE, context=noti_params,
                       dst_user_id=member_id)
            notifyAdmin(request=self.request, action=SUBSCR_NO_TYPE, context=noti_params)

        except:
            exceptions.handle(request)
            return False
            
        return True
    def handle(self, request, data):
    
        try:
        
            role_names = [ role['name'] for role in self.request.user.roles ]
            if not TENANTADMIN_ROLE in role_names:
                raise Exception(_('Permissions denied: cannot approve subscriptions'))
        
            with transaction.atomic():
            
                curr_prjname = self.request.user.tenant_name
                q_args = {
                    'registration__regid' : int(data['regid']),
                    'project__projectname' : curr_prjname
                }                
                prj_req = PrjRequest.objects.filter(**q_args)[0]
                
                member_id = prj_req.registration.userid
                tmpres = EMail.objects.filter(registration__userid=member_id)
                member_email = tmpres[0].email if tmpres else None
                project_name = prj_req.project.projectname
                user_name = prj_req.registration.username
                
                #
                # clear request
                #
                prj_req.delete()

            #
            # send notification to the user
            #
            noti_params = {
                'username': user_name,
                'project' : project_name,
                'notes' : data['reason']
            }

            notifyUser(request=self.request, rcpt=member_email, action=SUBSCR_NO_TYPE, context=noti_params,
                       dst_user_id=member_id)
            notifyAdmin(request=self.request, action=SUBSCR_NO_TYPE, context=noti_params)

        except:
            exceptions.handle(request)
            return False
            
        return True
Пример #5
0
    def delete(self, request, obj_id):

        try:

            with transaction.atomic():

                q_args = {
                    'registration__userid': obj_id,
                    'project__projectname': request.user.tenant_name
                }
                Expiration.objects.filter(**q_args).delete()
                PrjRequest.objects.filter(**q_args).delete()
                PrjRole.objects.filter(**q_args).delete()

                roles_obj = client_factory(request).roles
                role_assign_obj = client_factory(request).role_assignments

                arg_dict = {'project': request.user.tenant_id, 'user': obj_id}
                for r_item in role_assign_obj.list(**arg_dict):
                    roles_obj.revoke(r_item.role['id'], **arg_dict)

            tmpres = EMail.objects.filter(registration__userid=obj_id)
            member_email = tmpres[0].email if tmpres else None
            member_name = tmpres[0].registration.username if tmpres else None

            tmpres = EMail.objects.filter(registration__userid=request.user.id)
            admin_email = tmpres[0].email if tmpres else None

            noti_params = {
                'username': member_name,
                'admin_address': admin_email,
                'project': request.user.tenant_name
            }
            notifyUser(request=request,
                       rcpt=member_email,
                       action=MEMBER_REMOVED,
                       context=noti_params,
                       dst_user_id=obj_id)
            notifyAdmin(request=request,
                        action=MEMBER_REMOVED_ADM,
                        context=noti_params)

        except:
            LOG.error("Grant revoke error", exc_info=True)
            messages.error(request, _('Unable to delete member from tenant.'))
    def delete(self, request, obj_id):
    
        try:
            
            with transaction.atomic():

                q_args = {
                    'registration__userid' : obj_id,
                    'project__projectname' : request.user.tenant_name
                }
                Expiration.objects.filter(**q_args).delete()
                PrjRequest.objects.filter(**q_args).delete()
                PrjRole.objects.filter(**q_args).delete()

                roles_obj = client_factory(request).roles
                role_assign_obj = client_factory(request).role_assignments
                
                arg_dict = {
                    'project' : request.user.tenant_id,
                    'user' : obj_id
                }
                for r_item in role_assign_obj.list(**arg_dict):
                    roles_obj.revoke(r_item.role['id'], **arg_dict)

            tmpres = EMail.objects.filter(registration__userid=obj_id)
            member_email = tmpres[0].email if tmpres else None
            member_name = tmpres[0].registration.username if tmpres else None
            
            tmpres = EMail.objects.filter(registration__userid=request.user.id)
            admin_email = tmpres[0].email if tmpres else None

            noti_params = {
                'username' : member_name,
                'admin_address' : admin_email,
                'project' : request.user.tenant_name
            }
            notifyUser(request=request, rcpt=member_email, action=MEMBER_REMOVED, context=noti_params,
                       dst_user_id=obj_id)
            notifyAdmin(request=request, action=MEMBER_REMOVED_ADM, context=noti_params)

            
        except:
            LOG.error("Grant revoke error", exc_info=True)
            messages.error(request, _('Unable to delete member from tenant.'))
    def handle(self, request, data):
        try:

            with transaction.atomic():

                q_args = {
                    'registration__userid' : data['userid'],
                    'project__projectid' : request.user.tenant_id
                }
                Expiration.objects.filter(**q_args).update(expdate=data['expiration'])

                all_exp = Expiration.objects.filter(registration__userid=data['userid'])
                if len(all_exp):
                    new_exp = max([ x.expdate for x in all_exp ])
                    all_exp[0].registration.expdate = new_exp
                    all_exp[0].registration.save()

                PrjRequest.objects.filter(**q_args).delete()

                tmpres = EMail.objects.filter(registration__userid=data['userid'])
                if len(tmpres) == 0:
                    return True

                user_name = tmpres[0].registration.username
                user_mail = tmpres[0].email
                noti_params = {
                    'username' : user_name,
                    'project' : request.user.tenant_name,
                    'expiration' : data['expiration'].strftime("%d %B %Y")
                }

                try:
                    notifyUser(request=request, rcpt=user_mail, action=USER_RENEWED_TYPE,
                               context=noti_params, dst_user_id=data['userid'])
                    notifyAdmin(request=request, action=USER_RENEWED_TYPE, context=noti_params)
                except:
                    LOG.error("Cannot notify %s" % user_name, exc_info=True)

        except:
            exceptions.handle(request)
            return False
        return True
    def _update_project_members(self, request, data, project_id):
        
        admin_role_id = None
        available_roles = baseWorkflows.api.keystone.role_list(request)
        member_ids = set()
        prjadm_ids = set()
        result = None
        
        with transaction.atomic():

            #
            # Create project in the database
            #
            newprj_id = self.object.id

            qargs = {
                'projectname' : data['name'],
                'projectid' : newprj_id,
                'description' : data['description'],
                'status' : PRJ_PUBLIC
            }
            newprj = Project(**qargs)
            newprj.save()
            self.this_project = newprj

            #
            # Setup members
            #
            for role in available_roles:
            
                tmp_step = self.get_step(baseWorkflows.PROJECT_USER_MEMBER_SLUG)
                field_name = tmp_step.get_member_field_name(role.id)

                if role.name == TENANTADMIN_ROLE:
                    admin_role_id = role.id
                    for tmpid in data[field_name]:
                        prjadm_ids.add(tmpid)

                for user_id in data[field_name]:
                    member_ids.add(user_id)


            #
            # Import expiration per tenant, use per-user expiration date as a fall back
            # Create the project admin cache
            #
            for u_item in Registration.objects.filter(userid__in=member_ids):

                new_p_exp = Expiration()
                new_p_exp.registration = u_item
                new_p_exp.project = self.this_project
                new_p_exp.expdate = u_item.expdate
                new_p_exp.save()

                if u_item.userid in prjadm_ids:
                    new_prjrole = PrjRole()
                    new_prjrole.registration = u_item
                    new_prjrole.project = self.this_project
                    new_prjrole.roleid = admin_role_id
                    new_prjrole.save()
                    LOG.debug("Created prj admin: %s" % u_item.username)

            #
            # Insert cloud admin as project_manager if missing
            #
            if len(prjadm_ids) == 0:
                baseWorkflows.api.keystone.add_tenant_user_role(request, project_id,
                                                    request.user.id, admin_role_id)

            result = super(ExtCreateProject, self)._update_project_members(request, data, project_id)

        #
        # Notify users
        #
        for e_item in EMail.objects.filter(registration__userid__in=member_ids):
            noti_params = {
                'username' : e_item.registration.username,
                'project' : self.this_project.projectname,
                'isadmin' : e_item.registration.userid in prjadm_ids
            }
            notifyUser(request=request, rcpt=e_item.email, action=MEMBER_FORCED_ADD, context=noti_params,
                       dst_project_id=self.this_project.projectid, dst_user_id=e_item.registration.userid)

        #
        # Notify all cloud admins
        #
        notifyAdmin(request=request, action=NEWPRJ_BY_ADM,
                    context={'project' : self.this_project.projectname})        

        return result
    def handle(self, *args, **options):

        super(Command, self).handle(options)

        LOG.info("Checking expired users")
        try:

            keystone_client = client.Client(
                username=self.config.cron_user,
                password=self.config.cron_pwd,
                project_name=self.config.cron_prj,
                user_domain_name=self.config.cron_domain,
                project_domain_name=self.config.cron_domain,
                cacert=self.config.cron_ca,
                auth_url=self.config.cron_kurl)

            prjman_roleid = get_prjman_roleid(keystone_client)
            cloud_adminid = keystone_client.auth_ref.user_id

        except:
            LOG.error("Check expiration failed", exc_info=True)
            raise CommandError("Check expiration failed")

        updated_prjs = set()

        exp_date = datetime.now() - timedelta(self.config.cron_defer)

        for mem_item in Expiration.objects.filter(expdate__lt=exp_date):

            username = mem_item.registration.username
            userid = mem_item.registration.userid
            prjname = mem_item.project.projectname
            prjid = mem_item.project.projectid

            updated_prjs.add(prjid)

            try:
                with transaction.atomic():

                    tmpres = EMail.objects.filter(
                        registration=mem_item.registration)
                    user_mail = tmpres[0].email if len(tmpres) else None

                    q_args = {
                        'registration': mem_item.registration,
                        'project': mem_item.project
                    }
                    Expiration.objects.filter(**q_args).delete()
                    PrjRequest.objects.filter(**q_args).delete()
                    PrjRole.objects.filter(**q_args).delete()

                    arg_dict = {'project': prjid, 'user': userid}
                    for r_item in keystone_client.role_assignments.list(
                            **arg_dict):
                        keystone_client.roles.revoke(r_item.role['id'],
                                                     **arg_dict)

                    LOG.info("Removed %s from %s" % (username, prjid))

                noti_params = {'username': username, 'project': prjname}
                notifyUser(user_mail,
                           USER_EXPIRED_TYPE,
                           noti_params,
                           project_id=prjid,
                           dst_user_id=userid)
                #
                # TODO notify project admins
                #

            except:
                LOG.error("Check expiration failed for %s" % username,
                          exc_info=True)

        #
        # Check for tenants without admin (use cloud admin if missing)
        #
        for prj_id in updated_prjs:
            if PrjRole.objects.filter(project__projectid=prj_id).count() == 0:
                try:
                    keystone_client.roles.grant(prjman_roleid,
                                                user=cloud_adminid,
                                                project=prj_id)
                    LOG.info("Cloud Administrator as admin for %s" % prj_id)
                    noti_params = {
                        'project': prj_id,
                        's_role': 'None',
                        'd_role': 'project_manager'
                    }
                    notifyAdmin(CHANGED_MEMBER_ROLE,
                                noti_params,
                                dst_user_id=prj_id)
                except:
                    LOG.error("Cannot set super admin for %s" % username,
                              exc_info=True)
    def handle(self, *args, **options):

        super(Command, self).handle(options)

        now = datetime.now()
        exp_date = now + timedelta(self.config.cron_renewd)

        LOG.info("Checking for renewal after %s" % str(exp_date))

        try:

            new_reqs = dict()
            mail_table = dict()

            with transaction.atomic():

                stored_reqs = set()
                renew_status_list = [ PSTATUS_RENEW_ADMIN, PSTATUS_RENEW_MEMB ]
                for prj_req in PrjRequest.objects.filter(flowstatus__in=renew_status_list):
                    stored_reqs.add((prj_req.registration.regid, prj_req.project.projectname))

                for e_item in Expiration.objects.filter(expdate__lte=exp_date, expdate__gt=now):

                    if not (e_item.registration.regid, e_item.project.projectname) in stored_reqs:
                        q_args = {
                            'registration' : e_item.registration,
                            'project' : e_item.project
                        }
                        is_admin = (PrjRole.objects.filter(**q_args).count() > 0)
                        f_exp = e_item.expdate.date().isoformat()
                        new_reqs[(e_item.registration, e_item.project)] = (is_admin, f_exp)

                for req_pair, req_data in new_reqs.items():
                    reqArgs = {
                        'registration' : req_pair[0],
                        'project' : req_pair[1],
                        'notes' : req_data[1],
                        'flowstatus' : PSTATUS_RENEW_ADMIN if req_data[0] else PSTATUS_RENEW_MEMB
                    }
                    PrjRequest(**reqArgs).save()

                    LOG.info("Issued renewal for %s" % req_pair[0].username)

                    if mail_table.has_key(req_pair[1].projectname):
                        continue

                    tmpl = list()
                    for prj_role in PrjRole.objects.filter(project=req_pair[1]):
                        tmpobj = EMail.objects.filter(registration=prj_role.registration)
                        if len(tmpobj):
                            tmpl.append(tmpobj[0].email)
                    mail_table[req_pair[1].projectname] = tmpl

            for req_pair, req_data in new_reqs.items():
                try:
                    noti_params = {
                        'username' : req_pair[0].username,
                        'project' : req_pair[1].projectname
                    }
                    if req_data[0]:
                        notifyAdmin(USER_NEED_RENEW, noti_params, user_id=req_pair[0].userid,
                                    project_id=req_pair[1].projectid,
                                    dst_project_id=req_pair[1].projectid)
                    else:
                        notifyProject(mail_table[req_pair[1].projectname], USER_NEED_RENEW,
                                      noti_params, user_id=req_pair[0].userid,
                                      project_id=req_pair[1].projectid,
                                      dst_project_id=req_pair[1].projectid)
                except:
                    LOG.error("Cannot notify %s" % req_pair[0].username, exc_info=True)
        except:
            LOG.error("Renewal request failed", exc_info=True)
            raise CommandError("Renewal request failed")
Пример #11
0
    def handle(self, request, data):
    
        try:
        
            role_names = [ role['name'] for role in self.request.user.roles ]
            if not TENANTADMIN_ROLE in role_names:
                raise Exception(_('Permissions denied: cannot approve subscriptions'))
        
            with transaction.atomic():
            
                curr_prjname = self.request.user.tenant_name
                q_args = {
                    'registration__regid' : int(data['regid']),
                    'project__projectname' : curr_prjname
                }                
                prj_req = PrjRequest.objects.filter(**q_args)[0]
                
                member_id = prj_req.registration.userid
                tmpres = EMail.objects.filter(registration__userid=member_id)
                member_email = tmpres[0].email if tmpres else None
                project_name = prj_req.project.projectname
                user_name = prj_req.registration.username
                
                LOG.debug("Approving subscription for %s" % prj_req.registration.username)
            
                default_role = getattr(settings, 'OPENSTACK_KEYSTONE_DEFAULT_ROLE', None)
                
                expiration = Expiration()
                expiration.registration = prj_req.registration
                expiration.project = prj_req.project
                expiration.expdate = data['expiration']
                expiration.save()
                
                #
                # Update the max expiration per user
                #
                user_reg = prj_req.registration
                if data['expiration'] > user_reg.expdate:
                    user_reg.expdate = data['expiration']
                    user_reg.save()

                roles_obj = client_factory(request).roles
                arg_dict = {
                    'project' : prj_req.project.projectid,
                    'user' : prj_req.registration.userid
                }
                
                missing_default = True
                for item in roles_obj.list():
                    if item.name == default_role:
                        roles_obj.grant(item.id, **arg_dict)
                        missing_default = False
                if missing_default:
                    raise Exception("Default role is undefined")
                #
                # Enable reminder for cloud admin
                #
                RegRequest.objects.filter(
                    registration = prj_req.registration,
                    flowstatus = RSTATUS_REMINDER
                ).update(flowstatus = RSTATUS_REMINDACK)
                #
                # clear request
                #
                prj_req.delete()

            #
            # send notification to the user
            #
            noti_params = {
                'username': user_name,
                'project' : project_name
            }

            notifyUser(request=self.request, rcpt=member_email, action=SUBSCR_OK_TYPE, context=noti_params,
                       dst_user_id=member_id)
            notifyAdmin(request=self.request, action=SUBSCR_OK_TYPE, context=noti_params)

        except:
            exceptions.handle(request)
            return False
            
        return True
Пример #12
0
    def handle(self, request, data):
    
        with transaction.atomic():
        
            registration = Registration.objects.filter(userid=request.user.id)[0]
        
            prj_action = data['prjaction']
            prjlist = list()
            if prj_action == 'selprj':
                for project in data['selprj']:
                    prjlist.append((project, "", PRJ_PUBLIC, False))
            
            elif prj_action == 'newprj':
                prjlist.append((
                    data['newprj'],
                    data['prjdescr'],
                    PRJ_PRIVATE if data['prjpriv'] else PRJ_PUBLIC,
                    True
                ))

        
            newprjlist = list()
            exstprjlist = list()
            for prjitem in prjlist:
        
                if prjitem[3]:
                    try:

                        prjArgs = {
                            'projectname' : prjitem[0],
                            'description' : prjitem[1],
                            'status' : prjitem[2]
                        }
                        project = Project.objects.create(**prjArgs)
                        newprjlist.append(project.projectname)

                    except IntegrityError:
                        messages.error(request, _("Project %s already exists") % prjitem[0])
                        LOG.error("Cannot create project %s" % prjitem[0])
                        return False
                
                elif prjitem[0] in self.pendingProjects:
                    continue
                else:
                    project = Project.objects.get(projectname=prjitem[0])
                    exstprjlist.append(project)
                        
                reqArgs = {
                    'registration' : registration,
                    'project' : project,
                    'flowstatus' : PSTATUS_PENDING,
                    'notes' : data['notes']
                }                
                reqPrj = PrjRequest(**reqArgs)
                reqPrj.save()

            #
            # Send notification to cloud admins for project creation
            #
            for prj_name in newprjlist:
                noti_params = {
                    'username' : request.user.username,
                    'project' : prj_name
                }
                notifyAdmin(request=self.request, action=NEWPRJ_REQ_TYPE, context=noti_params)

            #
            # Send notifications to project managers
            #
            for prj_item in exstprjlist:

                admin_emails = list()
                for prj_role in PrjRole.objects.filter(project=prj_item):
                    for email_obj in EMail.objects.filter(registration=prj_role.registration):
                        admin_emails.append(email_obj.email)

                noti_params = {
                    'username' : request.user.username,
                    'project' : prj_item.projectname
                }
                notifyProject(request=request, rcpt=admin_emails, action=MEMBER_REQUEST, 
                              context=noti_params)

        return True
    def handle(self, request, data):
    
        try:
        
            role_names = [ role['name'] for role in self.request.user.roles ]
            if not TENANTADMIN_ROLE in role_names:
                raise Exception(_('Permissions denied: cannot approve subscriptions'))
        
            with transaction.atomic():
            
                curr_prjname = self.request.user.tenant_name
                q_args = {
                    'registration__regid' : int(data['regid']),
                    'project__projectname' : curr_prjname
                }                
                prj_req = PrjRequest.objects.filter(**q_args)[0]
                
                member_id = prj_req.registration.userid
                tmpres = EMail.objects.filter(registration__userid=member_id)
                member_email = tmpres[0].email if tmpres else None
                project_name = prj_req.project.projectname
                user_name = prj_req.registration.username
                
                LOG.debug("Approving subscription for %s" % prj_req.registration.username)
            
                default_role = getattr(settings, 'OPENSTACK_KEYSTONE_DEFAULT_ROLE', None)
                
                expiration = Expiration()
                expiration.registration = prj_req.registration
                expiration.project = prj_req.project
                expiration.expdate = data['expiration']
                expiration.save()
                
                #
                # Update the max expiration per user
                #
                user_reg = prj_req.registration
                if data['expiration'] > user_reg.expdate:
                    user_reg.expdate = data['expiration']
                    user_reg.save()

                roles_obj = client_factory(request).roles
                arg_dict = {
                    'project' : prj_req.project.projectid,
                    'user' : prj_req.registration.userid
                }
                
                missing_default = True
                for item in roles_obj.list():
                    if item.name == default_role:
                        roles_obj.grant(item.id, **arg_dict)
                        missing_default = False
                if missing_default:
                    raise Exception("Default role is undefined")
                    
                #
                # clear request
                #
                prj_req.delete()

            #
            # send notification to the user
            #
            noti_params = {
                'username': user_name,
                'project' : project_name
            }

            notifyUser(request=self.request, rcpt=member_email, action=SUBSCR_OK_TYPE, context=noti_params,
                       dst_user_id=member_id)
            notifyAdmin(request=self.request, action=SUBSCR_OK_TYPE, context=noti_params)

        except:
            exceptions.handle(request)
            return False
            
        return True
    def handle(self, *args, **options):

        super(Command, self).handle(options)

        now = datetime.now()
        exp_date = now + timedelta(self.config.cron_renewd)

        LOG.info("Checking for renewal after %s" % str(exp_date))

        try:

            new_reqs = dict()
            mail_table = dict()

            with transaction.atomic():

                stored_reqs = set()
                renew_status_list = [PSTATUS_RENEW_ADMIN, PSTATUS_RENEW_MEMB]
                for prj_req in PrjRequest.objects.filter(
                        flowstatus__in=renew_status_list):
                    stored_reqs.add((prj_req.registration.regid,
                                     prj_req.project.projectname))

                for e_item in Expiration.objects.filter(expdate__lte=exp_date,
                                                        expdate__gt=now):

                    if not (e_item.registration.regid,
                            e_item.project.projectname) in stored_reqs:
                        q_args = {
                            'registration': e_item.registration,
                            'project': e_item.project
                        }
                        is_admin = (PrjRole.objects.filter(**q_args).count() >
                                    0)
                        f_exp = e_item.expdate.date().isoformat()
                        new_reqs[(e_item.registration,
                                  e_item.project)] = (is_admin, f_exp)

                for req_pair, req_data in new_reqs.items():
                    reqArgs = {
                        'registration':
                        req_pair[0],
                        'project':
                        req_pair[1],
                        'notes':
                        req_data[1],
                        'flowstatus':
                        PSTATUS_RENEW_ADMIN
                        if req_data[0] else PSTATUS_RENEW_MEMB
                    }
                    PrjRequest(**reqArgs).save()

                    LOG.info("Issued renewal for %s" % req_pair[0].username)

                    if mail_table.has_key(req_pair[1].projectname):
                        continue

                    tmpl = list()
                    for prj_role in PrjRole.objects.filter(
                            project=req_pair[1]):
                        tmpobj = EMail.objects.filter(
                            registration=prj_role.registration)
                        if len(tmpobj):
                            tmpl.append(tmpobj[0].email)
                    mail_table[req_pair[1].projectname] = tmpl

            for req_pair, req_data in new_reqs.items():
                try:
                    noti_params = {
                        'username': req_pair[0].username,
                        'project': req_pair[1].projectname
                    }
                    if req_data[0]:
                        notifyAdmin(USER_NEED_RENEW,
                                    noti_params,
                                    user_id=req_pair[0].userid,
                                    project_id=req_pair[1].projectid,
                                    dst_project_id=req_pair[1].projectid)
                    else:
                        notifyProject(mail_table[req_pair[1].projectname],
                                      USER_NEED_RENEW,
                                      noti_params,
                                      user_id=req_pair[0].userid,
                                      project_id=req_pair[1].projectid,
                                      dst_project_id=req_pair[1].projectid)
                except:
                    LOG.error("Cannot notify %s" % req_pair[0].username,
                              exc_info=True)
        except:
            LOG.error("Renewal request failed", exc_info=True)
            raise CommandError("Renewal request failed")
    def _update_project_members(self, request, data, project_id):

        admin_role_id = None
        available_roles = baseWorkflows.api.keystone.role_list(request)
        member_ids = set()
        prjadm_ids = set()
        result = None

        with transaction.atomic():

            #
            # Create project in the database
            #
            newprj_id = self.object.id

            qargs = {
                'projectname': data['name'],
                'projectid': newprj_id,
                'description': data['description'],
                'status': PRJ_PUBLIC
            }
            newprj = Project(**qargs)
            newprj.save()
            self.this_project = newprj

            #
            # Setup members
            #
            for role in available_roles:

                tmp_step = self.get_step(
                    baseWorkflows.PROJECT_USER_MEMBER_SLUG)
                field_name = tmp_step.get_member_field_name(role.id)

                if role.name == TENANTADMIN_ROLE:
                    admin_role_id = role.id
                    for tmpid in data[field_name]:
                        prjadm_ids.add(tmpid)

                for user_id in data[field_name]:
                    member_ids.add(user_id)

            #
            # Import expiration per tenant, use per-user expiration date as a fall back
            # Create the project admin cache
            #
            for u_item in Registration.objects.filter(userid__in=member_ids):

                new_p_exp = Expiration()
                new_p_exp.registration = u_item
                new_p_exp.project = self.this_project
                new_p_exp.expdate = u_item.expdate
                new_p_exp.save()

                if u_item.userid in prjadm_ids:
                    new_prjrole = PrjRole()
                    new_prjrole.registration = u_item
                    new_prjrole.project = self.this_project
                    new_prjrole.roleid = admin_role_id
                    new_prjrole.save()
                    LOG.debug("Created prj admin: %s" % u_item.username)

            #
            # Insert cloud admin as project_manager if missing
            #
            if len(prjadm_ids) == 0:
                baseWorkflows.api.keystone.add_tenant_user_role(
                    request, project_id, request.user.id, admin_role_id)

            result = super(ExtCreateProject, self)._update_project_members(
                request, data, project_id)

        #
        # Notify users
        #
        for e_item in EMail.objects.filter(
                registration__userid__in=member_ids):
            noti_params = {
                'username': e_item.registration.username,
                'project': self.this_project.projectname,
                'isadmin': e_item.registration.userid in prjadm_ids
            }
            notifyUser(request=request,
                       rcpt=e_item.email,
                       action=MEMBER_FORCED_ADD,
                       context=noti_params,
                       dst_project_id=self.this_project.projectid,
                       dst_user_id=e_item.registration.userid)

        #
        # Notify all cloud admins
        #
        notifyAdmin(request=request,
                    action=NEWPRJ_BY_ADM,
                    context={'project': self.this_project.projectname})

        return result