Esempio n. 1
0
    def watchdogs(self, status='active', lc=None):
        """ Return all active/expired tasks for this lab controller
            The lab controllers login with host/fqdn
        """
        # TODO work on logic that determines whether or not originator
        # was qpid or kobo ?
        if lc is None:
            try:
                labcontroller = identity.current.user.lab_controller
            except AttributeError:
                raise BX(
                    _('No lab controller passed in and not currently logged in'
                      ))

            if not labcontroller:
                raise BX(
                    _(u'Invalid login: %s, must log in as a lab controller' %
                      identity.current.user))
        else:
            try:
                labcontroller = LabController.by_name(lc)
            except InvalidRequestError:
                raise BX(_(u'Invalid lab controller: %s' % lc))

        return [
            dict(recipe_id=w.recipe.id,
                 system=w.recipe.resource.fqdn,
                 is_virt_recipe=(w.recipe.resource.type == ResourceType.virt))
            for w in Watchdog.by_status(labcontroller, status)
        ]
Esempio n. 2
0
 def _check_lc_leaks(self):
     with session.begin():
         lc = LabController.by_name(lc_fqdn)
         # check for outstanding watchdogs
         watchdogs = Watchdog.query\
             .join(Watchdog.recipe).join(Recipe.recipeset)\
             .filter(RecipeSet.lab_controller == lc)
         if watchdogs.count():
             # If your test case hits this error, you need to fix it so that 
             # any running recipes are cancelled otherwise beaker-watchdog 
             # will eventually pick them up and abort them, interfering with 
             # some later test.
             raise AssertionError('Leaked watchdogs for %s: %s'
                     % (lc_fqdn, watchdogs.all()))
         # check for systems left associated to the LC
         systems = System.query.filter(System.lab_controller == lc)
         if systems.count():
             # If your test case hits this error, you need to fix it so that 
             # any systems which were associated to the LC are 
             # de-associated, otherwise subsequent tests which invoke the 
             # scheduler will try to schedule recipes onto the system and 
             # then beaker-provision will start trying to run the 
             # provisioning commands.
             raise AssertionError('Leaked systems for %s: %s'
                     % (lc_fqdn, systems.all()))
Esempio n. 3
0
 def test_lookup_secret_fqdn(self):
     with session.begin():
         system = data_setup.create_system()
         system.private = True
     lab_controller_user = LabController.by_name(self.lc_fqdn).user
     system2 = System.by_fqdn(str(system.fqdn), user=lab_controller_user)
     self.assertEquals(system, system2)
Esempio n. 4
0
    def yum_config(self, distro_tree_id, *args, **kwargs):
        # Ignore positional args, so that we can make nice URLs like
        # /distrotrees/yum_config/12345/RHEL-6.2-Server-i386.repo
        try:
            distro_tree = DistroTree.by_id(int(distro_tree_id))
        except (ValueError, NoResultFound):
            raise cherrypy.NotFound(distro_tree_id)
        if not kwargs.get('lab'):
            lc = distro_tree.lab_controller_assocs[0].lab_controller
        else:
            try:
                lc = LabController.by_name(kwargs['lab'])
            except NoResultFound:
                raise cherrypy.HTTPError(status=400,
                                         message='No such lab controller %r' %
                                         kwargs['lab'])
        base = distro_tree.url_in_lab(lc, scheme='http')
        if not base:
            raise cherrypy.HTTPError(status=404,
                                     message='%s is not present in lab %s' %
                                     (distro_tree, lc))
        if not distro_tree.repos:
            return '# No repos for %s' % distro_tree
        sections = []
        for repo in distro_tree.repos:
            sections.append('''[%s]
name=%s
baseurl=%s
enabled=1
gpgcheck=0
''' % (repo.repo_id, repo.repo_id, urlparse.urljoin(base, repo.path)))
        return '\n'.join(sections)
Esempio n. 5
0
def doit():
    distro_trees = []
    for id in request.form.getlist('distro_tree_id'):
        try:
            distro_trees.append(DistroTree.by_id(id))
        except NoResultFound:
            raise BadRequest400('Distro tree %r does not exist' % id)
    job_details = {}
    job_details['pick'] = request.form.get('pick') or 'auto'
    if job_details['pick'] == 'fqdn':
        try:
            job_details['system'] = System.by_fqdn(request.form.get('system'),
                                                   identity.current.user)
        except NoResultFound:
            raise BadRequest400('System %s not found' %
                                request.form.get('system'))
    elif job_details['pick'] == 'lab':
        try:
            job_details['lab'] = LabController.by_name(request.form.get('lab'))
        except NoResultFound:
            raise BadRequest400('Lab controller %s not found' %
                                request.form.get('lab'))
    days = int(request.form.get('reserve_days') or DEFAULT_RESERVE_DAYS)
    days = min(days, MAX_DAYS_PROVISION)
    job_details['reservetime'] = days * 24 * 60 * 60
    job_details['whiteboard'] = request.form.get('whiteboard')
    job_details['ks_meta'] = request.form.get('ks_meta')
    job_details['koptions'] = request.form.get('koptions')
    job_details['koptions_post'] = request.form.get('koptions_post')
    with convert_internal_errors():
        job = Job.provision_system_job(distro_trees, **job_details)
    return 'Created %s' % job.t_id, 201, [('Location',
                                           url('/jobs/%s' % job.id))]
Esempio n. 6
0
 def _check_lc_leaks(self):
     with session.begin():
         lc = LabController.by_name(lc_fqdn)
         # check for outstanding watchdogs
         watchdogs = Watchdog.query\
             .join(Watchdog.recipe).join(Recipe.recipeset)\
             .filter(RecipeSet.lab_controller == lc)
         if watchdogs.count():
             # If your test case hits this error, you need to fix it so that
             # any running recipes are cancelled otherwise beaker-watchdog
             # will eventually pick them up and abort them, interfering with
             # some later test.
             raise AssertionError('Leaked watchdogs for %s: %s' %
                                  (lc_fqdn, watchdogs.all()))
         # check for systems left associated to the LC
         systems = System.query.filter(System.lab_controller == lc)
         if systems.count():
             # If your test case hits this error, you need to fix it so that
             # any systems which were associated to the LC are
             # de-associated, otherwise subsequent tests which invoke the
             # scheduler will try to schedule recipes onto the system and
             # then beaker-provision will start trying to run the
             # provisioning commands.
             raise AssertionError('Leaked systems for %s: %s' %
                                  (lc_fqdn, systems.all()))
Esempio n. 7
0
    def yum_config(self, distro_tree_id, *args, **kwargs):
        # Ignore positional args, so that we can make nice URLs like
        # /distrotrees/yum_config/12345/RHEL-6.2-Server-i386.repo
        try:
            distro_tree = DistroTree.by_id(int(distro_tree_id))
        except (ValueError, NoResultFound):
            raise cherrypy.NotFound(distro_tree_id)
        if not kwargs.get('lab'):
            lc = distro_tree.lab_controller_assocs[0].lab_controller
        else:
            try:
                lc = LabController.by_name(kwargs['lab'])
            except NoResultFound:
                raise cherrypy.HTTPError(status=400,
                        message='No such lab controller %r' % kwargs['lab'])
        base = distro_tree.url_in_lab(lc, scheme='http')
        if not base:
            raise cherrypy.HTTPError(status=404,
                    message='%s is not present in lab %s' % (distro_tree, lc))
        if not distro_tree.repos:
            return '# No repos for %s' % distro_tree
        sections = []
        for repo in distro_tree.repos:
            sections.append('''[%s]
name=%s
baseurl=%s
enabled=1
gpgcheck=0
''' % (repo.repo_id, repo.repo_id, urlparse.urljoin(base, repo.path)))
        return '\n'.join(sections)
Esempio n. 8
0
def doit():
    distro_trees = []
    for id in request.form.getlist('distro_tree_id'):
        try:
            distro_trees.append(DistroTree.by_id(id))
        except NoResultFound:
            raise BadRequest400('Distro tree %r does not exist' % id)
    job_details = {}
    job_details['pick'] = request.form.get('pick') or 'auto'
    if job_details['pick'] == 'fqdn':
        try:
            job_details['system'] = System.by_fqdn(request.form.get('system'),
                    identity.current.user)
        except NoResultFound:
            raise BadRequest400('System %s not found' % request.form.get('system'))
    elif job_details['pick'] == 'lab':
        try:
            job_details['lab'] = LabController.by_name(request.form.get('lab'))
        except NoResultFound:
            raise BadRequest400('Lab controller %s not found' % request.form.get('lab'))
    days = int(request.form.get('reserve_days') or DEFAULT_RESERVE_DAYS)
    days = min(days, MAX_DAYS_PROVISION)
    job_details['reservetime'] = days * 24 * 60 * 60
    job_details['whiteboard'] = request.form.get('whiteboard')
    job_details['ks_meta'] = request.form.get('ks_meta')
    job_details['koptions'] = request.form.get('koptions')
    job_details['koptions_post'] = request.form.get('koptions_post')
    with convert_internal_errors():
        job = Job.provision_system_job(distro_trees, **job_details)
    return 'Created %s' % job.t_id, 201, [('Location', absolute_url('/jobs/%s' % job.id))]
Esempio n. 9
0
def find_labcontroller_or_raise404(fqdn):
    """Returns a lab controller object or raises a NotFound404 error if the lab
    controller does not exist in the database."""
    try:
        labcontroller = LabController.by_name(fqdn)
    except NoResultFound:
        raise NotFound404('Lab controller %s does not exist' % fqdn)
    return labcontroller
Esempio n. 10
0
def find_labcontroller_or_raise404(fqdn):
    """Returns a lab controller object or raises a NotFound404 error if the lab
    controller does not exist in the database."""
    try:
        labcontroller = LabController.by_name(fqdn)
    except NoResultFound:
        raise NotFound404('Lab controller %s does not exist' % fqdn)
    return labcontroller
Esempio n. 11
0
def create_labcontroller(fqdn=None, user=None):
    if fqdn is None:
        fqdn = unique_name(u'lab%s.testdata.invalid')
    try:
        lc = LabController.by_name(fqdn)  
    except NoResultFound:
        if user is None:
            user = User(user_name='host/%s' % fqdn)
        lc = LabController(fqdn=fqdn)
        lc.user = user
        user.groups.append(Group.by_name(u'lab_controller'))
        return lc
    log.debug('labcontroller %s already exists' % fqdn)
    return lc
Esempio n. 12
0
def doit():
    distro_trees = []
    for id in request.form.getlist('distro_tree_id'):
        try:
            distro_trees.append(DistroTree.by_id(id))
        except NoResultFound:
            raise BadRequest400('Distro tree %r does not exist' % id)
    job_details = {}
    job_details['pick'] = request.form.get('pick') or 'auto'
    system_choice = 'any system'
    if job_details['pick'] == 'fqdn':
        try:
            job_details['system'] = System.by_fqdn(request.form.get('system'),
                                                   identity.current.user)
            system_choice = 'a specific system'
        except DatabaseLookupError:
            raise BadRequest400('System %s not found' %
                                request.form.get('system'))
    elif job_details['pick'] == 'lab':
        try:
            job_details['lab'] = LabController.by_name(request.form.get('lab'))
            system_choice = 'any lab system'
        except NoResultFound:
            raise BadRequest400('Lab controller %s not found' %
                                request.form.get('lab'))
    reservetime = int(
        request.form.get('reserve_duration') or DEFAULT_RESERVE_SECONDS)
    if reservetime > MAX_SECONDS_PROVISION:
        raise BadRequest400(
            'Reservation time exceeds maximum time of %s hours' %
            MAX_HOURS_PROVISION)
    job_details['reservetime'] = reservetime
    job_details['whiteboard'] = request.form.get('whiteboard')
    if not job_details['whiteboard']:
        job_details['whiteboard'] = (
            "Reserve Workflow provision of distro %s on %s for %d seconds" %
            (request.form.get('distro'), system_choice,
             job_details['reservetime']))

    job_details['ks_meta'] = request.form.get('ks_meta')
    job_details['koptions'] = request.form.get('koptions')
    job_details['koptions_post'] = request.form.get('koptions_post')
    with convert_internal_errors():
        job = Job.provision_system_job(distro_trees, **job_details)
    return 'Created %s' % job.t_id, 201, [('Location',
                                           absolute_url('/jobs/%s' % job.id))]
Esempio n. 13
0
    def test_lab_controller_remove(self):
        b = self.browser
        lc_name = data_setup.unique_name('lc%s.com')
        lc_email = data_setup.unique_name('me@my%s.com')
        self._add_lc(b, lc_name, lc_email, data_setup.ADMIN_USER)
        with session.begin():
            sys = data_setup.create_system()
            sys.lab_controller = LabController.by_name(lc_name)
        b.get(get_server_base() + 'labcontrollers')
        b.find_element_by_xpath("//table[@id='widget']/tbody/tr/"
            "td[preceding-sibling::td/a[normalize-space(text())='%s']]"
            "/a[normalize-space(text())='Remove (-)']" % lc_name).click()
        self.assert_('%s removed' % lc_name in
            b.find_element_by_css_selector('.flash').text)

        # Search in  LC activity
        b.get(get_server_base() + 'activity/labcontroller')
        b.find_element_by_id('advancedsearch').click()
        b.find_element_by_xpath("//select[@id='activitysearch_0_table']/"
            "option[@value='LabController/Name']").click()
        b.find_element_by_xpath("//select[@id='activitysearch_0_operation']/"
            "option[@value='is']").click()
        b.find_element_by_xpath("//input[@id='activitysearch_0_value']"). \
            send_keys(lc_name)
        b.find_element_by_xpath("//input[@name='Search']").click()
        self.assert_(is_activity_row_present(b,
            object_='LabController: %s' % lc_name, via='WEBUI',
            property_='Disabled', action='Changed', new_value='True'))
        self.assert_(is_activity_row_present(b,
            object_='LabController: %s' % lc_name, via='WEBUI',
            property_='Removed', action='Changed', new_value='True'))

        # Ensure System Actvity has been updated to note removal of LC
        b.get(get_server_base() + 'activity/system')
        b.find_element_by_id('advancedsearch').click()
        b.find_element_by_xpath("//select[@id='activitysearch_0_table']/"
            "option[@value='System/Name']").click()
        b.find_element_by_xpath("//select[@id='activitysearch_0_operation']/"
            "option[@value='is']").click()
        b.find_element_by_xpath("//input[@id='activitysearch_0_value']"). \
            send_keys(sys.fqdn)
        b.find_element_by_xpath("//input[@name='Search']").click()
        self.assert_(is_activity_row_present(b,
            object_='System: %s' % sys.fqdn, via='WEBUI',
            property_='lab_controller', action='Changed', new_value=''))
Esempio n. 14
0
    def test_lab_controller_add(self):
        b = self.browser
        lc_name = data_setup.unique_name("lc%s.com")
        lc_email = data_setup.unique_name("me@my%s.com")
        self._add_lc(lc_name, lc_email)
        self.assert_("%s saved" % lc_name in b.find_element_by_css_selector(".flash").text)

        # check activity
        with session.begin():
            lc = LabController.by_name(lc_name)
            self.assertEquals(lc.activity[0].field_name, u"Disabled")
            self.assertEquals(lc.activity[0].action, u"Changed")
            self.assertEquals(lc.activity[0].new_value, u"False")
            self.assertEquals(lc.activity[1].field_name, u"User")
            self.assertEquals(lc.activity[1].action, u"Changed")
            self.assertEquals(lc.activity[1].new_value, u"host/" + lc_name)
            self.assertEquals(lc.activity[2].field_name, u"FQDN")
            self.assertEquals(lc.activity[2].action, u"Changed")
            self.assertEquals(lc.activity[2].new_value, lc_name)
Esempio n. 15
0
def create_labcontroller(fqdn=None, user=None):
    if fqdn is None:
        fqdn = unique_name(u'lab%s.testdata.invalid')
    try:
        lc = LabController.by_name(fqdn)
    except NoResultFound:
        if user is None:
            user = User(user_name=u'host/%s' % fqdn,
                        email_address=u'root@%s' % fqdn)
        lc = LabController(fqdn=fqdn)
        lc.user = user
        session.add(lc)
        user.groups.append(Group.by_name(u'lab_controller'))
        # Need to ensure it is inserted now, since we aren't using lazy_create
        # here so a subsequent call to create_labcontroller could try and
        # create the same LC again.
        session.flush()
        return lc
    log.debug('labcontroller %s already exists' % fqdn)
    return lc
Esempio n. 16
0
    def test_lab_controller_add(self):
        b = self.browser
        lc_name = data_setup.unique_name('lc%s.com')
        lc_email = data_setup.unique_name('me@my%s.com')
        self._add_lc(lc_name, lc_email)
        self.assert_('%s saved' %
                     lc_name in b.find_element_by_css_selector('.flash').text)

        # check activity
        with session.begin():
            lc = LabController.by_name(lc_name)
            self.assertEquals(lc.activity[0].field_name, u'Disabled')
            self.assertEquals(lc.activity[0].action, u'Changed')
            self.assertEquals(lc.activity[0].new_value, u'False')
            self.assertEquals(lc.activity[1].field_name, u'User')
            self.assertEquals(lc.activity[1].action, u'Changed')
            self.assertEquals(lc.activity[1].new_value, u'host/' + lc_name)
            self.assertEquals(lc.activity[2].field_name, u'FQDN')
            self.assertEquals(lc.activity[2].action, u'Changed')
            self.assertEquals(lc.activity[2].new_value, lc_name)
Esempio n. 17
0
def create_labcontroller(fqdn=None, user=None):
    if fqdn is None:
        fqdn = unique_name(u'lab%s.testdata.invalid')
    try:
        lc = LabController.by_name(fqdn)  
    except NoResultFound:
        if user is None:
            user = User(user_name=u'host/%s' % fqdn,
                    email_address=u'root@%s' % fqdn)
        lc = LabController(fqdn=fqdn)
        lc.user = user
        session.add(lc)
        user.groups.append(Group.by_name(u'lab_controller'))
        # Need to ensure it is inserted now, since we aren't using lazy_create 
        # here so a subsequent call to create_labcontroller could try and 
        # create the same LC again.
        session.flush()
        return lc
    log.debug('labcontroller %s already exists' % fqdn)
    return lc
Esempio 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)
 def test_lab_controller_create(self):
     fqdn = data_setup.unique_name(u'mylab%s')
     run_client(['bkr', 'labcontroller-create',
                       '--fqdn', fqdn,
                       '--user', 'host/%s' % fqdn,
                       '--email', 'lab1@%s.com' % fqdn])
     with session.begin():
         lc = LabController.by_name(fqdn)
         self.assertEqual(lc.user.user_name, 'host/%s' % fqdn)
         self.assertEqual(lc.user.email_address, 'lab1@%s.com' % fqdn)
         self.assertIn(Group.by_name(u'lab_controller'), lc.user.groups)
     # cann't create duplicate lab controller 
     try:
         run_client(['bkr', 'labcontroller-create',
                           '--fqdn', fqdn,
                           '--user', 'host/%s' % fqdn,
                           '--email', 'lab1@%s.com' % fqdn])
         self.fail('Must fail')
     except ClientError as e:
         self.assertIn("Lab Controller %s already exists" % fqdn,
                       e.stderr_output)
Esempio n. 20
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)
Esempio n. 21
0
    def watchdogs(self, status='active',lc=None):
        """ Return all active/expired tasks for this lab controller
            The lab controllers login with host/fqdn
        """
        # TODO work on logic that determines whether or not originator
        # was qpid or kobo ?
        if lc is None:
            try:
                labcontroller = identity.current.user.lab_controller
            except AttributeError:
                raise BX(_('No lab controller passed in and not currently logged in'))

            if not labcontroller:
                raise BX(_(u'Invalid login: %s, must log in as a lab controller' % identity.current.user))
        else:
            try:
                labcontroller = LabController.by_name(lc)
            except InvalidRequestError:
                raise BX(_(u'Invalid lab controller: %s' % lc))

        return [dict(recipe_id = w.recipe.id,
                        system = w.recipe.resource.fqdn) for w in Watchdog.by_status(labcontroller, status)]
Esempio n. 22
0
 def test_lab_controller_create(self):
     fqdn = data_setup.unique_name(u'mylab%s')
     run_client([
         'bkr', 'labcontroller-create', '--fqdn', fqdn, '--user',
         'host/%s' % fqdn, '--email',
         'lab1@%s.com' % fqdn
     ])
     with session.begin():
         lc = LabController.by_name(fqdn)
         self.assertEqual(lc.user.user_name, 'host/%s' % fqdn)
         self.assertEqual(lc.user.email_address, 'lab1@%s.com' % fqdn)
         self.assertIn(Group.by_name(u'lab_controller'), lc.user.groups)
     # cann't create duplicate lab controller
     try:
         run_client([
             'bkr', 'labcontroller-create', '--fqdn', fqdn, '--user',
             'host/%s' % fqdn, '--email',
             'lab1@%s.com' % fqdn
         ])
         self.fail('Must fail')
     except ClientError as e:
         self.assertIn("Lab Controller %s already exists" % fqdn,
                       e.stderr_output)
Esempio n. 23
0
 def test_lookup_secret_fqdn(self):
     with session.begin():
         system = data_setup.create_system(private=True)
     lab_controller_user = LabController.by_name(self.lc_fqdn).user
     system2 = System.by_fqdn(str(system.fqdn), user=lab_controller_user)
     self.assertEquals(system, system2)
Esempio n. 24
0
    def _from_csv(cls, system, data, csv_type, log):
        """
        Import data from CSV file into System Objects
        """
        for key in data.keys():
            if key in cls.reg_keys and key != 'id':
                if data[key]:
                    newdata = smart_bool(data[key])
                else:
                    newdata = None
                current_data = getattr(system, key, None)
                if unicode(newdata) != unicode(current_data):
                    setattr(system, key, newdata)
                    system.record_activity(user=identity.current.user,
                                           service=u'CSV',
                                           action=u'Changed',
                                           field=key,
                                           old=u'%s' % current_data,
                                           new=u'%s' % newdata)
        # import arch
        if 'arch' in data:
            arch_objs = []
            if data['arch']:
                arches = data['arch'].split(',')
                for arch in arches:
                    try:
                        arch_obj = Arch.by_name(arch)
                    except ValueError:
                        raise ValueError("%s: Invalid arch %s" %
                                         (system.fqdn, arch))
                    arch_objs.append(arch_obj)
            if system.arch != arch_objs:
                system.record_activity(user=identity.current.user,
                                       service=u'CSV',
                                       action=u'Changed',
                                       field=u'arch',
                                       old=u'%s' % system.arch,
                                       new=u'%s' % arch_objs)
                system.arch = arch_objs

        # import cc
        if 'cc' in data:
            cc_objs = []
            if data['cc']:
                cc_objs = data['cc'].split(',')
            if system.cc != cc_objs:
                system.record_activity(user=identity.current.user,
                                       service=u'CSV',
                                       action=u'Changed',
                                       field=u'cc',
                                       old=u'%s' % system.cc,
                                       new=u'%s' % cc_objs)
                system.cc = cc_objs

        # import labController
        if 'lab_controller' in data:
            if data['lab_controller']:
                try:
                    lab_controller = LabController.by_name(
                        data['lab_controller'])
                except InvalidRequestError:
                    raise ValueError("%s: Invalid lab controller %s" %
                                     (system.fqdn, data['lab_controller']))
            else:
                lab_controller = None
            if system.lab_controller != lab_controller:
                system.record_activity(user=identity.current.user,
                                       service=u'CSV',
                                       action=u'Changed',
                                       field=u'lab_controller',
                                       old=u'%s' % system.lab_controller,
                                       new=u'%s' % lab_controller)
                system.lab_controller = lab_controller

        # import owner
        if 'owner' in data:
            if data['owner']:
                owner = User.by_user_name(data['owner'])
                if not owner:
                    raise ValueError("%s: Invalid User %s" %
                                     (system.fqdn, data['owner']))
                if owner.removed:
                    raise ValueError('%s: user %s is deleted' %
                                     (system.fqdn, owner.user_name))
            else:
                owner = None
            if system.owner != owner:
                system.record_activity(user=identity.current.user,
                                       service=u'CSV',
                                       action=u'Changed',
                                       field=u'owner',
                                       old=u'%s' % system.owner,
                                       new=u'%s' % owner)
                system.owner = owner
        # import status
        if 'status' in data and data['status']:
            try:
                systemstatus = SystemStatus.from_string(data['status'])
            except ValueError:
                raise ValueError("%s: Invalid Status %s" %
                                 (system.fqdn, data['status']))
            if system.status != systemstatus:
                system.record_activity(user=identity.current.user,
                                       service=u'CSV',
                                       action=u'Changed',
                                       field=u'status',
                                       old=u'%s' % system.status,
                                       new=u'%s' % systemstatus)
                system.status = systemstatus

        # import type
        if 'type' in data:
            if not data['type']:
                raise ValueError("%s: Invalid Type None" % system.fqdn)
            try:
                systemtype = SystemType.from_string(data['type'])
            except ValueError:
                raise ValueError("%s: Invalid Type %s" %
                                 (system.fqdn, data['type']))
            if system.type != systemtype:
                system.record_activity(user=identity.current.user,
                                       service=u'CSV',
                                       action=u'Changed',
                                       field=u'type',
                                       old=u'%s' % system.type,
                                       new=u'%s' % systemtype)
                system.type = systemtype
        # import secret
        if 'secret' in data:
            # 'private' used to be a field on system (called 'secret' in the UI
            # and CSV). The field is replaced by the 'view' permission in the
            # access policy so CSV export no longer produces 'secret' in its
            # output. However we still accept it on import for compatibility.
            # It is mapped to the 'view everybody' rule in the access policy.
            if not data['secret']:
                raise ValueError("%s: Invalid secret None" % system.fqdn)
            secret = smart_bool(data['secret'])
            view_everybody = system.custom_access_policy.grants_everybody(
                SystemPermission.view)
            if secret and view_everybody:
                # remove 'view everybody' rule
                for rule in system.custom_access_policy.rules:
                    if rule.permission == SystemPermission.view and rule.everybody:
                        system.record_activity(user=identity.current.user,
                                               service=u'HTTP',
                                               field=u'Access Policy Rule',
                                               action=u'Removed',
                                               old=repr(rule))
                        session.delete(rule)
            if not secret and not view_everybody:
                # add rule granting 'view everybody'
                new_rule = system.custom_access_policy.add_rule(
                    everybody=True, permission=SystemPermission.view)
                system.record_activity(user=identity.current.user,
                                       service=u'HTTP',
                                       field=u'Access Policy Rule',
                                       action=u'Added',
                                       new=repr(new_rule))
Esempio n. 25
0
    def _from_csv(cls,system,data,csv_type,log):
        """
        Import data from CSV file into System Objects
        """
        for key in data.keys():
            if key in cls.reg_keys and key != 'id':
                if data[key]:
                    newdata = smart_bool(data[key])
                else:
                    newdata = None
                current_data = getattr(system, key, None)
                if unicode(newdata) != unicode(current_data):
                    setattr(system,key,newdata)
                    system.record_activity(user=identity.current.user,
                            service=u'CSV', action=u'Changed', field=key,
                            old=u'%s' % current_data, new=u'%s' % newdata)
        # import arch
        if 'arch' in data:
            arch_objs = []
            if data['arch']:
                arches = data['arch'].split(',')
                for arch in arches:
                    try:
                        arch_obj = Arch.by_name(arch)
                    except ValueError:
                        raise ValueError("%s: Invalid arch %s" %
                                         (system.fqdn, arch))
                    arch_objs.append(arch_obj)
            if system.arch != arch_objs:
                system.record_activity(user=identity.current.user,
                        service=u'CSV', action=u'Changed', field=u'arch',
                        old=u'%s' % system.arch, new=u'%s' % arch_objs)
                system.arch = arch_objs

        # import cc
        if 'cc' in data:
            cc_objs = []
            if data['cc']:
                cc_objs = data['cc'].split(',')
            if system.cc != cc_objs:
                system.record_activity(user=identity.current.user,
                        service=u'CSV', action=u'Changed', field=u'cc',
                        old=u'%s' % system.cc, new=u'%s' % cc_objs)
                system.cc = cc_objs

        # import labController
        if 'lab_controller' in data:
            if data['lab_controller']:
                try:
                    lab_controller = LabController.by_name(data['lab_controller'])
                except InvalidRequestError:
                    raise ValueError("%s: Invalid lab controller %s" %
                                     (system.fqdn, data['lab_controller']))
            else:
                lab_controller = None
            if system.lab_controller != lab_controller:
                system.record_activity(user=identity.current.user,
                        service=u'CSV', action=u'Changed', field=u'lab_controller',
                        old=u'%s' % system.lab_controller, new=u'%s' % lab_controller)
                system.lab_controller = lab_controller

        # import owner
        if 'owner' in data:
            if data['owner']:
                owner = User.by_user_name(data['owner'])
                if not owner:
                    raise ValueError("%s: Invalid User %s" %
                                              (system.fqdn, data['owner']))
            else:
                owner = None
            if system.owner != owner:
                system.record_activity(user=identity.current.user,
                        service=u'CSV', action=u'Changed', field=u'owner',
                        old=u'%s' % system.owner, new=u'%s' % owner)
                system.owner = owner
        # import status
        if 'status' in data and data['status']:
            try:
                systemstatus = SystemStatus.from_string(data['status'])
            except ValueError:
                raise ValueError("%s: Invalid Status %s" %
                                 (system.fqdn, data['status']))
            if system.status != systemstatus:
                system.record_activity(user=identity.current.user,
                        service=u'CSV', action=u'Changed', field=u'status',
                        old=u'%s' % system.status, new=u'%s' % systemstatus)
                system.status = systemstatus

        # import type
        if 'type' in data:
            if not data['type']:
                raise ValueError("%s: Invalid Type None" % system.fqdn)
            try:
                systemtype = SystemType.from_string(data['type'])
            except ValueError:
                raise ValueError("%s: Invalid Type %s" %
                                 (system.fqdn, data['type']))
            if system.type != systemtype:
                system.record_activity(user=identity.current.user,
                        service=u'CSV', action=u'Changed', field=u'type',
                        old=u'%s' % system.type, new=u'%s' % systemtype)
                system.type = systemtype
        # import secret
        if 'secret' in data:
            # 'private' used to be a field on system (called 'secret' in the UI 
            # and CSV). The field is replaced by the 'view' permission in the 
            # access policy so CSV export no longer produces 'secret' in its 
            # output. However we still accept it on import for compatibility. 
            # It is mapped to the 'view everybody' rule in the access policy.
            if not data['secret']:
                raise ValueError("%s: Invalid secret None" % system.fqdn)
            secret = smart_bool(data['secret'])
            view_everybody = system.custom_access_policy.grants_everybody(
                    SystemPermission.view)
            if secret and view_everybody:
                # remove 'view everybody' rule
                for rule in system.custom_access_policy.rules:
                    if rule.permission == SystemPermission.view and rule.everybody:
                        system.record_activity(user=identity.current.user, service=u'HTTP',
                                field=u'Access Policy Rule', action=u'Removed',
                                old=repr(rule))
                        session.delete(rule)
            if not secret and not view_everybody:
                # add rule granting 'view everybody'
                new_rule = system.custom_access_policy.add_rule(everybody=True,
                        permission=SystemPermission.view)
                system.record_activity(user=identity.current.user, service=u'HTTP',
                        field=u'Access Policy Rule', action=u'Added',
                        new=repr(new_rule))
Esempio n. 26
0
def update_labcontroller(fqdn):
    """
    Updates attributes of the lab controller identified by it's FQDN. The
    request body must be a json object or only the FQDN if
    that is the only value to be updated.

    :param string fqdn: Lab controller's new fully-qualified domain name.
    :jsonparam string user_name: User name associated with the lab controller.
    :jsonparam string email_address: Email of the user account associated with the lab controller.
    :jsonparam string password: Optional password for the user account used to login.
    :jsonparam string removed: If True, detaches all systems, cancels all
        running recipes and removes associated distro trees. If False, restores
        the lab controller.
    :jsonparam bool disabled: Whether the lab controller should be disabled. New
        recipes are not scheduled on a lab controller while it is disabled.
    :status 200: LabController updated.
    :status 400: Invalid data was given.
    """
    labcontroller = find_labcontroller_or_raise404(fqdn)
    if not labcontroller.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit lab controller')
    data = read_json_request(request)
    with convert_internal_errors():
        # should the lab controller be removed?
        if data.get('removed', False) and not labcontroller.removed:
            remove_labcontroller(labcontroller)

        # should the controller be restored?
        if data.get('removed') is False and labcontroller.removed:
            restore_labcontroller(labcontroller)
        fqdn_changed = False
        new_fqdn = data.get('fqdn', fqdn)
        if labcontroller.fqdn != new_fqdn:
            lc = None
            try:
                lc = LabController.by_name(new_fqdn)
            except NoResultFound:
                pass
            if lc is not None:
                raise BadRequest400('FQDN %s already in use' % new_fqdn)

            labcontroller.record_activity(user=identity.current.user,
                                          service=u'HTTP',
                                          field=u'fqdn',
                                          action=u'Changed',
                                          old=labcontroller.fqdn,
                                          new=new_fqdn)
            labcontroller.fqdn = new_fqdn
            labcontroller.user.display_name = new_fqdn
            fqdn_changed = True
        if 'user_name' in data:
            user = find_user_or_create(data['user_name'])
            if labcontroller.user != user:
                user = update_user(user,
                                   display_name=new_fqdn,
                                   email_address=data.get(
                                       'email_address', user.email_address),
                                   password=data.get('password',
                                                     user.password))
                labcontroller.record_activity(user=identity.current.user,
                                              service=u'HTTP',
                                              field=u'User',
                                              action=u'Changed',
                                              old=labcontroller.user.user_name,
                                              new=user.user_name)
                labcontroller.user = user
        if 'email_address' in data:
            new_email_address = data.get('email_address')
            if labcontroller.user.email_address != new_email_address:
                labcontroller.user.email_address = new_email_address
        if data.get('password') is not None:
            labcontroller.user.password = data.get('password')
        if labcontroller.disabled != data.get('disabled',
                                              labcontroller.disabled):
            labcontroller.record_activity(user=identity.current.user,
                                          service=u'HTTP',
                                          field=u'disabled',
                                          action=u'Changed',
                                          old=unicode(labcontroller.disabled),
                                          new=data['disabled'])
            labcontroller.disabled = data['disabled']

    response = jsonify(labcontroller.__json__())
    if fqdn_changed:
        response.headers.add('Location', absolute_url(labcontroller.href))
    return response
Esempio n. 27
0
 def get_lc(self):
     return LabController.by_name(self.get_lc_fqdn())
Esempio n. 28
0
def update_labcontroller(fqdn):
    """
    Updates attributes of the lab controller identified by it's FQDN. The
    request body must be a json object or only the FQDN if
    that is the only value to be updated.

    :param string fqdn: Lab controller's new fully-qualified domain name.
    :jsonparam string user_name: User name associated with the lab controller.
    :jsonparam string email_address: Email of the user account associated with the lab controller.
    :jsonparam string password: Optional password for the user account used to login.
    :jsonparam string removed: If True, detaches all systems, cancels all
        running recipes and removes associated distro trees. If False, restores
        the lab controller.
    :jsonparam bool disabled: Whether the lab controller should be disabled. New
        recipes are not scheduled on a lab controller while it is disabled.
    :status 200: LabController updated.
    :status 400: Invalid data was given.
    """
    labcontroller = find_labcontroller_or_raise404(fqdn)
    if not labcontroller.can_edit(identity.current.user):
        raise Forbidden403('Cannot edit lab controller')
    data = read_json_request(request)
    with convert_internal_errors():
        # should the lab controller be removed?
        if data.get('removed', False) and not labcontroller.removed:
            remove_labcontroller(labcontroller)

        # should the controller be restored?
        if data.get('removed') is False and labcontroller.removed:
            restore_labcontroller(labcontroller)
        fqdn_changed = False
        new_fqdn = data.get('fqdn', fqdn)
        if labcontroller.fqdn != new_fqdn:
            lc = None
            try:
                lc = LabController.by_name(new_fqdn)
            except NoResultFound:
                pass
            if lc is not None:
                raise BadRequest400('FQDN %s already in use' % new_fqdn)

            labcontroller.record_activity(
                user=identity.current.user, service=u'HTTP',
                field=u'fqdn', action=u'Changed', old=labcontroller.fqdn, new=new_fqdn)
            labcontroller.fqdn = new_fqdn
            labcontroller.user.display_name = new_fqdn
            fqdn_changed = True
        if 'user_name' in data:
            user = find_user_or_create(data['user_name'])
            if labcontroller.user != user:
                user = update_user(
                    user,
                    display_name=new_fqdn,
                    email_address=data.get('email_address', user.email_address),
                    password=data.get('password', user.password)
                )
                labcontroller.record_activity(
                    user=identity.current.user, service=u'HTTP',
                    field=u'User', action=u'Changed',
                    old=labcontroller.user.user_name, new=user.user_name)
                labcontroller.user = user
        if 'email_address' in data:
            new_email_address = data.get('email_address')
            if labcontroller.user.email_address != new_email_address:
                labcontroller.user.email_address = new_email_address
        if data.get('password') is not None:
            labcontroller.user.password = data.get('password')
        if labcontroller.disabled != data.get('disabled', labcontroller.disabled):
            labcontroller.record_activity(
                user=identity.current.user, service=u'HTTP',
                field=u'disabled', action=u'Changed',
                old=unicode(labcontroller.disabled), new=data['disabled'])
            labcontroller.disabled = data['disabled']

    response = jsonify(labcontroller.__json__())
    if fqdn_changed:
        response.headers.add('Location', absolute_url(labcontroller.href))
    return response
Esempio n. 29
0
 def get_lc():
     return LabController.by_name(lc_fqdn)
Esempio n. 30
0
 def get_lc():
     return LabController.by_name(lc_fqdn)