Beispiel #1
0
    def save(self, targetname, bugzilla_email):
        person = People.by_username(turbogears.identity.current.user_name)
        target = People.by_username(targetname)

        if not can_edit_user(person, target):
            turbogears.flash(_("You do not have permission to edit '%s'") % target.username)
            turbogears.redirect('/bugzilla')
            return dict()

        new_configs = {'bugzilla_email': bugzilla_email}
        cur_configs = Configs.query.filter_by(person_id=target.id, application='bugzilla').all()

        if bugzilla_email == None:
          session.delete(cur_configs[0])
          turbogears.flash(_("Bugzilla specific email removed!  This means your bugzilla email must be set to: %s" % target.email))
          turbogears.redirect('/bugzilla/')
        for config in cur_configs:
            for new_config in new_configs.keys():
                if config.attribute == new_config:
                    config.value = new_configs[new_config]
                    del(new_configs[new_config])
        for config in new_configs:
            c = Configs(application='bugzilla', attribute=config, value=new_configs[config])
            target.configs.append(c)

        turbogears.flash(_("Changes saved.  Please allow up to 1 hour for changes to be realized."))
        turbogears.redirect('/bugzilla/')
        return dict()
Beispiel #2
0
def delete_access_policy_rules(pool_name):
    """
    Deletes one or more matching rules from a system pool's access policy.

    See :ref:`system-access-policies-api` for description of the expected query parameters

    :param pool_name: System pool's name.

    """
    pool = _get_pool_by_name(pool_name)
    if not pool.can_edit_policy(identity.current.user):
        raise Forbidden403('Cannot edit system policy')

    policy = pool.access_policy
    query = SystemAccessPolicyRule.query.filter(SystemAccessPolicyRule.policy == policy)
    if 'permission' in request.args:
        query = query.filter(SystemAccessPolicyRule.permission.in_(
                request.args.getlist('permission', type=SystemPermission.from_string)))
    else:
        raise MethodNotAllowed405
    if 'user' in request.args:
        query = query.join(SystemAccessPolicyRule.user)\
                .filter(User.user_name.in_(request.args.getlist('user')))
    elif 'group' in request.args:
        query = query.join(SystemAccessPolicyRule.group)\
                .filter(Group.group_name.in_(request.args.getlist('group')))
    elif 'everybody' in request.args:
        query = query.filter(SystemAccessPolicyRule.everybody)
    else:
        raise MethodNotAllowed405
    for rule in query:
        rule.record_deletion(service=u'HTTP')
        session.delete(rule)
    return '', 204
Beispiel #3
0
def _remove(user, method, **kw):
    if user == identity.current.user:
        raise BX(_('You cannot remove yourself'))

    # cancel all running and queued jobs
    Job.cancel_jobs_by_user(user, 'User %s removed' % user.user_name)

    # Return all systems in use by this user
    for system in System.query.filter(System.user==user):
        reservation = system.open_reservation
        system.unreserve(reservation=reservation, service=method)
    # Return all loaned systems in use by this user
    for system in System.query.filter(System.loaned==user):
        system.record_activity(user=identity.current.user, service=method,
                action=u'Changed', field=u'Loaned To',
                old=u'%s' % system.loaned, new=None)
        system.loaned = None
    # Remove the user from all system access policies
    for rule in SystemAccessPolicyRule.query.filter_by(user=user):
        rule.record_deletion(service=method)
        session.delete(rule)
    # Change the owner to the caller
    newowner = kw.get('newowner', identity.current.user)
    for system in System.query.filter(System.owner==user):
        system.owner = newowner
        system.record_activity(user=identity.current.user, service=method,
                action=u'Changed', field=u'Owner',
                               old=u'%s' % user, new=u'%s' % newowner)
    # Remove the user from all groups
    for group in user.groups:
        if not group.membership_type == GroupMembershipType.inverted:
            group.remove_member(user=user,
                    agent=identity.current.user, service=method)
    # Finally remove the user
    user.removed=datetime.utcnow()
Beispiel #4
0
    def remove(self, **kw):
        u = identity.current.user
        try:
            group = Group.by_id(kw['group_id'])
        except DatabaseLookupError:
            flash(unicode('Invalid group or already removed'))
            redirect('../groups/mine')

        if not group.can_edit(u):
            flash(_(u'You are not an owner of group %s' % group))
            redirect('../groups/mine')

        if group.is_protected_group():
            flash(_(u'This group %s is predefined and cannot be deleted' % group))
            redirect('../groups/mine')

        if group.jobs:
            flash(_(u'Cannot delete a group which has associated jobs'))
            redirect('../groups/mine')

        # Record the access policy rules that will be removed
        # before deleting the group
        for rule in group.system_access_policy_rules:
            rule.record_deletion()

        # For any system pool owned by this group, unset owning_group
        # and set owning_user to the user deleting this group
        pools = SystemPool.query.filter_by(owning_group_id=group.group_id)
        for pool in pools:
            pool.change_owner(user=u, service='WEBUI')
        session.delete(group)
        activity = Activity(u, u'WEBUI', u'Removed', u'Group', group.display_name, u"")
        session.add(activity)
        flash( _(u"%s deleted") % group.display_name )
        raise redirect(".")
Beispiel #5
0
def delete_group(group_name):
    """
    Deletes a group.

    :status 204: Group was successfully deleted.
    :status 400: Group cannot be deleted because it is a predefined group, or
      because it has associated jobs.
    """
    group = _get_group_by_name(group_name)
    if not group.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit group')
    if group.is_protected_group():
        raise BadRequest400("Group '%s' is predefined and cannot be deleted"
                % group.group_name)
    if group.jobs:
        raise BadRequest400('Cannot delete a group which has associated jobs')
    # Record the access policy rules that will be removed
    for rule in group.system_access_policy_rules:
        rule.record_deletion()
    # For any system pool owned by this group, unset owning_group
    # and set owning_user to the user deleting this group
    pools = SystemPool.query.filter_by(owning_group=group)
    for pool in pools:
        pool.change_owner(user=identity.current.user, service=u'HTTP')
    session.delete(group)
    activity = Activity(identity.current.user, u'HTTP', u'Removed', u'Group', group.display_name)
    session.add(activity)
    return '', 204
Beispiel #6
0
    def _from_csv(cls,system,data,csv_type,log):
        """
        Import data from CSV file into System Objects
        """
        try:
            arch = Arch.by_name(data['arch'])
        except ValueError:
            log.append("%s: Invalid Arch %s" % (system.fqdn, data['arch']))
            return False

        if data['update'] and data['family']:
            try:
                osversion = OSVersion.by_name(OSMajor.by_name(unicode(data['family'])),
                                                            unicode(data['update']))
            except InvalidRequestError:
                log.append("%s: Invalid Family %s Update %s" % (system.fqdn,
                                                        data['family'],
                                                        data['update']))
                return False
            if osversion not in [oldosversion.osversion for oldosversion in system.excluded_osversion_byarch(arch)]:
                if data['excluded'] == 'True':
                    exclude_osversion = ExcludeOSVersion(osversion=osversion,
                                                         arch=arch)
                    system.excluded_osversion.append(exclude_osversion)
                    system.record_activity(user=identity.current.user, service=u'CSV',
                            action=u'Added', field=u'Excluded_families',
                            old=u'', new=u'%s/%s' % (osversion, arch))
            else:
                if data['excluded'] == 'False':
                    for old_osversion in system.excluded_osversion_byarch(arch):
                        if old_osversion.osversion == osversion:
                            system.record_activity(user=identity.current.user,
                                    service=u'CSV', action=u'Removed',
                                    field=u'Excluded_families',
                                    old=u'%s/%s' % (old_osversion.osversion, arch),
                                    new=u'')
                            session.delete(old_osversion)
        if not data['update'] and data['family']:
            try:
                osmajor = OSMajor.by_name(data['family'])
            except InvalidRequestError:
                log.append("%s: Invalid family %s " % (system.fqdn,
                                                       data['family']))
                return False
            if osmajor not in [oldosmajor.osmajor for oldosmajor in system.excluded_osmajor_byarch(arch)]:
                if data['excluded'].lower() == 'true':
                    exclude_osmajor = ExcludeOSMajor(osmajor=osmajor, arch=arch)
                    system.excluded_osmajor.append(exclude_osmajor)
                    system.record_activity(user=identity.current.user, service=u'CSV',
                            action=u'Added', field=u'Excluded_families',
                            old=u'', new=u'%s/%s' % (osmajor, arch))
            else:
                if data['excluded'].lower() == 'false':
                    for old_osmajor in system.excluded_osmajor_byarch(arch):
                        if old_osmajor.osmajor == osmajor:
                            system.record_activity(user=identity.current.user, service=u'CSV',
                                    action=u'Removed', field=u'Excluded_families',
                                    old=u'%s/%s' % (old_osmajor.osmajor, arch), new=u'')
                            session.delete(old_osmajor)
        return True
Beispiel #7
0
    def genkey(self):
        
        username = turbogears.identity.current.user_name
        person = People.by_username(username)

        created = time.strftime("%Y-%m-%dT%H:%M:%S")
        hexctr = "%012x" % person.id
        publicname = hex2modhex(hexctr)
        internalname = gethexrand(12)
        aeskey = gethexrand(32)
        lockcode = gethexrand(12)

        try:
            new_ykksm = Ykksm(serialnr=person.id, publicname=publicname, created=created, internalname=internalname, aeskey=aeskey, lockcode=lockcode, creator=username)
            session.add(new_ykksm)
            session.flush() 
        except IntegrityError:
            session.rollback()
            old_ykksm = session.query(Ykksm).filter_by(serialnr=person.id).all()[0]
            session.delete(old_ykksm)
            new_ykksm = Ykksm(serialnr=person.id, publicname=publicname, created=created, internalname=internalname, aeskey=aeskey, lockcode=lockcode, creator=username)
            old_ykksm = new_ykksm
            session.flush()
        try:
            old_ykval = session.query(Ykval).filter_by(yk_publicname=publicname).all()[0]
            session.delete(old_ykval)
            session.flush()
        except IndexError:
            # No old record?  Maybe they never used their key
            pass
            
        string = "%s %s %s" % (publicname, internalname, aeskey)
        return dict(key=string)
Beispiel #8
0
    def genkey(self):
        
        username = turbogears.identity.current.user_name
        person = People.by_username(username)

        created = time.strftime("%Y-%m-%dT%H:%M:%S")
        hexctr = "%012x" % person.id
        publicname = hex2modhex(hexctr)
        internalname = gethexrand(12)
        aeskey = gethexrand(32)
        lockcode = gethexrand(12)

        try:
            new_ykksm = Ykksm(serialnr=person.id, publicname=publicname, created=created, internalname=internalname, aeskey=aeskey, lockcode=lockcode, creator=username)
            session.add(new_ykksm)
            session.flush() 
        except IntegrityError:
            session.rollback()
            old_ykksm = session.query(Ykksm).filter_by(serialnr=person.id).all()[0]
            session.delete(old_ykksm)
            new_ykksm = Ykksm(serialnr=person.id, publicname=publicname, created=created, internalname=internalname, aeskey=aeskey, lockcode=lockcode, creator=username)
            old_ykksm = new_ykksm
            session.flush()
        try:
            old_ykval = session.query(Ykval).filter_by(yk_publicname=publicname).all()[0]
            session.delete(old_ykval)
            session.flush()
        except IndexError:
            # No old record?  Maybe they never used their key
            pass
            
        string = "%s %s %s" % (publicname, internalname, aeskey)
        return dict(key=string)
Beispiel #9
0
def delete_group(group_name):
    """
    Deletes a group.

    :status 204: Group was successfully deleted.
    :status 400: Group cannot be deleted because it is a predefined group, or
      because it has associated jobs.
    """
    group = _get_group_by_name(group_name)
    if not group.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit group')
    if group.is_protected_group():
        raise BadRequest400("Group '%s' is predefined and cannot be deleted" %
                            group.group_name)
    if group.jobs:
        raise BadRequest400('Cannot delete a group which has associated jobs')
    # Record the access policy rules that will be removed
    for rule in group.system_access_policy_rules:
        rule.record_deletion()
    # For any system pool owned by this group, unset owning_group
    # and set owning_user to the user deleting this group
    pools = SystemPool.query.filter_by(owning_group=group)
    for pool in pools:
        pool.change_owner(user=identity.current.user, service=u'HTTP')
    session.delete(group)
    activity = Activity(identity.current.user, u'HTTP', u'Removed', u'Group',
                        group.display_name)
    session.add(activity)
    return '', 204
Beispiel #10
0
    def deleteQuery(self, query_id, *args, **kwargs):
        '''
            Allows user to delete a query. Updates query logging.
            
            @param query_id: identifies the query
            @return: status of attempted  delete operation of the query
        '''
        
        query = session.query(Query).get_by(query_id=int(query_id))
        
        status = ""
        
        if not query:
            status = "Query not found"
        elif session.query(ChatSession).get_by(query_id=int(query_id)):
            status = "Chat already started"
        elif query.user_id != identity.current.user.user_id:
            status = "Permission denied"
        else:
            query.experts[:] = []
            query_log=QueryLog(
                query_id = int(query_id),
                user_id = query.user_id,
                user_name = session.query(User).get_by(user_id=query.user_id).user_name,
                created = datetime.now(),
                status = 'Deleted')

            session.save(query_log)
            session.flush()
            session.delete(query);
            session.flush();
            
        return dict(status=status)    
Beispiel #11
0
 def setUpClass(cls):
     # Clear out any LDAP groups left behind by previous tests,
     # to avoid warning spew from beaker-refresh-ldap
     # when it fails to look up the rubbish group names.
     for group in Group.query.filter(
             Group.membership_type == GroupMembershipType.ldap):
         session.delete(group)
Beispiel #12
0
    def remove(self, id, *args, **kw):
        try:
            labcontroller = LabController.by_id(id)
            labcontroller.removed = datetime.utcnow()
            systems = System.query.filter_by(lab_controller_id=id).values(System.id)
            for system_id in systems:
                sys_activity = SystemActivity(identity.current.user, 'WEBUI', \
                    'Changed', 'lab_controller', labcontroller.fqdn,
                    None, system_id=system_id[0])
            system_table.update().where(system_table.c.lab_controller_id == id).\
                values(lab_controller_id=None).execute()
            watchdogs = Watchdog.by_status(labcontroller=labcontroller, 
                status='active')
            for w in watchdogs:
                w.recipe.recipeset.job.cancel(msg='LabController %s has been deleted' % labcontroller.fqdn)
            for lca in labcontroller._distro_trees:
                lca.distro_tree.activity.append(DistroTreeActivity(
                        user=identity.current.user, service=u'WEBUI',
                        action=u'Removed', field_name=u'lab_controller_assocs',
                        old_value=u'%s %s' % (lca.lab_controller, lca.url),
                        new_value=None))
                session.delete(lca)
            labcontroller.disabled = True
            LabControllerActivity(identity.current.user, 'WEBUI', 
                'Changed', 'Disabled', unicode(False), unicode(True), 
                lab_controller_id=id)
            LabControllerActivity(identity.current.user, 'WEBUI', 
                'Changed', 'Removed', unicode(False), unicode(True), 
                lab_controller_id=id)
            session.commit()
        finally:
            session.close()

        flash( _(u"%s removed") % labcontroller.fqdn )
        raise redirect(".")
Beispiel #13
0
def delete_access_policy_rules(pool_name):
    """
    Deletes one or more matching rules from a system pool's access policy.

    See :ref:`system-access-policies-api` for description of the expected query parameters

    :param pool_name: System pool's name.

    """
    pool = _get_pool_by_name(pool_name)
    if not pool.can_edit_policy(identity.current.user):
        raise Forbidden403('Cannot edit system policy')

    policy = pool.access_policy
    query = SystemAccessPolicyRule.query.filter(SystemAccessPolicyRule.policy == policy)
    if 'permission' in request.args:
        query = query.filter(SystemAccessPolicyRule.permission.in_(
                request.args.getlist('permission', type=SystemPermission.from_string)))
    else:
        raise MethodNotAllowed405
    if 'user' in request.args:
        query = query.join(SystemAccessPolicyRule.user)\
                .filter(User.user_name.in_(request.args.getlist('user')))
    elif 'group' in request.args:
        query = query.join(SystemAccessPolicyRule.group)\
                .filter(Group.group_name.in_(request.args.getlist('group')))
    elif 'everybody' in request.args:
        query = query.filter(SystemAccessPolicyRule.everybody)
    else:
        raise MethodNotAllowed405
    for rule in query:
        rule.record_deletion(service=u'HTTP')
        session.delete(rule)
    return '', 204
Beispiel #14
0
def delete_pool(pool_name):
    """
    Deletes a system pool

    :param pool_name: System pool's name

    """
    pool = _get_pool_by_name(pool_name, lockmode='update')
    u = identity.current.user
    if not pool.can_edit(u):
        raise Forbidden403('Cannot delete pool %s' % pool_name)

    systems = System.query.filter(System.pools.contains(pool))
    System.record_bulk_activity(systems, user=identity.current.user,
                                service=u'HTTP', action=u'Removed',
                                field=u'Pool',
                                old=unicode(pool),
                                new=None)
    # Since we are deleting the pool, we will have to change the active
    # access policy for all systems using the pool's policy to their
    # custom policy
    systems = System.query.filter(System.active_access_policy == pool.access_policy)
    for system in systems:
        system.active_access_policy = system.custom_access_policy
    System.record_bulk_activity(systems, user=identity.current.user,
                                service=u'HTTP',
                                field=u'Active Access Policy', action=u'Changed',
                                old = 'Pool policy: %s' % pool_name,
                                new = 'Custom access policy')
    session.delete(pool)
    activity = Activity(u, u'HTTP', u'Deleted', u'Pool', pool_name)
    session.add(activity)
    return '', 204
Beispiel #15
0
def delete_system_access_policy_rules(fqdn):
    system = _get_system_by_FQDN(fqdn)
    if not system.can_edit_policy(identity.current.user):
        raise Forbidden403('Cannot edit system policy')
    if system.custom_access_policy:
        policy = system.custom_access_policy
    else:
        policy = system.custom_access_policy = SystemAccessPolicy()
    # We expect some query string args specifying which rules should be 
    # deleted. If those are not present, it's "Method Not Allowed".
    query = SystemAccessPolicyRule.query.filter(SystemAccessPolicyRule.policy == policy)
    if 'permission' in request.args:
        query = query.filter(SystemAccessPolicyRule.permission.in_(
                request.args.getlist('permission', type=SystemPermission.from_string)))
    else:
        raise MethodNotAllowed405
    if 'user' in request.args:
        query = query.join(SystemAccessPolicyRule.user)\
                .filter(User.user_name.in_(request.args.getlist('user')))
    elif 'group' in request.args:
        query = query.join(SystemAccessPolicyRule.group)\
                .filter(Group.group_name.in_(request.args.getlist('group')))
    elif 'everybody' in request.args:
        query = query.filter(SystemAccessPolicyRule.everybody)
    else:
        raise MethodNotAllowed405
    for rule in query:
        rule.record_deletion(service=u'HTTP')
        session.delete(rule)
    return '', 204
Beispiel #16
0
def delete_system_access_policy_rules(fqdn):
    system = _get_system_by_FQDN(fqdn)
    if not system.can_edit_policy(identity.current.user):
        raise Forbidden403('Cannot edit system policy')
    if system.custom_access_policy:
        policy = system.custom_access_policy
    else:
        policy = system.custom_access_policy = SystemAccessPolicy()
    # We expect some query string args specifying which rules should be
    # deleted. If those are not present, it's "Method Not Allowed".
    query = SystemAccessPolicyRule.query.filter(
        SystemAccessPolicyRule.policy == policy)
    if 'permission' in request.args:
        query = query.filter(
            SystemAccessPolicyRule.permission.in_(
                request.args.getlist('permission',
                                     type=SystemPermission.from_string)))
    else:
        raise MethodNotAllowed405
    if 'user' in request.args:
        query = query.join(SystemAccessPolicyRule.user)\
                .filter(User.user_name.in_(request.args.getlist('user')))
    elif 'group' in request.args:
        query = query.join(SystemAccessPolicyRule.group)\
                .filter(Group.group_name.in_(request.args.getlist('group')))
    elif 'everybody' in request.args:
        query = query.filter(SystemAccessPolicyRule.everybody)
    else:
        raise MethodNotAllowed405
    for rule in query:
        rule.record_deletion(service=u'HTTP')
        session.delete(rule)
    return '', 204
Beispiel #17
0
def delete_pool(pool_name):
    """
    Deletes a system pool

    :param pool_name: System pool's name

    """
    pool = _get_pool_by_name(pool_name, lockmode='update')
    u = identity.current.user
    if not pool.can_edit(u):
        raise Forbidden403('Cannot delete pool %s' % pool_name)

    systems = System.query.filter(System.pools.contains(pool))
    System.record_bulk_activity(systems, user=identity.current.user,
                                service=u'HTTP', action=u'Removed',
                                field=u'Pool',
                                old=unicode(pool),
                                new=None)
    # Since we are deleting the pool, we will have to change the active
    # access policy for all systems using the pool's policy to their
    # custom policy
    systems = System.query.filter(System.active_access_policy == pool.access_policy)
    for system in systems:
        system.active_access_policy = system.custom_access_policy
    System.record_bulk_activity(systems, user=identity.current.user,
                                service=u'HTTP',
                                field=u'Active Access Policy', action=u'Changed',
                                old = 'Pool policy: %s' % pool_name,
                                new = 'Custom access policy')
    session.delete(pool)
    activity = Activity(u, u'HTTP', u'Deleted', u'Pool', pool_name)
    session.add(activity)
    return '', 204
Beispiel #18
0
def update_reservation_request(id):
    """
    Updates the reservation request of a recipe. The request must be 
    :mimetype:`application/json`.

    :param id: Recipe's id.
    :jsonparam boolean reserve: Whether the system will be reserved at the end
      of the recipe. If true, the system will be reserved. If false, the system
      will not be reserved.
    :jsonparam int duration: Number of seconds to reserve the system.
    :jsonparam string when: Circumstances under which the system will be 
      reserved. Valid values are:

      onabort
        If the recipe status is Aborted.
      onfail
        If the recipe status is Aborted, or the result is Fail.
      onwarn
        If the recipe status is Aborted, or the result is Fail or Warn.
      always
        Unconditionally.
    """

    recipe = _get_recipe_by_id(id)
    if not recipe.can_update_reservation_request(identity.current.user):
        raise Forbidden403(
            'Cannot update the reservation request of recipe %s' % recipe.id)
    data = read_json_request(request)
    if 'reserve' not in data:
        raise BadRequest400('No reserve specified')
    with convert_internal_errors():
        if data['reserve']:
            if not recipe.reservation_request:
                recipe.reservation_request = RecipeReservationRequest()
            if 'duration' in data:
                duration = int(data['duration'])
                if duration > MAX_SECONDS_PROVISION:
                    raise BadRequest400(
                        'Reservation time exceeds maximum time of %s hours' %
                        MAX_HOURS_PROVISION)
                old_duration = recipe.reservation_request.duration
                recipe.reservation_request.duration = duration
                _record_activity(recipe, u'Reservation Request', old_duration,
                                 duration)
            if 'when' in data:
                old_condition = recipe.reservation_request.when
                new_condition = RecipeReservationCondition.from_string(
                    data['when'])
                recipe.reservation_request.when = new_condition
                _record_activity(recipe, u'Reservation Condition',
                                 old_condition, new_condition)
            session.flush()  # to ensure the id is populated
            return jsonify(recipe.reservation_request.__json__())
        else:
            if recipe.reservation_request:
                session.delete(recipe.reservation_request)
                _record_activity(recipe, u'Reservation Request',
                                 recipe.reservation_request.duration, None)
            return jsonify(RecipeReservationRequest.empty_json())
Beispiel #19
0
 def destroy_self(self):
     '''
         Destroys self
     '''
     
     session.delete(self)
     session.flush()
     del(self)
Beispiel #20
0
 def delete(self, id):
     tag = Tag.by_id(id)
     if not tag.can_delete(): # Trying to be funny...
         flash(u'%s is not applicable for deletion' % tag.tag)
         redirect('/retentiontag/admin')
     session.delete(tag)
     flash(u'Successfully deleted %s' % tag.tag)
     redirect('/retentiontag/admin')
 def logout(self):
     """Remove the link between this identity and the visit."""
     visit = self.visit_link
     if visit:
         session.delete(visit)
         session.flush()
     # Clear the current identity
     identity.set_current_identity(SqlAlchemyIdentity())
Beispiel #22
0
 def logout(self):
     """Remove the link between this identity and the visit."""
     visit = self.visit_link
     if visit:
         session.delete(visit)
         session.flush()
     # Clear the current identity
     identity.set_current_identity(SqlAlchemyIdentity())
Beispiel #23
0
 def logout(self):
     '''Remove the link between this identity and the visit.'''
     visit = self.visit_link
     if visit:
         session.delete(visit)
         session.flush()
     # Clear the current identity
     identity.set_current_identity(SaFasIdentity())
Beispiel #24
0
 def logout(self):
     '''Remove the link between this identity and the visit.'''
     visit = self.visit_link
     if visit:
         session.delete(visit)
         session.flush()
     # Clear the current identity
     identity.set_current_identity(SaFasIdentity())
Beispiel #25
0
def _handle_package_mask(session, data, machine_id):
    # Find current entries
    try:
        package_mask = data['user_package_mask']
    except KeyError:
        package_mask = {}
    current_package_mask_set = set()
    for package, atoms in package_mask.items():
        for i in atoms:
            key = (package, i)
            current_package_mask_set.add(key)

    # Find old entries
    old_package_mask_rel_objects = session.query(\
            GentooPackageMaskRel).options(\
                eagerload('package'), \
                eagerload('atom')).\
            filter_by(machine_id=machine_id).all()
    old_package_mask_dict = {}
    for e in old_package_mask_rel_objects:
        key = (e.package.name, e.atom.name)
        old_package_mask_dict[key] = e
    old_package_mask_set = set(old_package_mask_dict.keys())

    # Calculate diff
    mask_entries_to_add = current_package_mask_set - old_package_mask_set
    mask_entries_to_remove = old_package_mask_set - current_package_mask_set

    # Resolve diff
    for i in mask_entries_to_remove:
        session.delete(old_package_mask_dict[i])
    if mask_entries_to_remove:
        session.flush()
    for i in mask_entries_to_add:
        package, atom = i
        lookup_or_add_jobs = (
            {'thing':'atom', },
            {'thing':'package', },
        )

        for job in lookup_or_add_jobs:
            thing = job['thing']
            details = {
                'class_name':pool_class_name(thing, vector_flag=False),
                'source_var_name':thing,
                'new_object_name':'%s_pool_object' % thing
            }

            program = _LOOKUP_OR_ADD_TEMPLATE % details
            dump_gentoo_python_code(program)
            exec(program)

        session.flush()
        package_id = package_pool_object.id
        atom_id = atom_pool_object.id

        mask_rel_object = GentooPackageMaskRel(machine_id, package_id, atom_id)
        session.add(mask_rel_object)
Beispiel #26
0
def update_reservation_request(id):
    """
    Updates the reservation request of a recipe. The request must be 
    :mimetype:`application/json`.

    :param id: Recipe's id.
    :jsonparam boolean reserve: Whether the system will be reserved at the end
      of the recipe. If true, the system will be reserved. If false, the system
      will not be reserved.
    :jsonparam int duration: Number of seconds to reserve the system.
    :jsonparam string when: Circumstances under which the system will be 
      reserved. Valid values are:

      onabort
        If the recipe status is Aborted.
      onfail
        If the recipe status is Aborted, or the result is Fail.
      onwarn
        If the recipe status is Aborted, or the result is Fail or Warn.
      always
        Unconditionally.
    """

    recipe = _get_recipe_by_id(id)
    if not recipe.can_update_reservation_request(identity.current.user):
        raise Forbidden403('Cannot update the reservation request of recipe %s'
                % recipe.id)
    data = read_json_request(request)
    if 'reserve' not in data:
        raise BadRequest400('No reserve specified')
    with convert_internal_errors():
        if data['reserve']:
            if not recipe.reservation_request:
                recipe.reservation_request = RecipeReservationRequest()
            if 'duration' in data:
                duration = int(data['duration'])
                if duration > MAX_SECONDS_PROVISION:
                    raise BadRequest400('Reservation time exceeds maximum time of %s hours'
                            % MAX_HOURS_PROVISION)
                old_duration = recipe.reservation_request.duration
                recipe.reservation_request.duration = duration
                _record_activity(recipe, u'Reservation Request', old_duration,
                        duration)
            if 'when' in data:
                old_condition = recipe.reservation_request.when
                new_condition = RecipeReservationCondition.from_string(data['when'])
                recipe.reservation_request.when = new_condition
                _record_activity(recipe, u'Reservation Condition',
                        old_condition, new_condition)
            session.flush() # to ensure the id is populated
            return jsonify(recipe.reservation_request.__json__())
        else:
            if recipe.reservation_request:
                session.delete(recipe.reservation_request)
                _record_activity(recipe, u'Reservation Request',
                        recipe.reservation_request.duration, None)
            return jsonify(RecipeReservationRequest.empty_json())
Beispiel #27
0
 def delete(self, **kw):
     item = ConfigItem.by_id(kw['item'])
     val = item.value_class.by_id(kw['id'])
     if val.valid_from <= datetime.utcnow():
         flash(_(u"Cannot remove past value of %s") % item.name)
         raise redirect("/configuration/edit?id=%d" % item.id)
     session.delete(val)
     session.flush()
     flash(_(u"Future value of %s cleared") % item.name)
     raise redirect(".")
Beispiel #28
0
 def delete(self, **kw):
     item = ConfigItem.by_id(kw['item'])
     val = item.value_class.by_id(kw['id'])
     if val.valid_from <= datetime.utcnow():
         flash(_(u"Cannot remove past value of %s") % item.name)
         raise redirect("/configuration/edit?id=%d" % item.id)
     session.delete(val)
     session.flush()
     flash(_(u"Future value of %s cleared") % item.name)
     raise redirect(".")
Beispiel #29
0
    def destroy(self):

        for city in self.cities:
            city.destroy()

        groups = self.groups
        for group in list(groups):
            groups.remove(group)

        session.delete(self)
Beispiel #30
0
 def delete(self, uuid):
     # TODO also search and clean batch queue?
     try:
         host = session.query(Host).filter_by(uuid=uuid).one()
     except:
         raise ValueError("Critical: UUID does not exist %s " % uuid)
     try:
         session.delete(host)
         session.flush()
     except:
         raise ValueError("Critical: Could not delete UUID - Please contact the smolt development team")
     raise ValueError('Success: UUID Removed')
Beispiel #31
0
 def tearDown(self):
     with session.begin():
         for t in self.recipe_tasks:
             session.delete(t)
         session.delete(self.task_one)
         session.delete(self.task_two)
         session.delete(self.task_three)
Beispiel #32
0
 def test_02_abort_dead_recipes(self):
     beakerd.process_new_recipes()
     beakerd.update_dirty_jobs()
     beakerd.queue_processed_recipesets()
     beakerd.update_dirty_jobs()
     with session.begin():
         self.assertEqual(Job.by_id(self.job2.id).status, TaskStatus.queued)
         # Remove distro_tree2 from lab1, should cause remaining recipe to abort.
         for lca in self.distro_tree2.lab_controller_assocs[:]:
             session.delete(lca)
     beakerd.abort_dead_recipes()
     beakerd.update_dirty_jobs()
     with session.begin():
         self.assertEqual(Job.by_id(self.job2.id).status, TaskStatus.aborted)
Beispiel #33
0
 def delete(self, uuid):
     # TODO also search and clean batch queue?
     try:
         host = session.query(Host).filter_by(uuid=uuid).one()
     except:
         raise ValueError("Critical: UUID does not exist %s " % uuid)
     try:
         session.delete(host)
         session.flush()
     except:
         raise ValueError(
             "Critical: Could not delete UUID - Please contact the smolt development team"
         )
     raise ValueError('Success: UUID Removed')
Beispiel #34
0
def delete_ssh_public_key(username, id):
    """
    Deletes a public SSH public key belonging to the given user account.

    :param username: The user's username.
    :param id: Database id of the SSH public key to be deleted.
    """
    user = _get_user(username)
    if not user.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit user %s' % user)
    matching_keys = [k for k in user.sshpubkeys if k.id == id]
    if not matching_keys:
        raise NotFound404('SSH public key id %s does not belong to user %s' % (id, user))
    key = matching_keys[0]
    session.delete(key)
    return '', 204
Beispiel #35
0
def delete_ssh_public_key(username, id):
    """
    Deletes a public SSH public key belonging to the given user account.

    :param username: The user's username.
    :param id: Database id of the SSH public key to be deleted.
    """
    user = _get_user(username)
    if not user.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit user %s' % user)
    matching_keys = [k for k in user.sshpubkeys if k.id == id]
    if not matching_keys:
        raise NotFound404('SSH public key id %s does not belong to user %s' % (id, user))
    key = matching_keys[0]
    session.delete(key)
    return '', 204
Beispiel #36
0
    def deleteBlogEntry(self, blogentry_id, **kwargs): 
        '''
            Deletes note and it's count.
            
            @param blogentry_id: needed to identify note
        '''
        
        entry = session.query(BlogEntry).get_by(blogentry_id=int(blogentry_id))
        entry.relatedQueries = []
        user=session.query(User).get_by(user_id = entry.user_id)

        if user.user_stats.no_of_blogs>1:
            user.user_stats.no_of_blogs-=1

        session.delete(entry);
        session.flush()
        return dict()
Beispiel #37
0
    def ssh_key_remove(self, *args, **kw):
        user = identity.current.user
        keyid = kw.get('id', None)

        try:
            key = SSHPubKey.by_id(keyid)
        except InvalidRequestError:
            flash(_(u"SSH key not found"))
            redirect('.')

        if user != key.user:
            flash(_(u"May not remove another user's keys"))
            redirect('.')

        session.delete(key)
        flash(_(u"SSH public key removed"))
        redirect('.')
Beispiel #38
0
    def ssh_key_remove(self, *args, **kw):
        user = identity.current.user
        keyid = kw.get('id', None)

        try:
            key = SSHPubKey.by_id(keyid)
        except InvalidRequestError:
            flash(_(u"SSH key not found"))
            redirect('.')

        if user != key.user:
            flash(_(u"May not remove another user's keys"))
            redirect('.')

        session.delete(key)
        flash(_(u"SSH public key removed"))
        redirect('.')
Beispiel #39
0
def _handle_call_flags(session, data, machine_id):
    for call_flag_class_upper in ('CFLAGS', 'CXXFLAGS', 'LDFLAGS', 'MAKEOPTS'):
        try:
            call_flag_class_object = session.query(GentooCallFlagClassString).filter_by(name=call_flag_class_upper).one()
        except sqlalchemy.orm.exc.NoResultFound:
            call_flag_class_object = GentooCallFlagClassString(call_flag_class_upper)
            session.add(call_flag_class_object)
            session.flush()
        call_flag_class_id = call_flag_class_object.id

        # Find current entries
        try:
            current_call_flag_list = data['call_flags'][call_flag_class_upper.lower()]
        except KeyError:
            current_call_flag_list = []

        # Find old entries
        old_call_flag_objects = session.query(GentooCallFlagRel).options(\
                eagerload('call_flag')).\
            filter_by(machine_id=machine_id, call_flag_class_id=call_flag_class_id).all()

        # Re-construct call flag list
        old_call_flag_list = [a.call_flag.name for a in sorted(\
                [e for e in old_call_flag_objects], key=lambda x: x.position)]

        # Consistent data?
        if len(old_call_flag_list) != len(old_call_flag_objects):
            old_call_flag_list = None

        # Calculate diff
        if cmp(current_call_flag_list, old_call_flag_list) != 0:
            # Resolve diff
            for e in old_call_flag_objects:
                session.delete(e)
            if old_call_flag_objects:
                session.flush()
            for position, call_flag in enumerate(current_call_flag_list):
                try:
                    call_flag_object = session.query(GentooCallFlagString).filter_by(name=call_flag).one()
                except sqlalchemy.orm.exc.NoResultFound:
                    call_flag_object = GentooCallFlagString(call_flag)
                    session.add(call_flag_object)
                    session.flush()
                call_flag_id = call_flag_object.id
                session.add(GentooCallFlagRel(machine_id, call_flag_class_id, call_flag_id, position))
            session.flush()
Beispiel #40
0
def _handle_accept_keywords(session, data, machine_id):
    # Find current entries
    try:
        accept_keywords = data['accept_keywords']
    except KeyError:
        accept_keywords = {}
    current_accept_keywords_set = set()
    for i in accept_keywords:
        if i.startswith('~'):
            key = (i.lstrip('~'), False)
        else:
            key = (i, True)
        current_accept_keywords_set.add(key)

    # Find old entries
    old_accept_keywords_objects = session.query(\
            GentooAcceptKeywordRel).options(\
                eagerload('keyword')).\
            filter_by(machine_id=machine_id).all()
    old_accept_keywords_dict = {}
    for i in old_accept_keywords_objects:
        key = (i.keyword.name, bool(i.stable))
        old_accept_keywords_dict[key] = i
    old_accept_keywords_set = set(old_accept_keywords_dict.keys())

    # Calculate diff
    mappings_to_add = current_accept_keywords_set - old_accept_keywords_set
    mappings_to_remove = old_accept_keywords_set - current_accept_keywords_set

    # Resolve diff
    for i in mappings_to_remove:
        session.delete(old_accept_keywords_dict[i])
    if mappings_to_remove:
        session.flush()
    for i in mappings_to_add:
        keyword, stable = i
        try:
            pool_object = session.query(GentooKeywordString).filter_by(name=keyword).one()
        except sqlalchemy.orm.exc.NoResultFound:
            pool_object = GentooKeywordString(keyword)
            session.add(pool_object)
            session.flush()
        keyword_id = pool_object.id
        session.add(GentooAcceptKeywordRel(machine_id, keyword_id, stable))
    session.flush()
Beispiel #41
0
    def remove(self, **kw):
        group = Group.by_id(kw['group_id'])

        if not group.can_edit(identity.current.user):
            flash(_(u'You are not an owner of group %s' % group))
            redirect('../groups/mine')

        if group.jobs:
            flash(_(u'Cannot delete a group which has associated jobs'))
            redirect('../groups/mine')

        session.delete(group)
        activity = Activity(identity.current.user, u'WEBUI', u'Removed', u'Group', group.display_name, u"")
        session.add(activity)
        for system in group.systems:
            SystemActivity(identity.current.user, u'WEBUI', u'Removed', u'Group', group.display_name, u"", object=system)
        flash( _(u"%s deleted") % group.display_name )
        raise redirect(".")
Beispiel #42
0
def _remove(user, method, **kw):
    if user == identity.current.user:
        raise BX(_('You cannot remove yourself'))

    # cancel all running and queued jobs
    Job.cancel_jobs_by_user(user, 'User %s removed' % user.user_name)

    # Return all systems in use by this user
    for system in System.query.filter(System.user == user):
        reservation = system.open_reservation
        system.unreserve(reservation=reservation, service=method)
    # Return all loaned systems in use by this user
    for system in System.query.filter(System.loaned == user):
        system.record_activity(user=identity.current.user,
                               service=method,
                               action=u'Changed',
                               field=u'Loaned To',
                               old=u'%s' % system.loaned,
                               new=None)
        system.loaned = None
    # Remove the user from all system access policies
    for rule in SystemAccessPolicyRule.query.filter_by(user=user):
        rule.record_deletion(service=method)
        session.delete(rule)
    # Change the owner to the caller
    newowner = kw.get('newowner', identity.current.user)
    for system in System.query.filter(System.owner == user):
        system.owner = newowner
        system.record_activity(user=identity.current.user,
                               service=method,
                               action=u'Changed',
                               field=u'Owner',
                               old=u'%s' % user,
                               new=u'%s' % newowner)
    for pool in SystemPool.query.filter(SystemPool.owning_user == user):
        pool.change_owner(user=newowner, service=method)
    # Remove the user from all groups
    for group in user.groups:
        if not group.membership_type == GroupMembershipType.inverted:
            group.remove_member(user=user,
                                agent=identity.current.user,
                                service=method)
    # Finally remove the user
    user.removed = datetime.utcnow()
Beispiel #43
0
def update_reservation_request(id):
    """
    Updates the reservation request of a recipe. The request must be 
    :mimetype:`application/json`.

    :param id: Recipe's id.
    :jsonparam boolean reserve: Whether the system will be reserved at the end
      of the recipe. If true, the system will be reserved. If false, the system
      will not be reserved.
    :jsonparam int duration: Number of seconds to rerserve the system.
    """

    recipe = _get_recipe_by_id(id)
    if not recipe.can_update_reservation_request(identity.current.user):
        raise Forbidden403('Cannot update the reservation request of recipe %s'
                % recipe.id)
    data = read_json_request(request)
    if 'reserve' not in data:
        raise BadRequest400('No reserve specified')
    with convert_internal_errors():
        if data['reserve']:
            if 'duration' not in data:
                raise BadRequest400('No duration specified')
            duration = data['duration']
            if duration > MAX_SECONDS_PROVISION:
                raise BadRequest400('Reservation time exceeds maximum time of %s hours' % MAX_HOURS_PROVISION)
            if recipe.reservation_request:
                old_duration = recipe.reservation_request.duration
                recipe.reservation_request.duration = data['duration']
                _record_activity(recipe, u'Reservation Request', old_duration,
                        data['duration'])
            else:
                reservation_request = RecipeReservationRequest(data['duration'])
                recipe.reservation_request = reservation_request
                _record_activity(recipe, u'Reservation Request', None,
                        reservation_request.duration, 'Changed')
            return jsonify(recipe.reservation_request.__json__())
        else:
            if recipe.reservation_request:
                session.delete(recipe.reservation_request)
                _record_activity(recipe, u'Reservation Request',
                        recipe.reservation_request.duration, None)
            return jsonify(RecipeReservationRequest.empty_json())
Beispiel #44
0
    def delete(self, fqdn):
        """
        Delete a system with the given fully-qualified domain name.

        The caller must be the owner of the system or an admin.

        :param fqdn: fully-qualified domain name of the system to be deleted
        :type fqdn: string

        .. versionadded:: 0.8.2
        """
        system = System.by_fqdn(fqdn, identity.current.user)
        if system.reservations:
            raise ValueError("Can't delete system %s with reservations" % fqdn)
        if system.owner != identity.current.user and \
           not identity.current.user.is_admin():
            raise ValueError("Can't delete system %s you don't own" % fqdn)
        session.delete(system)
        return 'Deleted %s' % fqdn
Beispiel #45
0
def update_reservation_request(id):
    """
    Updates the reservation request of a recipe. The request must be 
    :mimetype:`application/json`.

    :param id: Recipe's id.
    :jsonparam boolean reserve: Whether the system will be reserved at the end
      of the recipe. If true, the system will be reserved. If false, the system
      will not be reserved.
    :jsonparam int duration: Number of seconds to rerserve the system.
    """

    recipe = _get_recipe_by_id(id)
    if not recipe.can_update_reservation_request(identity.current.user):
        raise Forbidden403('Cannot update the reservation request of recipe %s'
                % recipe.id)
    data = read_json_request(request)
    if 'reserve' not in data:
        raise BadRequest400('No reserve specified')
    with convert_internal_errors():
        if data['reserve']:
            if 'duration' not in data:
                raise BadRequest400('No duration specified')
            duration = data['duration']
            if duration > MAX_SECONDS_PROVISION:
                raise BadRequest400('Reservation time exceeds maximum time of %s hours' % MAX_HOURS_PROVISION)
            if recipe.reservation_request:
                old_duration = recipe.reservation_request.duration
                recipe.reservation_request.duration = data['duration']
                _record_activity(recipe, u'Reservation Request', old_duration,
                        data['duration'])
            else:
                reservation_request = RecipeReservationRequest(data['duration'])
                recipe.reservation_request = reservation_request
                _record_activity(recipe, u'Reservation Request', None,
                        reservation_request.duration, 'Changed')
            return jsonify(recipe.reservation_request.__json__())
        else:
            if recipe.reservation_request:
                session.delete(recipe.reservation_request)
                _record_activity(recipe, u'Reservation Request',
                        recipe.reservation_request.duration, None)
            return jsonify(RecipeReservationRequest.empty_json())
Beispiel #46
0
    def delete(self, fqdn):
        """
        Delete a system with the given fully-qualified domain name.

        The caller must be the owner of the system or an admin.

        :param fqdn: fully-qualified domain name of the system to be deleted
        :type fqdn: string

        .. versionadded:: 0.8.2
        """
        system = System.by_fqdn(fqdn, identity.current.user)
        if system.reservations:
            raise ValueError("Can't delete system %s with reservations" % fqdn)
        if system.owner != identity.current.user and \
           not identity.current.user.is_admin():
            raise ValueError("Can't delete system %s you don't own" % fqdn)
        session.delete(system)
        return 'Deleted %s' % fqdn
Beispiel #47
0
def _handle_privacy_metrics(session, data, machine_id):
    # Find current entries
    try:
        privacy_metrics = data['privacy_metrics']
    except KeyError:
        privacy_metrics = {}
    current_privacy_metrics_set = set()
    for k, v in privacy_metrics.items():
        key = (k, ) + tuple(v)
        current_privacy_metrics_set.add(key)

    # Find old entries
    old_privacy_metrics_objects = session.query(\
            GentooPrivacyMetricRel).options(\
                eagerload('data_class')).\
            filter_by(machine_id=machine_id).all()
    old_privacy_metrics_dict = {}
    for i in old_privacy_metrics_objects:
        key = (i.data_class.name, bool(i.revealed), i.count_private, i.count_non_private)
        old_privacy_metrics_dict[key] = i
    old_privacy_metrics_set = set(old_privacy_metrics_dict.keys())

    # Calculate diff
    mappings_to_add = current_privacy_metrics_set - old_privacy_metrics_set
    mappings_to_remove = old_privacy_metrics_set - current_privacy_metrics_set

    # Resolve diff
    for i in mappings_to_remove:
        session.delete(old_privacy_metrics_dict[i])
    if mappings_to_remove:
        session.flush()
    for i in mappings_to_add:
        data_class, revealed, count_private, count_non_private = i
        try:
            pool_object = session.query(GentooDataClassString).filter_by(name=data_class).one()
        except sqlalchemy.orm.exc.NoResultFound:
            pool_object = GentooDataClassString(data_class)
            session.add(pool_object)
            session.flush()
        data_class_id = pool_object.id
        session.add(GentooPrivacyMetricRel(machine_id, data_class_id, revealed, count_private, count_non_private))
    session.flush()
Beispiel #48
0
    def remove(self, **kw):
        try:
            group = Group.by_id(kw['group_id'])
        except DatabaseLookupError:
            flash(unicode('Invalid group or already removed'))
            redirect('../groups/mine')

        if not group.can_edit(identity.current.user):
            flash(_(u'You are not an owner of group %s' % group))
            redirect('../groups/mine')

        if group.is_protected_group():
            flash(
                _(u'This group %s is predefined and cannot be deleted' %
                  group))
            redirect('../groups/mine')

        if group.jobs:
            flash(_(u'Cannot delete a group which has associated jobs'))
            redirect('../groups/mine')

        # Record the access policy rules that will be removed
        # before deleting the group
        for rule in group.system_access_policy_rules:
            rule.record_deletion()

        session.delete(group)
        activity = Activity(identity.current.user, u'WEBUI', u'Removed',
                            u'Group', group.display_name, u"")
        session.add(activity)
        for system in group.systems:
            session.add(
                SystemActivity(identity.current.user,
                               u'WEBUI',
                               u'Removed',
                               u'Group',
                               group.display_name,
                               u"",
                               object=system))
        flash(_(u"%s deleted") % group.display_name)
        raise redirect(".")
Beispiel #49
0
 def test_02_abort_dead_recipes(self):
     beakerd.process_new_recipes()
     beakerd.update_dirty_jobs()
     beakerd.queue_processed_recipesets()
     beakerd.update_dirty_jobs()
     with session.begin():
         job = Job.by_id(self.job2.id)
         self.assertEqual(job.status, TaskStatus.queued)
         # check if rows in system_recipe_map
         self.assertNotEqual(len(job.recipesets[0].recipes[0].systems), 0)
         # Remove distro_tree2 from lab1, should cause remaining recipe to abort.
         for lca in self.distro_tree2.lab_controller_assocs[:]:
             session.delete(lca)
     beakerd.abort_dead_recipes()
     beakerd.update_dirty_jobs()
     with session.begin():
         job = Job.by_id(self.job2.id)
         self.assertEqual(job.status, TaskStatus.aborted)
         # https://bugzilla.redhat.com/show_bug.cgi?id=1173376
         # check if no rows system_recipe_map
         self.assertEqual(len(job.recipesets[0].recipes[0].systems), 0)
 def test_02_abort_dead_recipes(self):
     beakerd.process_new_recipes()
     beakerd.update_dirty_jobs()
     with session.begin():
         job =  Job.by_id(self.job2.id)
         self.assertEqual(job.status, TaskStatus.processed)
         # check if rows in system_recipe_map
         self.assertNotEqual(len(job.recipesets[0].recipes[0].systems), 0)
         # Remove distro_tree2 from lab1, should cause remaining recipe to abort.
         for lca in self.distro_tree2.lab_controller_assocs[:]:
             session.delete(lca)
     beakerd.queue_processed_recipesets()
     beakerd.update_dirty_jobs()
     beakerd.abort_dead_recipes()
     beakerd.update_dirty_jobs()
     with session.begin():
         job =  Job.by_id(self.job2.id)
         self.assertEqual(job.status, TaskStatus.aborted)
         # https://bugzilla.redhat.com/show_bug.cgi?id=1173376
         # check if no rows system_recipe_map
         self.assertEqual(len(job.recipesets[0].recipes[0].systems), 0)
Beispiel #51
0
    def remove(self, **kw):
        u = identity.current.user
        try:
            group = Group.by_id(kw['group_id'])
        except DatabaseLookupError:
            flash(unicode('Invalid group or already removed'))
            redirect('../groups/mine')

        if not group.can_edit(u):
            flash(_(u'You are not an owner of group %s' % group))
            redirect('../groups/mine')

        if group.is_protected_group():
            flash(
                _(u'This group %s is predefined and cannot be deleted' %
                  group))
            redirect('../groups/mine')

        if group.jobs:
            flash(_(u'Cannot delete a group which has associated jobs'))
            redirect('../groups/mine')

        # Record the access policy rules that will be removed
        # before deleting the group
        for rule in group.system_access_policy_rules:
            rule.record_deletion()

        # For any system pool owned by this group, unset owning_group
        # and set owning_user to the user deleting this group
        pools = SystemPool.query.filter_by(owning_group_id=group.group_id)
        for pool in pools:
            pool.change_owner(user=u, service='WEBUI')
        session.delete(group)
        activity = Activity(u, u'WEBUI', u'Removed', u'Group',
                            group.display_name, u"")
        session.add(activity)
        flash(_(u"%s deleted") % group.display_name)
        raise redirect(".")
Beispiel #52
0
 def delete(cls):
     for role in cls.roles:
         session.delete(role)
     session.delete(cls)
Beispiel #53
0
 def remove(self, **kw):
     remove = Key.by_id(kw['id'])
     session.delete(remove)
     flash( _(u"%s Deleted") % remove.key_name )
     raise redirect(".")
Beispiel #54
0
                if e.faultCode == 51:
                    # This user doesn't have a bugzilla account yet
                    # add them to a list and we'll let them know.
                    no_bz_account.append(entry)
                    continue
                else:
                    print 'Error:', e, entry.email, entry.person.human_name
                    raise
            server.updateperms(entry.email, 'add', bzGroup)
        else:
            print 'Unrecognized action code: %s %s %s %s %s' % (entry.action,
                    entry.email, entry.person.human_name, entry.person.username, entry.group.name)
            continue

        # Remove them from the queue
        session.delete(entry)
        session.flush()

# Mail the people without bugzilla accounts
    if '$USER' in NOTIFYEMAIL:
        for person in no_bz_account:
            smtplib.SMTP(MAILSERVER)
            msg = Message()
            message = '''Hello %(name)s,

    As a Fedora packager, we grant you permissions to make changes to bugs in
    bugzilla to all Fedora bugs.  This lets you work together with other Fedora
    developers in an easier fashion.  However, to enable this functionality, we
    need to have your bugzilla email address stored in the Fedora Account System.
    At the moment you have: