예제 #1
0
파일: releases.py 프로젝트: yarda/bodhi
def get_release_json(request):
    id = request.matchdict.get('name')
    release = Release.get(id, request.db)
    if not release:
        request.errors.add('body', 'name', 'No such release')
        request.errors.status = HTTPNotFound.code
    return release
예제 #2
0
    def test_create_duplicate_override(self, publish):
        release = Release.get(u"F17", self.db)
        package = Package(name=u"not-bodhi")
        self.db.add(package)
        build = Build(nvr=u"not-bodhi-2.0-2.fc17", package=package, release=release)
        self.db.add(build)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        data = {
            "nvr": build.nvr,
            "notes": u"blah blah blah",
            "expiration_date": expiration_date,
            "csrf_token": self.get_csrf_token(),
        }
        res = self.app.post("/overrides/", data)

        publish.assert_called_once_with(topic="buildroot_override.tag", msg=mock.ANY)
        self.assertEquals(len(publish.call_args_list), 1)

        o = res.json_body
        self.assertEquals(o["build_id"], build.id)
        self.assertEquals(o["notes"], "blah blah blah")
        self.assertEquals(o["expiration_date"], expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o["expired_date"], None)

        # Submit it again
        res = self.app.post("/overrides/", data, status=400)
        self.assertEquals(
            res.json_body["errors"][0]["description"], "Buildroot override for %s already exists" % build.nvr
        )
예제 #3
0
파일: masher.py 프로젝트: pcreech/bodhi
    def _determine_tag_actions(self):
        tag_types, tag_rels = Release.get_tags(self.db)
        for update in sorted_updates(self.updates):
            add_tags = []
            move_tags = []

            if update.status is UpdateStatus.testing:
                status = 'testing'
            else:
                status = 'candidate'

            for build in update.builds:
                from_tag = None
                tags = build.get_tags()
                for tag in tags:
                    if tag in tag_types[status]:
                        from_tag = tag
                        break
                else:
                    reason = 'Cannot find relevant tag for %s: %s' % (
                        build.nvr, tags)
                    self.eject_from_mash(update, reason)
                    break

                if self.skip_mash:
                    add_tags.append((update.requested_tag, build.nvr))
                else:
                    move_tags.append(
                        (from_tag, update.requested_tag, build.nvr))
            else:
                self.add_tags.extend(add_tags)
                self.move_tags.extend(move_tags)
예제 #4
0
    def test_cannot_edit_override_build(self, publish):
        release = Release.get(u'F17', self.db)

        old_nvr = u'bodhi-2.0-1.fc17'

        res = self.app.get('/overrides/%s' % old_nvr)
        o = res.json_body['override']
        expiration_date = o['expiration_date']
        old_build_id = o['build_id']

        build = Build(nvr=u'bodhi-2.0-2.fc17', release=release)
        self.db.add(build)
        self.db.flush()

        o.update({
            'nvr': build.nvr,
            'edited': old_nvr,
            'csrf_token': self.get_csrf_token(),
        })
        res = self.app.post('/overrides/', o)

        override = res.json_body
        self.assertEquals(override['build_id'], old_build_id)
        self.assertEquals(override['notes'], 'blah blah blah')
        self.assertEquals(override['expiration_date'], expiration_date)
        self.assertEquals(override['expired_date'], None)
        self.assertEquals(len(publish.call_args_list), 0)
예제 #5
0
    def test_create_override(self, publish):
        session = DBSession()

        release = Release.get(u'F17', session)

        package = Package(name=u'not-bodhi')
        session.add(package)
        build = Build(nvr=u'not-bodhi-2.0-2.fc17', package=package,
                      release=release)
        session.add(build)
        session.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        data = {'nvr': build.nvr, 'notes': u'blah blah blah',
                'expiration_date': expiration_date,
                'csrf_token': self.get_csrf_token()}
        res = self.app.post('/overrides/', data)

        publish.assert_called_once_with(
            topic='buildroot_override.tag', msg=mock.ANY)
        self.assertEquals(len(publish.call_args_list), 1)

        o = res.json_body
        self.assertEquals(o['build_id'], build.id)
        self.assertEquals(o['notes'], 'blah blah blah')
        self.assertEquals(o['expiration_date'],
                          expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o['expired_date'], None)
예제 #6
0
    def test_create_override(self, publish):
        release = Release.get(u'F17', self.db)

        package = Package(name=u'not-bodhi')
        self.db.add(package)
        build = Build(nvr=u'not-bodhi-2.0-2.fc17',
                      package=package,
                      release=release)
        self.db.add(build)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        data = {
            'nvr': build.nvr,
            'notes': u'blah blah blah',
            'expiration_date': expiration_date,
            'csrf_token': self.get_csrf_token()
        }
        res = self.app.post('/overrides/', data)

        publish.assert_called_once_with(topic='buildroot_override.tag',
                                        msg=mock.ANY)
        self.assertEquals(len(publish.call_args_list), 1)

        o = res.json_body
        self.assertEquals(o['build_id'], build.id)
        self.assertEquals(o['notes'], 'blah blah blah')
        self.assertEquals(o['expiration_date'],
                          expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o['expired_date'], None)
예제 #7
0
파일: masher.py 프로젝트: remicollet/bodhi
    def _determine_tag_actions(self):
        tag_types, tag_rels = Release.get_tags()
        for update in sorted_updates(self.updates):
            if update.status is UpdateStatus.testing:
                status = 'testing'
            else:
                status = 'candidate'

            for build in update.builds:
                from_tag = None
                tags = build.get_tags()
                for tag in tags:
                    if tag in tag_types[status]:
                        from_tag = tag
                        break
                else:
                    reason = 'Cannot find relevant tag for %s: %s' % (
                        build.nvr, tags)
                    self.eject_from_mash(update, reason)
                    break

                if self.skip_mash:
                    self.add_tags.append((update.requested_tag, build.nvr))
                else:
                    self.move_tags.append((from_tag, update.requested_tag,
                                           build.nvr))
예제 #8
0
    def test_cannot_edit_override_build(self, publish):
        session = DBSession()

        release = Release.get(u'F17', session)

        old_nvr = u'bodhi-2.0-1.fc17'

        res = self.app.get('/overrides/%s' % old_nvr)
        o = res.json_body['override']
        expiration_date = o['expiration_date']
        old_build_id = o['build_id']

        build = Build(nvr=u'bodhi-2.0-2.fc17', release=release)
        session.add(build)
        session.flush()

        o.update({
            'nvr': build.nvr,
            'edited': old_nvr,
            'csrf_token': self.get_csrf_token(),
        })
        res = self.app.post('/overrides/', o)

        override = res.json_body
        self.assertEquals(override['build_id'], old_build_id)
        self.assertEquals(override['notes'], 'blah blah blah')
        self.assertEquals(override['expiration_date'], expiration_date)
        self.assertEquals(override['expired_date'], None)
        self.assertEquals(len(publish.call_args_list), 0)
예제 #9
0
파일: masher.py 프로젝트: cgwalters/bodhi
    def _determine_tag_actions(self):
        tag_types, tag_rels = Release.get_tags(self.db)
        for update in sorted_updates(self.updates):
            add_tags = []
            move_tags = []

            if update.status is UpdateStatus.testing:
                status = "testing"
            else:
                status = "candidate"

            for build in update.builds:
                from_tag = None
                tags = build.get_tags()
                for tag in tags:
                    if tag in tag_types[status]:
                        from_tag = tag
                        break
                else:
                    reason = ("Cannot find relevant tag for %s.  " "None of %s are in %s.") % (
                        build.nvr,
                        tags,
                        tag_types[status],
                    )
                    self.eject_from_mash(update, reason)
                    break

                if self.skip_mash:
                    add_tags.append((update.requested_tag, build.nvr))
                else:
                    move_tags.append((from_tag, update.requested_tag, build.nvr))
            else:
                self.add_tags.extend(add_tags)
                self.move_tags.extend(move_tags)
예제 #10
0
    def test_security_update_priority_testing(self, publish, *args):
        with self.db_factory() as db:
            up = db.query(Update).one()
            up.type = UpdateType.security
            up.request = UpdateRequest.testing
            user = db.query(User).first()

            # Create a security update for a different release
            release = Release(
                name=u'F18', long_name=u'Fedora 18',
                id_prefix=u'FEDORA', version=u'18',
                dist_tag=u'f18', stable_tag=u'f18-updates',
                testing_tag=u'f18-updates-testing',
                candidate_tag=u'f18-updates-candidate',
                pending_testing_tag=u'f18-updates-testing-pending',
                pending_stable_tag=u'f18-updates-pending',
                override_tag=u'f18-override',
                branch=u'f18')
            db.add(release)
            build = Build(nvr=u'bodhi-2.0-1.fc18', release=release,
                          package=up.builds[0].package)
            db.add(build)
            update = Update(
                title=u'bodhi-2.0-1.fc18',
                builds=[build], user=user,
                status=UpdateStatus.testing,
                request=UpdateRequest.stable,
                notes=u'Useful details!', release=release)
            update.type = UpdateType.enhancement
            db.add(update)

            # Wipe out the tag cache so it picks up our new release
            Release._tag_cache = None

        self.msg['body']['msg']['updates'] += ['bodhi-2.0-1.fc18']

        self.masher.consume(self.msg)

        # Ensure that F17 updates-testing runs before F18
        calls = publish.mock_calls
        self.assertEquals(calls[1], mock.call(
            msg={'repo': u'f17-updates-testing',
                 'updates': [u'bodhi-2.0-1.fc17']},
            force=True,
            topic='mashtask.mashing'))
        self.assertEquals(calls[3], mock.call(
            msg={'success': True, 'repo': 'f17-updates-testing'},
            force=True,
            topic='mashtask.complete'))
        self.assertEquals(calls[4], mock.call(
            msg={'repo': u'f18-updates',
                 'updates': [u'bodhi-2.0-1.fc18']},
            force=True,
            topic='mashtask.mashing'))
        self.assertEquals(calls[-1], mock.call(
            msg={'success': True, 'repo': 'f18-updates'},
            force=True,
            topic='mashtask.complete'))
예제 #11
0
    def test_create_override_too_long(self, publish):
        release = Release.get(u'F17', self.db)

        package = Package(name=u'not-bodhi')
        self.db.add(package)
        build = Build(nvr=u'not-bodhi-2.0-2.fc17', package=package,
                      release=release)
        self.db.add(build)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=60)

        data = {'nvr': build.nvr, 'notes': u'blah blah blah',
                'expiration_date': expiration_date,
                'csrf_token': self.get_csrf_token()}
        self.app.post('/overrides/', data, status=400)
예제 #12
0
    def setUp(self):
        super(TestReleasesService, self).setUp()

        release = Release(
            name=u'F22', long_name=u'Fedora 22',
            id_prefix=u'FEDORA', version=u'22',
            dist_tag=u'f22', stable_tag=u'f22-updates',
            testing_tag=u'f22-updates-testing',
            candidate_tag=u'f22-updates-candidate',
            pending_testing_tag=u'f22-updates-testing-pending',
            pending_stable_tag=u'f22-updates-pending',
            override_tag=u'f22-override',
            branch=u'f22')

        self.db.add(release)
        self.db.flush()
예제 #13
0
    def test_create_override_multiple_nvr(self, publish):
        release = Release.get(u'F17', self.db)
        package = Package(name=u'not-bodhi')
        self.db.add(package)
        build1 = Build(nvr=u'not-bodhi-2.0-2.fc17',
                       package=package,
                       release=release)
        self.db.add(build1)
        self.db.flush()

        package = Package(name=u'another-not-bodhi')
        self.db.add(package)
        build2 = Build(nvr=u'another-not-bodhi-2.0-2.fc17',
                       package=package,
                       release=release)
        self.db.add(build2)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        data = {
            'nvr': ','.join([build1.nvr, build2.nvr]),
            'notes': u'blah blah blah',
            'expiration_date': expiration_date,
            'csrf_token': self.get_csrf_token(),
        }
        res = self.app.post('/overrides/', data)

        self.assertEquals(len(publish.call_args_list), 2)

        result = res.json_body
        self.assertEquals(result['caveats'][0]['description'],
                          'Your override submission was split into 2.')

        o1, o2 = result['overrides']
        self.assertEquals(o1['build_id'], build1.id)
        self.assertEquals(o1['notes'], 'blah blah blah')
        self.assertEquals(o1['expiration_date'],
                          expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o1['expired_date'], None)
        self.assertEquals(o2['build_id'], build2.id)
        self.assertEquals(o2['notes'], 'blah blah blah')
        self.assertEquals(o2['expiration_date'],
                          expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o2['expired_date'], None)
예제 #14
0
    def test_create_override_multiple_nvr(self, publish):
        session = DBSession()

        release = Release.get(u'F17', session)
        package = Package(name=u'not-bodhi')
        session.add(package)
        build1 = Build(nvr=u'not-bodhi-2.0-2.fc17', package=package,
                      release=release)
        session.add(build1)
        session.flush()

        package = Package(name=u'another-not-bodhi')
        session.add(package)
        build2 = Build(nvr=u'another-not-bodhi-2.0-2.fc17', package=package,
                      release=release)
        session.add(build2)
        session.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        data = {
            'nvr': ','.join([build1.nvr, build2.nvr]),
            'notes': u'blah blah blah',
            'expiration_date': expiration_date,
            'csrf_token': self.get_csrf_token(),
        }
        res = self.app.post('/overrides/', data)

        self.assertEquals(len(publish.call_args_list), 2)

        result = res.json_body
        self.assertEquals(result['caveats'][0]['description'],
                          'Your override submission was split into 2.')

        o1, o2 = result['overrides']
        self.assertEquals(o1['build_id'], build1.id)
        self.assertEquals(o1['notes'], 'blah blah blah')
        self.assertEquals(o1['expiration_date'],
                          expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o1['expired_date'], None)
        self.assertEquals(o2['build_id'], build2.id)
        self.assertEquals(o2['notes'], 'blah blah blah')
        self.assertEquals(o2['expiration_date'],
                          expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o2['expired_date'], None)
예제 #15
0
    def test_create_override_too_long(self, publish):
        release = Release.get(u"F17", self.db)

        package = Package(name=u"not-bodhi")
        self.db.add(package)
        build = Build(nvr=u"not-bodhi-2.0-2.fc17", package=package, release=release)
        self.db.add(build)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=60)

        data = {
            "nvr": build.nvr,
            "notes": u"blah blah blah",
            "expiration_date": expiration_date,
            "csrf_token": self.get_csrf_token(),
        }
        self.app.post("/overrides/", data, status=400)
예제 #16
0
    def test_list_overrides_by_releases_without_override(self):
        self.db.add(
            Release(name=u'F42',
                    long_name=u'Fedora 42',
                    id_prefix=u'FEDORA',
                    version=u'42',
                    dist_tag=u'f42',
                    stable_tag=u'f42-updates',
                    testing_tag=u'f42-updates-testing',
                    candidate_tag=u'f42-updates-candidate',
                    pending_testing_tag=u'f42-updates-testing-pending',
                    pending_stable_tag=u'f42-updates-pending',
                    override_tag=u'f42-override',
                    branch=u'f42'))
        self.db.flush()

        res = self.app.get('/overrides/', {'releases': 'F42'})

        body = res.json_body
        self.assertEquals(len(body['overrides']), 0)
예제 #17
0
    def test_create_override_too_long(self, publish):
        release = Release.get(u'F17', self.db)

        package = Package(name=u'not-bodhi')
        self.db.add(package)
        build = Build(nvr=u'not-bodhi-2.0-2.fc17',
                      package=package,
                      release=release)
        self.db.add(build)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=60)

        data = {
            'nvr': build.nvr,
            'notes': u'blah blah blah',
            'expiration_date': expiration_date,
            'csrf_token': self.get_csrf_token()
        }
        self.app.post('/overrides/', data, status=400)
예제 #18
0
    def _determine_tag_actions(self):
        tag_types, tag_rels = Release.get_tags(self.db)
        # sync & async tagging batches
        for i, batch in enumerate(sorted_updates(self.updates)):
            for update in batch:
                add_tags = []
                move_tags = []

                if update.status is UpdateStatus.testing:
                    status = 'testing'
                else:
                    status = 'candidate'

                for build in update.builds:
                    from_tag = None
                    tags = build.get_tags()
                    for tag in tags:
                        if tag in tag_types[status]:
                            from_tag = tag
                            break
                    else:
                        reason = (
                            'Cannot find relevant tag for %s.  '
                            'None of %s are in %s.') % (
                                build.nvr, tags, tag_types[status])
                        self.eject_from_mash(update, reason)
                        break

                    if self.skip_mash:
                        add_tags.append((update.requested_tag, build.nvr))
                    else:
                        move_tags.append((from_tag, update.requested_tag,
                                          build.nvr))
                else:
                    if i == 0:
                        self.add_tags_sync.extend(add_tags)
                        self.move_tags_sync.extend(move_tags)
                    else:
                        self.add_tags_async.extend(add_tags)
                        self.move_tags_async.extend(move_tags)
예제 #19
0
    def test_edit_unexisting_override(self):
        release = Release.get(u"F17", self.db)

        build = Build(nvr=u"bodhi-2.0-2.fc17", release=release)
        self.db.add(build)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        o = {
            "nvr": build.nvr,
            "notes": "blah blah blah",
            "expiration_date": expiration_date,
            "edited": build.nvr,
            "csrf_token": self.get_csrf_token(),
        }
        res = self.app.post("/overrides/", o, status=400)

        errors = res.json_body["errors"]
        self.assertEquals(len(errors), 1)
        self.assertEquals(errors[0]["name"], "edited")
        self.assertEquals(errors[0]["description"], "No buildroot override for this build")
예제 #20
0
파일: masher.py 프로젝트: puiterwijk/bodhi
    def _determine_tag_actions(self):
        tag_types, tag_rels = Release.get_tags(self.db)
        # sync & async tagging batches
        for i, batch in enumerate(sorted_updates(self.updates)):
            for update in batch:
                add_tags = []
                move_tags = []

                if update.status is UpdateStatus.testing:
                    status = 'testing'
                else:
                    status = 'candidate'

                for build in update.builds:
                    from_tag = None
                    tags = build.get_tags()
                    for tag in tags:
                        if tag in tag_types[status]:
                            from_tag = tag
                            break
                    else:
                        reason = ('Cannot find relevant tag for %s.  '
                                  'None of %s are in %s.') % (
                                      build.nvr, tags, tag_types[status])
                        self.eject_from_mash(update, reason)
                        break

                    if self.skip_mash:
                        add_tags.append((update.requested_tag, build.nvr))
                    else:
                        move_tags.append(
                            (from_tag, update.requested_tag, build.nvr))
                else:
                    if i == 0:
                        self.add_tags_sync.extend(add_tags)
                        self.move_tags_sync.extend(move_tags)
                    else:
                        self.add_tags_async.extend(add_tags)
                        self.move_tags_async.extend(move_tags)
예제 #21
0
    def test_create_override_multiple_nvr(self, publish):
        release = Release.get(u"F17", self.db)
        package = Package(name=u"not-bodhi")
        self.db.add(package)
        build1 = Build(nvr=u"not-bodhi-2.0-2.fc17", package=package, release=release)
        self.db.add(build1)
        self.db.flush()

        package = Package(name=u"another-not-bodhi")
        self.db.add(package)
        build2 = Build(nvr=u"another-not-bodhi-2.0-2.fc17", package=package, release=release)
        self.db.add(build2)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        data = {
            "nvr": ",".join([build1.nvr, build2.nvr]),
            "notes": u"blah blah blah",
            "expiration_date": expiration_date,
            "csrf_token": self.get_csrf_token(),
        }
        res = self.app.post("/overrides/", data)

        self.assertEquals(len(publish.call_args_list), 2)

        result = res.json_body
        self.assertEquals(result["caveats"][0]["description"], "Your override submission was split into 2.")

        o1, o2 = result["overrides"]
        self.assertEquals(o1["build_id"], build1.id)
        self.assertEquals(o1["notes"], "blah blah blah")
        self.assertEquals(o1["expiration_date"], expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o1["expired_date"], None)
        self.assertEquals(o2["build_id"], build2.id)
        self.assertEquals(o2["notes"], "blah blah blah")
        self.assertEquals(o2["expiration_date"], expiration_date.strftime("%Y-%m-%d %H:%M:%S"))
        self.assertEquals(o2["expired_date"], None)
예제 #22
0
    def test_edit_unexisting_override(self):
        release = Release.get(u'F17', self.db)

        build = Build(nvr=u'bodhi-2.0-2.fc17', release=release)
        self.db.add(build)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        o = {
            'nvr': build.nvr,
            'notes': 'blah blah blah',
            'expiration_date': expiration_date,
            'edited': build.nvr,
            'csrf_token': self.get_csrf_token(),
        }
        res = self.app.post('/overrides/', o, status=400)

        errors = res.json_body['errors']
        self.assertEquals(len(errors), 1)
        self.assertEquals(errors[0]['name'], 'edited')
        self.assertEquals(errors[0]['description'],
                          'No buildroot override for this build')
예제 #23
0
    def test_edit_unexisting_override(self):
        release = Release.get(u'F17', self.db)

        build = Build(nvr=u'bodhi-2.0-2.fc17', release=release)
        self.db.add(build)
        self.db.flush()

        expiration_date = datetime.utcnow() + timedelta(days=1)

        o = {
            'nvr': build.nvr,
            'notes': 'blah blah blah',
            'expiration_date': expiration_date,
            'edited': build.nvr,
            'csrf_token': self.get_csrf_token(),
        }
        res = self.app.post('/overrides/', o, status=400)

        errors = res.json_body['errors']
        self.assertEquals(len(errors), 1)
        self.assertEquals(errors[0]['name'], 'edited')
        self.assertEquals(errors[0]['description'],
                          'No buildroot override for this build')
예제 #24
0
    def test_cannot_edit_override_build(self, publish):
        release = Release.get(u"F17", self.db)

        old_nvr = u"bodhi-2.0-1.fc17"

        res = self.app.get("/overrides/%s" % old_nvr)
        o = res.json_body["override"]
        expiration_date = o["expiration_date"]
        old_build_id = o["build_id"]

        build = Build(nvr=u"bodhi-2.0-2.fc17", release=release)
        self.db.add(build)
        self.db.flush()

        o.update({"nvr": build.nvr, "edited": old_nvr, "csrf_token": self.get_csrf_token()})
        res = self.app.post("/overrides/", o)

        override = res.json_body
        self.assertEquals(override["build_id"], old_build_id)
        self.assertEquals(override["notes"], "blah blah blah")
        self.assertEquals(override["expiration_date"], expiration_date)
        self.assertEquals(override["expired_date"], None)
        self.assertEquals(len(publish.call_args_list), 0)
예제 #25
0
파일: releases.py 프로젝트: yarda/bodhi
def save_release(request):
    """Save a release

    This entails either creating a new release, or editing an existing one. To
    edit an existing release, the release's original name must be specified in
    the ``edited`` parameter.
    """
    data = request.validated

    edited = data.pop("edited", None)

    # This has already been validated at this point, but we need to ditch
    # it since the models don't care about a csrf argument.
    data.pop('csrf_token')

    try:
        if edited is None:
            log.info("Creating a new release: %s" % data['name'])
            r = Release(**data)

        else:
            log.info("Editing release: %s" % edited)
            r = request.db.query(Release).filter(Release.name==edited).one()
            for k, v in data.items():
                setattr(r, k, v)

    except Exception as e:
        log.exception(e)
        request.errors.add('body', 'release',
                           'Unable to create update: %s' % e)
        return


    request.db.add(r)
    request.db.flush()

    return r
예제 #26
0
def get_releases(request):
    from bodhi.models import Release
    return Release.all_releases(request.db)
예제 #27
0
파일: releases.py 프로젝트: yarda/bodhi
def get_release_html(request):
    id = request.matchdict.get('name')
    release = Release.get(id, request.db)
    if not release:
        request.errors.add('body', 'name', 'No such release')
        request.errors.status = HTTPNotFound.code
    updates = request.db.query(Update).filter(
        Update.release==release).order_by(
            Update.date_submitted.desc())

    updates_count = request.db.query(Update.date_submitted, Update.type).filter(
        Update.release==release).order_by(
            Update.date_submitted.desc())

    date_commits = {}
    dates = set()

    for update in updates_count.all():
        d = update.date_submitted
        yearmonth = str(d.year) + '/' + str(d.month).zfill(2)
        dates.add(yearmonth)
        if not update.type.description in date_commits:
            date_commits[update.type.description] = {}
        if yearmonth in date_commits[update.type.description]:
            date_commits[update.type.description][yearmonth] += 1
        else:
            date_commits[update.type.description][yearmonth] = 0

    base_count_query = request.db.query(Update)\
        .filter(Update.release==release)

    num_updates_pending = base_count_query\
        .filter(Update.status==UpdateStatus.pending).count()
    num_updates_testing = base_count_query\
        .filter(Update.status==UpdateStatus.testing).count()
    num_updates_stable = base_count_query\
        .filter(Update.status==UpdateStatus.stable).count()
    num_updates_unpushed = base_count_query\
        .filter(Update.status==UpdateStatus.unpushed).count()
    num_updates_obsolete = base_count_query\
        .filter(Update.status==UpdateStatus.obsolete).count()

    num_updates_security = base_count_query\
        .filter(Update.type==UpdateType.security).count()
    num_updates_bugfix = base_count_query\
        .filter(Update.type==UpdateType.bugfix).count()
    num_updates_enhancement = base_count_query\
        .filter(Update.type==UpdateType.enhancement).count()
    num_updates_newpackage = base_count_query\
        .filter(Update.type==UpdateType.newpackage).count()

    num_active_overrides = request.db.query(
        BuildrootOverride
    ).filter(
        BuildrootOverride.expired_date==None
    ).join(
        BuildrootOverride.build
    ).join(
        Build.release
    ).filter(
        Build.release==release
    ).count()

    num_expired_overrides = request.db.query(
        BuildrootOverride
    ).filter(
        BuildrootOverride.expired_date!=None
    ).join(
        BuildrootOverride.build
    ).join(
        Build.release
    ).filter(
        Build.release==release
    ).count()

    return dict(release=release,
                latest_updates=updates.limit(25).all(),
                count=updates.count(),
                date_commits=date_commits,
                dates=sorted(dates),

                num_updates_pending=num_updates_pending,
                num_updates_testing=num_updates_testing,
                num_updates_stable=num_updates_stable,
                num_updates_unpushed=num_updates_unpushed,
                num_updates_obsolete=num_updates_obsolete,

                num_updates_security=num_updates_security,
                num_updates_bugfix=num_updates_bugfix,
                num_updates_enhancement=num_updates_enhancement,
                num_updates_newpackage=num_updates_newpackage,

                num_active_overrides=num_active_overrides,
                num_expired_overrides=num_expired_overrides,
                )
예제 #28
0
def get_releases(request):
    from bodhi.models import Release
    return Release.all_releases(request.db)
예제 #29
0
def load_sqlalchemy_db():
    print "\nLoading pickled database %s" % sys.argv[2]
    db = file(sys.argv[2], 'r')
    data = pickle.load(db)

    import transaction
    from bodhi.models import Base
    from bodhi.models import Release, Update, Build, Comment, User, Bug, CVE
    from bodhi.models import Package, Group
    from bodhi.models import UpdateType, UpdateStatus, UpdateRequest
    from sqlalchemy import create_engine
    from sqlalchemy.orm.exc import NoResultFound

    # Caches for quick lookup
    releases = {}
    packages = {}
    users = {}
    critpath = {}

    aliases = []

    engine = bodhi.config['sqlalchemy.url']
    Session = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
    Session.configure(bind=engine)
    db = Session()

    # Allow filtering of releases to load
    whitelist = []
    if '--release' in sys.argv:
        for r in sys.argv[sys.argv.index('--release') + 1].split(','):
            whitelist.append(r)
        print('whitelist = %r' % whitelist)

    # Legacy format was just a list of update dictionaries
    # Now we'll pull things out into an organized dictionary:
    # {'updates': [], 'releases': []}
    if isinstance(data, dict):
        for release in data['releases']:
            try:
                db.query(Release).filter_by(name=release['name']).one()
            except NoResultFound:
                del(release['metrics'])
                del(release['locked'])
                r = Release(**release)
                r.stable_tag = "%s-updates" % r.dist_tag
                r.testing_tag = "%s-testing" % r.stable_tag
                r.candidate_tag = "%s-candidate" % r.stable_tag
                r.pending_testing_tag = "%s-pending" % r.testing_tag
                r.pending_stable_tag = "%s-pending" % r.stable_tag
                r.override_tag = "%s-override" % r.dist_tag
                db.add(r)
        data = data['updates']

    progress = ProgressBar(widgets=[SimpleProgress(), Percentage(), Bar()])

    for u in progress(data):
        try:
            release = releases[u['release'][0]]
        except KeyError:
            try:
                release = db.query(Release).filter_by(name=u['release'][0]).one()
            except NoResultFound:
                release = Release(name=u['release'][0], long_name=u['release'][1],
                                  id_prefix=u['release'][2],
                                  dist_tag=u['release'][3])
                db.add(release)
            releases[u['release'][0]] = release
            if whitelist:
                if release.name in whitelist:
                    critpath[release.name] = get_critpath_pkgs(release.name.lower())
                    print('%s critpath packages for %s' % (len(critpath[release.name]),
                                                           release.name))
            else:
                critpath[release.name] = get_critpath_pkgs(release.name.lower())
                print('%s critpath packages for %s' % (len(critpath[release.name]),
                                                       release.name))

        if whitelist and release.name not in whitelist:
            continue

        ## Backwards compatbility
        request = u['request']
        if u['request'] == 'move':
            u['request'] = 'stable'
        elif u['request'] == 'push':
            u['request'] = 'testing'
        elif u['request'] == 'unpush':
            u['request'] = 'obsolete'
        if u['approved'] not in (True, False):
            u['approved'] = None
        if u.has_key('update_id'):
            u['updateid'] = u['update_id']
            u['alias'] = u['update_id']

            if u['alias']:
                split = u['alias'].split('-')
                year, id = split[-2:]
                aliases.append((int(year), int(id)))

        if not u.has_key('date_modified'):
            u['date_modified'] = None

        # Port to new enum types
        if u['request']:
            if u['request'] == 'stable':
                u['request'] = UpdateRequest.stable
            elif u['request'] == 'testing':
                u['request'] = UpdateRequest.testing
            else:
                raise Exception("Unknown request: %s" % u['request'])

        if u['type'] == 'bugfix':
            u['type'] = UpdateType.bugfix
        elif u['type'] == 'newpackage':
            u['type'] = UpdateType.newpackage
        elif u['type'] == 'enhancement':
            u['type'] = UpdateType.enhancement
        elif u['type'] == 'security':
            u['type'] = UpdateType.security
        else:
            raise Exception("Unknown type: %r" % u['type'])

        if u['status'] == 'pending':
            u['status'] = UpdateStatus.pending
        elif u['status'] == 'testing':
            u['status'] = UpdateStatus.testing
        elif u['status'] == 'obsolete':
            u['status'] = UpdateStatus.obsolete
        elif u['status'] == 'stable':
            u['status'] = UpdateStatus.stable
        elif u['status'] == 'unpushed':
            u['status'] = UpdateStatus.unpushed
        else:
            raise Exception("Unknown status: %r" % u['status'])

        try:
            update = db.query(Update).filter_by(title=u['title']).one()
            continue
        except NoResultFound:
            update = Update(title=u['title'],
                            date_submitted=u['date_submitted'],
                            date_pushed=u['date_pushed'],
                            date_modified=u['date_modified'],
                            release=release,
                            old_updateid=u['updateid'],
                            alias=u['updateid'],
                            pushed=u['pushed'],
                            notes=u['notes'],
                            karma=u['karma'],
                            type=u['type'],
                            status=u['status'],
                            request=u['request'],
                            )
                            #approved=u['approved'])
            db.add(update)
            db.flush()

            try:
                user = users[u['submitter']]
            except KeyError:
                try:
                    user = db.query(User).filter_by(name=u['submitter']).one()
                except NoResultFound:
                    user = User(name=u['submitter'])
                    db.add(user)
                    db.flush()
                users[u['submitter']] = user
            user.updates.append(update)

        ## Create Package and Build objects
        for pkg, nvr in u['builds']:
            try:
                package = packages[pkg]
            except KeyError:
                try:
                    package = db.query(Package).filter_by(name=pkg).one()
                except NoResultFound:
                    package = Package(name=pkg)
                    db.add(package)
                packages[pkg] = package
            if package.name in critpath[update.release.name]:
                update.critpath = True
            try:
                build = db.query(Build).filter_by(nvr=nvr).one()
            except NoResultFound:
                build = Build(nvr=nvr, package=package)
                db.add(build)
                update.builds.append(build)

        ## Create all Bugzilla objects for this update
        for bug_num, bug_title, security, parent in u['bugs']:
            try:
                bug = db.query(Bug).filter_by(bug_id=bug_num).one()
            except NoResultFound:
                bug = Bug(bug_id=bug_num, security=security, parent=parent,
                          title=bug_title)
                db.add(bug)
            update.bugs.append(bug)

        ## Create all CVE objects for this update
        for cve_id in u['cves']:
            try:
                cve = db.query(CVE).filter_by(cve_id=cve_id).one()
            except NoResultFound:
                cve = CVE(cve_id=cve_id)
                db.add(cve)
            update.cves.append(cve)

        ## Create all Comments for this update
        for c in u['comments']:
            try:
                timestamp, author, text, karma, anonymous = c
            except ValueError:
                timestamp, author, text, karma = c
                anonymous = '@' in author

            comment = Comment(timestamp=timestamp, text=text,
                              karma=karma, anonymous=anonymous)
            db.add(comment)
            db.flush()
            update.comments.append(comment)
            if anonymous:
                name = u'anonymous'
            else:
                name = author
            group = None
            if not anonymous and ' (' in name:
                split = name.split(' (')
                name = split[0]
                group = split[1][:-1]
                assert group, name
            try:
                user = users[name]
            except KeyError:
                try:
                    user = db.query(User).filter_by(name=name).one()
                except NoResultFound:
                    user = User(name=name)
                    db.add(user)
                    db.flush()
                users[name] = user

            comment.user = user

            if group:
                try:
                    group = db.query(Group).filter_by(name=group).one()
                except NoResultFound:
                    group = Group(name=group)
                    db.add(group)
                    db.flush()
                user.groups.append(group)

        db.flush()

    # Hack to get the Bodhi2 alias generator working with bodhi1 data.
    # The new generator assumes that the alias is assigned at submission time, as opposed to push time.
    year, id = max(aliases)
    print('Highest alias = %r %r' % (year, id))
    up = db.query(Update).filter_by(alias=u'FEDORA-%s-%s' % (year, id)).one()
    print(up.title)
    up.date_submitted = up.date_pushed
    db.flush()

    transaction.commit()

    print("\nDatabase migration complete!")
    print(" * %d updates" % db.query(Update).count())
    print(" * %d builds" % db.query(Build).count())
    print(" * %d comments" % db.query(Comment).count())
    print(" * %d users" % db.query(User).count())
    print(" * %d bugs" % db.query(Bug).count())
    print(" * %d CVEs" % db.query(CVE).count())
예제 #30
0
파일: pickledb.py 프로젝트: yarda/bodhi
def load_sqlalchemy_db():
    print "\nLoading pickled database %s" % sys.argv[2]
    db = file(sys.argv[2], 'r')
    data = pickle.load(db)

    import transaction
    from bodhi.models import Base
    from bodhi.models import Release, Update, Build, Comment, User, Bug, CVE
    from bodhi.models import Package, Group
    from bodhi.models import UpdateType, UpdateStatus, UpdateRequest
    from sqlalchemy import create_engine
    from sqlalchemy.orm.exc import NoResultFound

    # Caches for quick lookup
    releases = {}
    packages = {}
    users = {}
    critpath = {}

    aliases = []

    engine = bodhi.config['sqlalchemy.url']
    Session = scoped_session(
        sessionmaker(extension=ZopeTransactionExtension()))
    Session.configure(bind=engine)
    db = Session()

    # Allow filtering of releases to load
    whitelist = []
    if '--release' in sys.argv:
        for r in sys.argv[sys.argv.index('--release') + 1].split(','):
            whitelist.append(r)
        print('whitelist = %r' % whitelist)

    # Legacy format was just a list of update dictionaries
    # Now we'll pull things out into an organized dictionary:
    # {'updates': [], 'releases': []}
    if isinstance(data, dict):
        for release in data['releases']:
            try:
                db.query(Release).filter_by(name=release['name']).one()
            except NoResultFound:
                del (release['metrics'])
                del (release['locked'])
                r = Release(**release)
                r.stable_tag = "%s-updates" % r.dist_tag
                r.testing_tag = "%s-testing" % r.stable_tag
                r.candidate_tag = "%s-candidate" % r.stable_tag
                r.pending_testing_tag = "%s-pending" % r.testing_tag
                r.pending_stable_tag = "%s-pending" % r.stable_tag
                r.override_tag = "%s-override" % r.dist_tag
                db.add(r)
        data = data['updates']

    progress = ProgressBar(widgets=[SimpleProgress(), Percentage(), Bar()])

    for u in progress(data):
        try:
            release = releases[u['release'][0]]
        except KeyError:
            try:
                release = db.query(Release).filter_by(
                    name=u['release'][0]).one()
            except NoResultFound:
                release = Release(name=u['release'][0],
                                  long_name=u['release'][1],
                                  id_prefix=u['release'][2],
                                  dist_tag=u['release'][3])
                db.add(release)
            releases[u['release'][0]] = release
            if whitelist:
                if release.name in whitelist:
                    critpath[release.name] = get_critpath_pkgs(
                        release.name.lower())
                    print('%s critpath packages for %s' %
                          (len(critpath[release.name]), release.name))
            else:
                critpath[release.name] = get_critpath_pkgs(
                    release.name.lower())
                print('%s critpath packages for %s' %
                      (len(critpath[release.name]), release.name))

        if whitelist and release.name not in whitelist:
            continue

        ## Backwards compatbility
        request = u['request']
        if u['request'] == 'move':
            u['request'] = 'stable'
        elif u['request'] == 'push':
            u['request'] = 'testing'
        elif u['request'] == 'unpush':
            u['request'] = 'obsolete'
        if u['approved'] not in (True, False):
            u['approved'] = None
        if u.has_key('update_id'):
            u['updateid'] = u['update_id']
            u['alias'] = u['update_id']

            if u['alias']:
                split = u['alias'].split('-')
                year, id = split[-2:]
                aliases.append((int(year), int(id)))

        if not u.has_key('date_modified'):
            u['date_modified'] = None

        # Port to new enum types
        if u['request']:
            if u['request'] == 'stable':
                u['request'] = UpdateRequest.stable
            elif u['request'] == 'testing':
                u['request'] = UpdateRequest.testing
            else:
                raise Exception("Unknown request: %s" % u['request'])

        if u['type'] == 'bugfix':
            u['type'] = UpdateType.bugfix
        elif u['type'] == 'newpackage':
            u['type'] = UpdateType.newpackage
        elif u['type'] == 'enhancement':
            u['type'] = UpdateType.enhancement
        elif u['type'] == 'security':
            u['type'] = UpdateType.security
        else:
            raise Exception("Unknown type: %r" % u['type'])

        if u['status'] == 'pending':
            u['status'] = UpdateStatus.pending
        elif u['status'] == 'testing':
            u['status'] = UpdateStatus.testing
        elif u['status'] == 'obsolete':
            u['status'] = UpdateStatus.obsolete
        elif u['status'] == 'stable':
            u['status'] = UpdateStatus.stable
        elif u['status'] == 'unpushed':
            u['status'] = UpdateStatus.unpushed
        else:
            raise Exception("Unknown status: %r" % u['status'])

        try:
            update = db.query(Update).filter_by(title=u['title']).one()
            continue
        except NoResultFound:
            update = Update(
                title=u['title'],
                date_submitted=u['date_submitted'],
                date_pushed=u['date_pushed'],
                date_modified=u['date_modified'],
                release=release,
                old_updateid=u['updateid'],
                alias=u['updateid'],
                pushed=u['pushed'],
                notes=u['notes'],
                karma=u['karma'],
                type=u['type'],
                status=u['status'],
                request=u['request'],
            )
            #approved=u['approved'])
            db.add(update)
            db.flush()

            try:
                user = users[u['submitter']]
            except KeyError:
                try:
                    user = db.query(User).filter_by(name=u['submitter']).one()
                except NoResultFound:
                    user = User(name=u['submitter'])
                    db.add(user)
                    db.flush()
                users[u['submitter']] = user
            user.updates.append(update)

        ## Create Package and Build objects
        for pkg, nvr in u['builds']:
            try:
                package = packages[pkg]
            except KeyError:
                try:
                    package = db.query(Package).filter_by(name=pkg).one()
                except NoResultFound:
                    package = Package(name=pkg)
                    db.add(package)
                packages[pkg] = package
            if package.name in critpath[update.release.name]:
                update.critpath = True
            try:
                build = db.query(Build).filter_by(nvr=nvr).one()
            except NoResultFound:
                build = Build(nvr=nvr, package=package)
                db.add(build)
                update.builds.append(build)

        ## Create all Bugzilla objects for this update
        for bug_num, bug_title, security, parent in u['bugs']:
            try:
                bug = db.query(Bug).filter_by(bug_id=bug_num).one()
            except NoResultFound:
                bug = Bug(bug_id=bug_num,
                          security=security,
                          parent=parent,
                          title=bug_title)
                db.add(bug)
            update.bugs.append(bug)

        ## Create all CVE objects for this update
        for cve_id in u['cves']:
            try:
                cve = db.query(CVE).filter_by(cve_id=cve_id).one()
            except NoResultFound:
                cve = CVE(cve_id=cve_id)
                db.add(cve)
            update.cves.append(cve)

        ## Create all Comments for this update
        for c in u['comments']:
            try:
                timestamp, author, text, karma, anonymous = c
            except ValueError:
                timestamp, author, text, karma = c
                anonymous = '@' in author

            comment = Comment(timestamp=timestamp,
                              text=text,
                              karma=karma,
                              anonymous=anonymous)
            db.add(comment)
            db.flush()
            update.comments.append(comment)
            if anonymous:
                name = u'anonymous'
            else:
                name = author
            group = None
            if not anonymous and ' (' in name:
                split = name.split(' (')
                name = split[0]
                group = split[1][:-1]
                assert group, name
            try:
                user = users[name]
            except KeyError:
                try:
                    user = db.query(User).filter_by(name=name).one()
                except NoResultFound:
                    user = User(name=name)
                    db.add(user)
                    db.flush()
                users[name] = user

            comment.user = user

            if group:
                try:
                    group = db.query(Group).filter_by(name=group).one()
                except NoResultFound:
                    group = Group(name=group)
                    db.add(group)
                    db.flush()
                user.groups.append(group)

        db.flush()

    # Hack to get the Bodhi2 alias generator working with bodhi1 data.
    # The new generator assumes that the alias is assigned at submission time, as opposed to push time.
    year, id = max(aliases)
    print('Highest alias = %r %r' % (year, id))
    up = db.query(Update).filter_by(alias=u'FEDORA-%s-%s' % (year, id)).one()
    print(up.title)
    up.date_submitted = up.date_pushed
    db.flush()

    transaction.commit()

    print("\nDatabase migration complete!")
    print(" * %d updates" % db.query(Update).count())
    print(" * %d builds" % db.query(Build).count())
    print(" * %d comments" % db.query(Comment).count())
    print(" * %d users" % db.query(User).count())
    print(" * %d bugs" % db.query(Bug).count())
    print(" * %d CVEs" % db.query(CVE).count())
예제 #31
0
파일: __init__.py 프로젝트: pcreech/bodhi
def populate(db):
    user = User(name=u'guest')
    db.add(user)
    anonymous = User(name=u'anonymous')
    db.add(anonymous)
    provenpackager = Group(name=u'provenpackager')
    db.add(provenpackager)
    packager = Group(name=u'packager')
    db.add(packager)
    db.flush()
    user.groups.append(packager)
    release = Release(name=u'F17',
                      long_name=u'Fedora 17',
                      id_prefix=u'FEDORA',
                      version=u'17',
                      dist_tag=u'f17',
                      stable_tag=u'f17-updates',
                      testing_tag=u'f17-updates-testing',
                      candidate_tag=u'f17-updates-candidate',
                      pending_testing_tag=u'f17-updates-testing-pending',
                      pending_stable_tag=u'f17-updates-pending',
                      override_tag=u'f17-override',
                      branch=u'f17')
    db.add(release)
    pkg = Package(name=u'bodhi')
    db.add(pkg)
    user.packages.append(pkg)
    build = Build(nvr=u'bodhi-2.0-1.fc17', release=release, package=pkg)
    db.add(build)
    testcase = TestCase(name=u'Wat')
    db.add(testcase)
    pkg.test_cases.append(testcase)
    update = Update(
        title=u'bodhi-2.0-1.fc17',
        builds=[build],
        user=user,
        request=UpdateRequest.testing,
        notes=u'Useful details!',
        release=release,
        date_submitted=datetime(1984, 11, 02),
        requirements=u'rpmlint',
        stable_karma=3,
        unstable_karma=-3,
    )
    update.type = UpdateType.bugfix
    bug = Bug(bug_id=12345)
    db.add(bug)
    update.bugs.append(bug)
    cve = CVE(cve_id=u"CVE-1985-0110")
    db.add(cve)
    update.cves.append(cve)

    comment = Comment(karma=1, text=u"wow. amaze.")
    db.add(comment)
    comment.user = user
    update.comments.append(comment)
    update.karma = 1

    comment = Comment(karma=0, text=u"srsly.  pretty good.", anonymous=True)
    comment.user = anonymous
    db.add(comment)
    update.comments.append(comment)

    with mock.patch(target='uuid.uuid4', return_value='wat'):
        update.assign_alias()
    db.add(update)

    expiration_date = datetime.utcnow()
    expiration_date = expiration_date + timedelta(days=1)

    override = BuildrootOverride(build=build,
                                 submitter=user,
                                 notes=u'blah blah blah',
                                 expiration_date=expiration_date)
    db.add(override)

    db.flush()