Ejemplo n.º 1
0
    def lab_controller_add(self, distro_tree_id, lab_controller_id, url):
        try:
            distro_tree = DistroTree.by_id(distro_tree_id)
        except NoResultFound:
            flash(_(u'Invalid distro tree id %s') % distro_tree_id)
            redirect('.')
        try:
            lab_controller = LabController.by_id(lab_controller_id)
        except NoResultFound:
            flash(_(u'Invalid lab controller id %s') % lab_controller_id)
            redirect(str(distro_tree.id))

        url = url.strip()
        if not url.endswith('/'):
            url = url + '/'
        if not urlparse.urlparse(url).scheme:
            flash(_(u'URL %r is not absolute') % url)
            redirect(str(distro_tree.id))
        distro_tree.lab_controller_assocs.append(
                LabControllerDistroTree(lab_controller=lab_controller, url=url))
        distro_tree.activity.append(DistroTreeActivity(
                user=identity.current.user, service=u'WEBUI',
                action=u'Added', field_name=u'lab_controller_assocs',
                old_value=None, new_value=u'%s %s' % (lab_controller, url)))
        flash(_(u'Added %s %s') % (lab_controller, url))
        redirect(str(distro_tree.id))
Ejemplo n.º 2
0
    def validate_python(self, form_fields, state):
        lc_id = form_fields.get('id', None)
        email_address = form_fields['email']
        user_name = form_fields['lusername']

        try:
            User.by_email_address(email_address)
        except NoResultFound:
            email_is_used = False
        else:
            email_is_used = True

        if User.by_user_name(user_name):
            new_user = False
        else:
            new_user = True

        if not lc_id:
            labcontroller = None
            luser = None
        else:
            labcontroller = LabController.by_id(lc_id)
            luser = labcontroller.user

        try:
            if not labcontroller and email_is_used: # New LC using dupe email
                raise ValueError
            if new_user and email_is_used: #New user using dupe email
                raise ValueError
            if luser:
                _check_user_email(email_address, luser.user_id)
        except ValueError:
            error = {'email' : self.message('not_unique', state)}
            raise Invalid('Email address is not unique', form_fields,
                state, error_dict=error)
Ejemplo n.º 3
0
 def has_active_recipes(self, id):
     labcontroller = LabController.by_id(id)
     count = Watchdog.by_status(labcontroller=labcontroller, status='active').count()
     if count:
         return {'has_active_recipes' : True}
     else:
         return {'has_active_recipes' : False}
Ejemplo n.º 4
0
    def lab_controller_add(self, distro_tree_id, lab_controller_id, url):
        try:
            distro_tree = DistroTree.by_id(distro_tree_id)
        except NoResultFound:
            flash(_(u'Invalid distro tree id %s') % distro_tree_id)
            redirect('.')
        try:
            lab_controller = LabController.by_id(lab_controller_id)
        except ValueError:
            flash(_(u'Invalid lab controller id %s') % lab_controller_id)
            redirect(str(distro_tree.id))

        url = url.strip()
        if not url.endswith('/'):
            url = url + '/'
        if not urlparse.urlparse(url).scheme:
            flash(_(u'URL %r is not absolute') % url)
            redirect(str(distro_tree.id))
        distro_tree.lab_controller_assocs.append(
                LabControllerDistroTree(lab_controller=lab_controller, url=url))
        distro_tree.activity.append(DistroTreeActivity(
                user=identity.current.user, service=u'WEBUI',
                action=u'Added', field_name=u'lab_controller_assocs',
                old_value=None, new_value=u'%s %s' % (lab_controller, url)))
        flash(_(u'Added %s %s') % (lab_controller, url))
        redirect(str(distro_tree.id))
Ejemplo n.º 5
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(".")
Ejemplo n.º 6
0
    def remove(self, id, *args, **kw):
        labcontroller = LabController.by_id(id)
        labcontroller.removed = datetime.utcnow()
        # de-associate systems
        systems = System.query.filter(System.lab_controller == labcontroller)
        System.record_bulk_activity(systems, user=identity.current.user,
                service=u'WEBUI', action=u'Changed', field=u'lab_controller',
                old=labcontroller.fqdn, new=None)
        systems.update({'lab_controller_id': None}, synchronize_session=False)
        # cancel running recipes
        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)
        # remove distro trees
        distro_tree_assocs = LabControllerDistroTree.query\
            .filter(LabControllerDistroTree.lab_controller == labcontroller)\
            .join(LabControllerDistroTree.distro_tree)
        DistroTree.record_bulk_activity(distro_tree_assocs, user=identity.current.user,
                service=u'WEBUI', action=u'Removed', field=u'lab_controller_assocs',
                old=labcontroller.fqdn, new=None)
        distro_tree_assocs.delete(synchronize_session=False)
        labcontroller.disabled = True
        labcontroller.record_activity(user=identity.current.user, service=u'WEBUI',
                field=u'Disabled', action=u'Changed', old=unicode(False), new=unicode(True))
        labcontroller.record_activity(user=identity.current.user, service=u'WEBUI',
                field=u'Removed', action=u'Changed', old=unicode(False), new=unicode(True))

        flash( _(u"%s removed") % labcontroller.fqdn )
        raise redirect(".")
Ejemplo n.º 7
0
 def has_active_recipes(self, id):
     labcontroller = LabController.by_id(id)
     count = Watchdog.by_status(labcontroller=labcontroller,
                                status='active').count()
     if count:
         return {'has_active_recipes': True}
     else:
         return {'has_active_recipes': False}
Ejemplo n.º 8
0
    def unremove(self, id):
        labcontroller = LabController.by_id(id)
        labcontroller.removed = None
        labcontroller.disabled = False

        labcontroller.record_activity(user=identity.current.user, service=u'WEBUI',
                field=u'Disabled', action=u'Changed', old=unicode(True), new=unicode(False))
        labcontroller.record_activity(user=identity.current.user, service=u'WEBUI',
                field=u'Removed', action=u'Changed', old=unicode(True), new=unicode(False))
        flash('Successfully re-added %s' % labcontroller.fqdn)
        redirect(url('.'))
Ejemplo n.º 9
0
    def unremove(self, id):
        labcontroller = LabController.by_id(id)
        labcontroller.removed = None
        labcontroller.disabled = False

        LabControllerActivity(identity.current.user, 'WEBUI', 
            'Changed', 'Disabled', unicode(True), unicode(False),
            lab_controller_id = id)
        LabControllerActivity(identity.current.user, 'WEBUI', 
            'Changed', 'Removed', unicode(True), unicode(False), 
            lab_controller_id=id)
        flash('Succesfully re-added %s' % labcontroller.fqdn)
        redirect(url('.'))
Ejemplo n.º 10
0
    def edit(self, id, **kw):
        options = {}
        if id:
            labcontroller = LabController.by_id(id)
            options.update({'user': labcontroller.user})
        else:
            labcontroller = None

        return dict(form=self.labcontroller_form,
                    action='./save',
                    options=options,
                    value=labcontroller,
                    title='Edit Lab Controller')
Ejemplo n.º 11
0
    def save(self, **kw):
        if kw.get('id'):
            labcontroller = LabController.by_id(kw['id'])
        else:
            labcontroller = LabController()
            session.add(labcontroller)
        if labcontroller.fqdn != kw['fqdn']:
            activity = LabControllerActivity(identity.current.user, 'WEBUI',
                                             'Changed', 'FQDN',
                                             labcontroller.fqdn, kw['fqdn'])
            labcontroller.fqdn = kw['fqdn']
            labcontroller.write_activity.append(activity)

        # labcontroller.user is used by the lab controller to login here
        try:
            # pick up an existing user if it exists.
            luser = User.query.filter_by(user_name=kw['lusername']).one()
        except InvalidRequestError:
            # Nope, create from scratch
            luser = User()
        if labcontroller.user != luser:
            if labcontroller.user is None:
                old_user_name = None
            else:
                old_user_name = labcontroller.user.user_name
            activity = LabControllerActivity(identity.current.user, 'WEBUI',
                                             'Changed', 'User', old_user_name,
                                             unicode(kw['lusername']))
            labcontroller.user = luser
            labcontroller.write_activity.append(activity)

        # Make sure user is a member of lab_controller group
        group = Group.by_name(u'lab_controller')
        if group not in luser.groups:
            luser.groups.append(group)
        luser.display_name = kw['fqdn']
        luser.email_address = kw['email']
        luser.user_name = kw['lusername']

        if kw['lpassword']:
            luser.password = kw['lpassword']
        if labcontroller.disabled != kw['disabled']:
            activity = LabControllerActivity(identity.current.user, 'WEBUI',
                                             'Changed', 'Disabled',
                                             unicode(labcontroller.disabled),
                                             unicode(kw['disabled']))
            labcontroller.disabled = kw['disabled']
            labcontroller.write_activity.append(activity)

        flash(_(u"%s saved" % labcontroller.fqdn))
        redirect(".")
Ejemplo n.º 12
0
    def edit(self, id, **kw):
        options = {}
        if id:
            labcontroller = LabController.by_id(id)
            options.update({'user' : labcontroller.user})
        else:
            labcontroller=None

        return dict(
            form = self.labcontroller_form,
            action = './save',
            options = options,
            value = labcontroller,
        )
Ejemplo n.º 13
0
    def save(self, **kw):
        if kw.get('id'):
            labcontroller = LabController.by_id(kw['id'])
        else:
            labcontroller =  LabController()
            session.add(labcontroller)
        if labcontroller.fqdn != kw['fqdn']:
            activity = LabControllerActivity(identity.current.user,
                'WEBUI', 'Changed', 'FQDN', labcontroller.fqdn, kw['fqdn'])
            labcontroller.fqdn = kw['fqdn']
            labcontroller.write_activity.append(activity)

        # labcontroller.user is used by the lab controller to login here
        try:
            # pick up an existing user if it exists.
            luser = User.query.filter_by(user_name=kw['lusername']).one()
        except InvalidRequestError:
            # Nope, create from scratch
            luser = User()
        if labcontroller.user != luser:
            if labcontroller.user is None:
                old_user_name = None
            else:
                old_user_name = labcontroller.user.user_name
            activity = LabControllerActivity(identity.current.user, 'WEBUI',
                'Changed', 'User', old_user_name, unicode(kw['lusername']))
            labcontroller.user = luser
            labcontroller.write_activity.append(activity)

        # Make sure user is a member of lab_controller group
        group = Group.by_name(u'lab_controller')
        if group not in luser.groups:
            luser.groups.append(group)
        luser.display_name = kw['fqdn']
        luser.email_address = kw['email']
        luser.user_name = kw['lusername']

        if kw['lpassword']:
            luser.password = kw['lpassword']
        if labcontroller.disabled != kw['disabled']:
            activity = LabControllerActivity(identity.current.user, 'WEBUI',
                'Changed', 'Disabled', unicode(labcontroller.disabled), 
                unicode(kw['disabled']))
            labcontroller.disabled = kw['disabled']
            labcontroller.write_activity.append(activity)

        flash( _(u"%s saved" % labcontroller.fqdn) )
        redirect(".")
Ejemplo n.º 14
0
    def remove(self, id, *args, **kw):
        labcontroller = LabController.by_id(id)
        labcontroller.removed = datetime.utcnow()
        # de-associate systems
        systems = System.query.filter(System.lab_controller == labcontroller)
        System.record_bulk_activity(systems,
                                    user=identity.current.user,
                                    service=u'WEBUI',
                                    action=u'Changed',
                                    field=u'lab_controller',
                                    old=labcontroller.fqdn,
                                    new=None)
        systems.update({'lab_controller_id': None}, synchronize_session=False)
        # cancel running recipes
        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)
        # remove distro trees
        distro_tree_assocs = LabControllerDistroTree.query\
            .filter(LabControllerDistroTree.lab_controller == labcontroller)\
            .join(LabControllerDistroTree.distro_tree)
        DistroTree.record_bulk_activity(distro_tree_assocs,
                                        user=identity.current.user,
                                        service=u'WEBUI',
                                        action=u'Removed',
                                        field=u'lab_controller_assocs',
                                        old=labcontroller.fqdn,
                                        new=None)
        distro_tree_assocs.delete(synchronize_session=False)
        labcontroller.disabled = True
        labcontroller.record_activity(user=identity.current.user,
                                      service=u'WEBUI',
                                      field=u'Disabled',
                                      action=u'Changed',
                                      old=unicode(False),
                                      new=unicode(True))
        labcontroller.record_activity(user=identity.current.user,
                                      service=u'WEBUI',
                                      field=u'Removed',
                                      action=u'Changed',
                                      old=unicode(False),
                                      new=unicode(True))

        flash(_(u"%s removed") % labcontroller.fqdn)
        raise redirect(".")
Ejemplo n.º 15
0
    def unremove(self, id):
        labcontroller = LabController.by_id(id)
        labcontroller.removed = None
        labcontroller.disabled = False

        labcontroller.record_activity(user=identity.current.user,
                                      service=u'WEBUI',
                                      field=u'Disabled',
                                      action=u'Changed',
                                      old=unicode(True),
                                      new=unicode(False))
        labcontroller.record_activity(user=identity.current.user,
                                      service=u'WEBUI',
                                      field=u'Removed',
                                      action=u'Changed',
                                      old=unicode(True),
                                      new=unicode(False))
        flash('Successfully re-added %s' % labcontroller.fqdn)
        redirect(url('.'))
Ejemplo n.º 16
0
    def validate_python(self, form_fields, state):
        lc_id = form_fields.get('id', None)
        fqdn = form_fields['fqdn']
        lusername = form_fields['lusername']

        try:
            existing_lc_with_fqdn = LabController.by_name(fqdn)
        except NoResultFound:
            existing_lc_with_fqdn = None

        existing_user_with_lusername = User.by_user_name(lusername)

        if not lc_id:
            labcontroller = None
            luser = None
        else:
            labcontroller = LabController.by_id(lc_id)
            luser = labcontroller.user

        errors = {}
        if not labcontroller and existing_lc_with_fqdn:
            # New LC using duplicate FQDN
            errors['fqdn'] = self.message('fqdn_not_unique', state)
        elif (labcontroller and existing_lc_with_fqdn
              and labcontroller != existing_lc_with_fqdn):
            # Existing LC changing FQDN to a duplicate one
            errors['fqdn'] = self.message('fqdn_not_unique', state)
        if (not luser and existing_user_with_lusername
                and existing_user_with_lusername.lab_controller):
            # New LC using username that is already in use
            errors['lusername'] = self.message('username_in_use', state)
        if (luser and existing_user_with_lusername
                and luser != existing_user_with_lusername
                and existing_user_with_lusername.lab_controller):
            # Existing LC changing username to one that is already in use
            errors['lusername'] = self.message('username_in_use', state)
        if errors:
            raise Invalid('Validation failed',
                          form_fields,
                          state,
                          error_dict=errors)
Ejemplo n.º 17
0
 def _get_distro_tree_options(self, distro=None, lab_controller_id=None, **kwargs):
     """
     Returns a list of distro trees for the given distro.
     """
     if not distro:
         return []
     try:
         distro = Distro.by_name(distro)
     except NoResultFound:
         return []
     trees = distro.dyn_trees.join(DistroTree.arch)\
             .order_by(DistroTree.variant, Arch.arch)
     if lab_controller_id:
         try:
             lc = LabController.by_id(lab_controller_id)
         except NoResultFound:
             return []
         trees = trees.filter(DistroTree.lab_controller_assocs.any(
                 LabControllerDistroTree.lab_controller == lc))
     else:
         trees = trees.filter(DistroTree.lab_controller_assocs.any())
     return [(tree.id, unicode(tree)) for tree in trees]
Ejemplo n.º 18
0
    def validate_python(self, form_fields, state):
        lc_id = form_fields.get('id', None)
        fqdn = form_fields['fqdn']
        lusername = form_fields['lusername']

        try:
            existing_lc_with_fqdn = LabController.by_name(fqdn)
        except NoResultFound:
            existing_lc_with_fqdn = None

        existing_user_with_lusername = User.by_user_name(lusername)

        if not lc_id:
            labcontroller = None
            luser = None
        else:
            labcontroller = LabController.by_id(lc_id)
            luser = labcontroller.user

        errors = {}
        if not labcontroller and existing_lc_with_fqdn:
            # New LC using duplicate FQDN
            errors['fqdn'] = self.message('fqdn_not_unique', state)
        elif (labcontroller and existing_lc_with_fqdn and
                labcontroller != existing_lc_with_fqdn):
            # Existing LC changing FQDN to a duplicate one
            errors['fqdn'] = self.message('fqdn_not_unique', state)
        if (not luser and existing_user_with_lusername and
                existing_user_with_lusername.lab_controller):
            # New LC using username that is already in use
            errors['lusername'] = self.message('username_in_use', state)
        if (luser and existing_user_with_lusername and
                luser != existing_user_with_lusername and
                existing_user_with_lusername.lab_controller):
            # Existing LC changing username to one that is already in use
            errors['lusername'] = self.message('username_in_use', state)
        if errors:
            raise Invalid('Validation failed', form_fields,
                    state, error_dict=errors)
Ejemplo n.º 19
0
    def lab_controller_add(self, distro_tree_id, lab_controller_id, url):
        try:
            distro_tree = DistroTree.by_id(distro_tree_id)
        except NoResultFound:
            flash(_(u'Invalid distro tree id %s') % distro_tree_id)
            redirect('.')
        try:
            lab_controller = LabController.by_id(lab_controller_id)
        except ValueError:
            flash(_(u'Invalid lab controller id %s') % lab_controller_id)
            redirect(str(distro_tree.id))

        # make sure the url ends with /
        url = os.path.join(url.strip(), '')
        try:
            self.add_distro_urls(distro_tree, lab_controller, [url])
        except ValueError as e:
            flash(_(u'%s') % e)
            redirect(str(distro_tree.id))

        flash(_(u'Changed/Added %s %s') % (lab_controller, url))
        redirect(str(distro_tree.id))
Ejemplo n.º 20
0
def update_system(fqdn):
    system = _get_system_by_FQDN(fqdn)
    if not system.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit system')
    data = read_json_request(request)
    # helper for recording activity below
    def record_activity(field, old, new, action=u'Changed'):
        system.record_activity(user=identity.current.user, service=u'HTTP',
                action=action, field=field, old=old, new=new)
    with convert_internal_errors():
        # XXX what a nightmare... need to use a validation/conversion library, 
        # and maybe simplify/relocate the activity recording stuff somehow
        changed = False
        renamed = False
        if 'fqdn' in data:
            new_fqdn = data['fqdn'].lower()
            if new_fqdn != system.fqdn:
                if System.query.filter(System.fqdn == new_fqdn).count():
                    raise Conflict409('System %s already exists' % new_fqdn)
                record_activity(u'FQDN', system.fqdn, new_fqdn)
                system.fqdn = new_fqdn
                changed = True
                renamed = True
        if 'owner' in data and data['owner'].get('user_name') != system.owner.user_name:
            if not system.can_change_owner(identity.current.user):
                raise Forbidden403('Cannot change owner')
            new_owner = User.by_user_name(data['owner'].get('user_name'))
            if new_owner is None:
                raise BadRequest400('No such user %s' % data['owner'].get('user_name'))
            record_activity(u'Owner', system.owner, new_owner)
            system.owner = new_owner
            changed = True
        if 'status' in data:
            new_status = SystemStatus.from_string(data['status'])
            if new_status != system.status:
                record_activity(u'Status', system.status, new_status)
                system.status = new_status
                if not new_status.bad and system.status_reason:
                    # clear the status reason for "good" statuses
                    record_activity(u'Status Reason', system.status_reason, None)
                    system.status_reason = None
                changed = True
        if 'status_reason' in data:
            new_reason = data['status_reason'] or None
            if new_reason and not system.status.bad:
                raise ValueError('Cannot set status reason when status is %s'
                        % system.status)
            if new_reason != system.status_reason:
                record_activity(u'Status Reason', system.status_reason, new_reason)
                system.status_reason = new_reason
                changed = True
        if 'type' in data:
            new_type = SystemType.from_string(data['type'])
            if new_type != system.type:
                record_activity(u'Type', system.type, new_type)
                system.type = new_type
                changed = True
        if 'arches' in data:
            new_arches = [Arch.by_name(a) for a in (data['arches'] or [])]
            added_arches = set(new_arches).difference(system.arch)
            removed_arches = set(system.arch).difference(new_arches)
            if added_arches or removed_arches:
                for added_arch in added_arches:
                    record_activity(u'Arch', None, added_arch, u'Added')
                for removed_arch in removed_arches:
                    record_activity(u'Arch', removed_arch, None, u'Removed')
                system.arch[:] = new_arches
                changed = True
        if 'lab_controller_id' in data:
            if data['lab_controller_id']:
                new_lc = LabController.by_id(data['lab_controller_id'])
            else:
                new_lc = None
            if new_lc != system.lab_controller:
                if system.open_reservation is not None:
                    raise Conflict409('Unable to change lab controller while system '
                            'is in use (return the system first)')
                record_activity(u'Lab Controller', system.lab_controller, new_lc)
                system.lab_controller = new_lc
                changed = True
        # If we're given any power-related keys, need to ensure system.power exists
        if not system.power and set(['power_type', 'power_address', 'power_user',
                'power_password', 'power_id', 'power_quiescent_period'])\
                .intersection(data.keys()):
            system.power = Power()
        if 'power_type' in data:
            new_power_type = PowerType.by_name(data['power_type'])
            if new_power_type != system.power.power_type:
                if not system.power.power_type:
                    old_power_type = ''
                else:
                    old_power_type = system.power.power_type.name
                record_activity(u'power_type', old_power_type, new_power_type.name)
                system.power.power_type = new_power_type
                changed = True
        if 'power_address' in data:
            new_power_address = data['power_address']
            if not new_power_address:
                raise ValueError('Power address is required')
            if new_power_address != system.power.power_address:
                record_activity(u'power_address', system.power.power_address,
                        data['power_address'])
                system.power.power_address = new_power_address
                changed = True
        if 'power_user' in data:
            new_power_user = data['power_user'] or u''
            if new_power_user != (system.power.power_user or u''):
                record_activity(u'power_user', u'********', u'********')
                system.power.power_user = new_power_user
                changed = True
        if 'power_password' in data:
            new_power_password = data['power_password'] or u''
            if new_power_password != (system.power.power_passwd or u''):
                record_activity(u'power_passwd', u'********', u'********')
                system.power.power_passwd = new_power_password
                changed = True
        if 'power_id' in data:
            new_power_id = data['power_id'] or u''
            if new_power_id != (system.power.power_id or u''):
                record_activity(u'power_id', system.power.power_id, new_power_id)
                system.power.power_id = new_power_id
                changed = True
        if 'power_quiescent_period' in data:
            new_qp = int(data['power_quiescent_period'])
            if new_qp != system.power.power_quiescent_period:
                record_activity(u'power_quiescent_period',
                        system.power.power_quiescent_period, new_qp)
                system.power.power_quiescent_period = new_qp
                changed = True
        if 'release_action' in data:
            new_release_action = ReleaseAction.from_string(data['release_action'])
            if new_release_action != (system.release_action or ReleaseAction.power_off):
                record_activity(u'release_action',
                        (system.release_action or ReleaseAction.power_off),
                        new_release_action)
                system.release_action = new_release_action
                changed = True
        if 'reprovision_distro_tree' in data:
            if (not data['reprovision_distro_tree'] or
                    'id' not in data['reprovision_distro_tree']):
                new_rpdt = None
            else:
                new_rpdt = DistroTree.by_id(data['reprovision_distro_tree']['id'])
            if new_rpdt != system.reprovision_distro_tree:
                record_activity(u'reprovision_distro_tree',
                        unicode(system.reprovision_distro_tree),
                        unicode(new_rpdt))
                system.reprovision_distro_tree = new_rpdt
                changed = True
        if 'location' in data:
            new_location = data['location'] or None
            if new_location != system.location:
                record_activity(u'Location', system.location, new_location)
                system.location = new_location
                changed = True
        if 'lender' in data:
            new_lender = data['lender'] or None
            if new_lender != system.lender:
                record_activity(u'Lender', system.lender, new_lender)
                system.lender = new_lender
                changed = True
        if 'kernel_type' in data:
            new_kernel_type = KernelType.by_name(data['kernel_type'])
            if new_kernel_type != system.kernel_type:
                record_activity(u'Kernel Type', system.kernel_type, new_kernel_type)
                system.kernel_type = new_kernel_type
                changed = True
        if 'hypervisor' in data:
            if data['hypervisor']:
                new_hypervisor = Hypervisor.by_name(data['hypervisor'])
            else:
                new_hypervisor = None
            if new_hypervisor != system.hypervisor:
                record_activity(u'Hypervisor', system.hypervisor, new_hypervisor)
                system.hypervisor = new_hypervisor
                changed = True
        if 'vendor' in data:
            new_vendor = data['vendor'] or None
            if new_vendor != system.vendor:
                record_activity(u'Vendor', system.vendor, new_vendor)
                system.vendor = new_vendor
                changed = True
        if 'model' in data:
            new_model = data['model'] or None
            if new_model != system.model:
                record_activity(u'Model', system.model, new_model)
                system.model = new_model
                changed = True
        if 'serial_number' in data:
            new_serial_number = data['serial_number'] or None
            if new_serial_number != system.serial:
                record_activity(u'Serial Number', system.serial, new_serial_number)
                system.serial = new_serial_number
                changed = True
        if 'mac_address' in data:
            new_mac_address = data['mac_address'] or None
            if new_mac_address != system.mac_address:
                record_activity(u'MAC Address', system.mac_address, new_mac_address)
                system.mac_address = new_mac_address
                changed = True
        if 'memory' in data:
            new_memory = int(data['memory']) if data['memory'] else None
            if new_memory != system.memory:
                record_activity(u'Memory', system.memory, new_memory)
                system.memory = new_memory
                changed = True
        if 'numa_nodes' in data:
            new_numa_nodes = int(data['numa_nodes']) if data['numa_nodes'] else None
            if not system.numa:
                system.numa = Numa()
            if new_numa_nodes != system.numa.nodes:
                record_activity(u'NUMA/Nodes', system.numa.nodes, new_numa_nodes)
                system.numa.nodes = new_numa_nodes
                changed = True
        if changed:
            # XXX clear checksum!?
            system.date_modified = datetime.datetime.utcnow()
    response = jsonify(system.__json__())
    if renamed:
        response.headers.add('Location', url('/view/%s' % system.fqdn))
    return response
Ejemplo n.º 21
0
def update_system(fqdn):
    system = _get_system_by_FQDN(fqdn)
    if not system.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit system')
    data = read_json_request(request)

    # helper for recording activity below
    def record_activity(field, old, new, action=u'Changed'):
        system.record_activity(user=identity.current.user,
                               service=u'HTTP',
                               action=action,
                               field=field,
                               old=old,
                               new=new)

    with convert_internal_errors():
        # XXX what a nightmare... need to use a validation/conversion library,
        # and maybe simplify/relocate the activity recording stuff somehow
        changed = False
        renamed = False
        if 'fqdn' in data:
            new_fqdn = data['fqdn'].lower()
            if new_fqdn != system.fqdn:
                if System.query.filter(System.fqdn == new_fqdn).count():
                    raise Conflict409('System %s already exists' % new_fqdn)
                record_activity(u'FQDN', system.fqdn, new_fqdn)
                system.fqdn = new_fqdn
                changed = True
                renamed = True
        if 'owner' in data and data['owner'].get(
                'user_name') != system.owner.user_name:
            if not system.can_change_owner(identity.current.user):
                raise Forbidden403('Cannot change owner')
            new_owner = User.by_user_name(data['owner'].get('user_name'))
            if new_owner is None:
                raise BadRequest400('No such user %s' %
                                    data['owner'].get('user_name'))
            record_activity(u'Owner', system.owner, new_owner)
            system.owner = new_owner
            changed = True
        if 'status' in data:
            new_status = SystemStatus.from_string(data['status'])
            if new_status != system.status:
                record_activity(u'Status', system.status, new_status)
                system.status = new_status
                if not new_status.bad and system.status_reason:
                    # clear the status reason for "good" statuses
                    record_activity(u'Status Reason', system.status_reason,
                                    None)
                    system.status_reason = None
                changed = True
        if 'status_reason' in data:
            new_reason = data['status_reason'] or None
            if new_reason and not system.status.bad:
                raise ValueError('Cannot set status reason when status is %s' %
                                 system.status)
            if new_reason != system.status_reason:
                record_activity(u'Status Reason', system.status_reason,
                                new_reason)
                system.status_reason = new_reason
                changed = True
        if 'type' in data:
            new_type = SystemType.from_string(data['type'])
            if new_type != system.type:
                record_activity(u'Type', system.type, new_type)
                system.type = new_type
                changed = True
        if 'arches' in data:
            new_arches = [Arch.by_name(a) for a in (data['arches'] or [])]
            added_arches = set(new_arches).difference(system.arch)
            removed_arches = set(system.arch).difference(new_arches)
            if added_arches or removed_arches:
                for added_arch in added_arches:
                    record_activity(u'Arch', None, added_arch, u'Added')
                for removed_arch in removed_arches:
                    record_activity(u'Arch', removed_arch, None, u'Removed')
                system.arch[:] = new_arches
                changed = True
        if 'lab_controller_id' in data:
            if data['lab_controller_id']:
                new_lc = LabController.by_id(data['lab_controller_id'])
            else:
                new_lc = None
            if new_lc != system.lab_controller:
                if system.open_reservation is not None:
                    raise Conflict409(
                        'Unable to change lab controller while system '
                        'is in use (return the system first)')
                record_activity(u'Lab Controller', system.lab_controller,
                                new_lc)
                system.lab_controller = new_lc
                changed = True
        # If we're given any power-related keys, need to ensure system.power exists
        if not system.power and set(['power_type', 'power_address', 'power_user',
                'power_password', 'power_id', 'power_quiescent_period'])\
                .intersection(data.keys()):
            system.power = Power()
        if 'power_type' in data:
            new_power_type = PowerType.by_name(data['power_type'])
            if new_power_type != system.power.power_type:
                if not system.power.power_type:
                    old_power_type = ''
                else:
                    old_power_type = system.power.power_type.name
                record_activity(u'power_type', old_power_type,
                                new_power_type.name)
                system.power.power_type = new_power_type
                changed = True
        if 'power_address' in data:
            new_power_address = data['power_address']
            if not new_power_address:
                raise ValueError('Power address is required')
            if new_power_address != system.power.power_address:
                record_activity(u'power_address', system.power.power_address,
                                data['power_address'])
                system.power.power_address = new_power_address
                changed = True
        if 'power_user' in data:
            new_power_user = data['power_user'] or u''
            if new_power_user != (system.power.power_user or u''):
                record_activity(u'power_user', u'********', u'********')
                system.power.power_user = new_power_user
                changed = True
        if 'power_password' in data:
            new_power_password = data['power_password'] or u''
            if new_power_password != (system.power.power_passwd or u''):
                record_activity(u'power_passwd', u'********', u'********')
                system.power.power_passwd = new_power_password
                changed = True
        if 'power_id' in data:
            new_power_id = data['power_id'] or u''
            if new_power_id != (system.power.power_id or u''):
                record_activity(u'power_id', system.power.power_id,
                                new_power_id)
                system.power.power_id = new_power_id
                changed = True
        if 'power_quiescent_period' in data:
            new_qp = int(data['power_quiescent_period'])
            if new_qp != system.power.power_quiescent_period:
                record_activity(u'power_quiescent_period',
                                system.power.power_quiescent_period, new_qp)
                system.power.power_quiescent_period = new_qp
                changed = True
        if 'release_action' in data:
            new_release_action = ReleaseAction.from_string(
                data['release_action'])
            if new_release_action != (system.release_action
                                      or ReleaseAction.power_off):
                record_activity(
                    u'release_action',
                    (system.release_action or ReleaseAction.power_off),
                    new_release_action)
                system.release_action = new_release_action
                changed = True
        if 'reprovision_distro_tree' in data:
            if (not data['reprovision_distro_tree']
                    or 'id' not in data['reprovision_distro_tree']):
                new_rpdt = None
            else:
                new_rpdt = DistroTree.by_id(
                    data['reprovision_distro_tree']['id'])
            if new_rpdt != system.reprovision_distro_tree:
                record_activity(u'reprovision_distro_tree',
                                unicode(system.reprovision_distro_tree),
                                unicode(new_rpdt))
                system.reprovision_distro_tree = new_rpdt
                changed = True
        if 'location' in data:
            new_location = data['location'] or None
            if new_location != system.location:
                record_activity(u'Location', system.location, new_location)
                system.location = new_location
                changed = True
        if 'lender' in data:
            new_lender = data['lender'] or None
            if new_lender != system.lender:
                record_activity(u'Lender', system.lender, new_lender)
                system.lender = new_lender
                changed = True
        if 'kernel_type' in data:
            new_kernel_type = KernelType.by_name(data['kernel_type'])
            if new_kernel_type != system.kernel_type:
                record_activity(u'Kernel Type', system.kernel_type,
                                new_kernel_type)
                system.kernel_type = new_kernel_type
                changed = True
        if 'hypervisor' in data:
            if data['hypervisor']:
                new_hypervisor = Hypervisor.by_name(data['hypervisor'])
            else:
                new_hypervisor = None
            if new_hypervisor != system.hypervisor:
                record_activity(u'Hypervisor', system.hypervisor,
                                new_hypervisor)
                system.hypervisor = new_hypervisor
                changed = True
        if 'vendor' in data:
            new_vendor = data['vendor'] or None
            if new_vendor != system.vendor:
                record_activity(u'Vendor', system.vendor, new_vendor)
                system.vendor = new_vendor
                changed = True
        if 'model' in data:
            new_model = data['model'] or None
            if new_model != system.model:
                record_activity(u'Model', system.model, new_model)
                system.model = new_model
                changed = True
        if 'serial_number' in data:
            new_serial_number = data['serial_number'] or None
            if new_serial_number != system.serial:
                record_activity(u'Serial Number', system.serial,
                                new_serial_number)
                system.serial = new_serial_number
                changed = True
        if 'mac_address' in data:
            new_mac_address = data['mac_address'] or None
            if new_mac_address != system.mac_address:
                record_activity(u'MAC Address', system.mac_address,
                                new_mac_address)
                system.mac_address = new_mac_address
                changed = True
        if 'memory' in data:
            new_memory = int(data['memory']) if data['memory'] else None
            if new_memory != system.memory:
                record_activity(u'Memory', system.memory, new_memory)
                system.memory = new_memory
                changed = True
        if 'numa_nodes' in data:
            new_numa_nodes = int(
                data['numa_nodes']) if data['numa_nodes'] else None
            if not system.numa:
                system.numa = Numa()
            if new_numa_nodes != system.numa.nodes:
                record_activity(u'NUMA/Nodes', system.numa.nodes,
                                new_numa_nodes)
                system.numa.nodes = new_numa_nodes
                changed = True
        if changed:
            # XXX clear checksum!?
            system.date_modified = datetime.datetime.utcnow()
    response = jsonify(system.__json__())
    if renamed:
        response.headers.add('Location', url('/view/%s' % system.fqdn))
    return response