예제 #1
0
    def show(self, gist_id, revision='tip', format='html', f_path=None):
        c.gist = Gist.get_or_404(gist_id)

        if c.gist.is_expired:
            log.error('Gist expired at %s',
                      time_to_datetime(c.gist.gist_expires))
            raise HTTPNotFound()
        try:
            c.file_changeset, c.files = GistModel().get_gist_files(
                gist_id, revision=revision)
        except VCSError:
            log.error(traceback.format_exc())
            raise HTTPNotFound()
        if format == 'raw':
            content = '\n\n'.join([
                f.content for f in c.files
                if (f_path is None or safe_unicode(f.path) == f_path)
            ])
            response.content_type = 'text/plain'
            return content
        return render('admin/gists/show.html')
예제 #2
0
    def get_file(self, request):
        """Returns a file located in the static/ directory."""
        filename = request.sync_info['filename']
        path = os.path.join(_STATIC_DIR, filename)
        if not os.path.exists(path):
            raise HTTPNotFound()

        with open(path) as f:
            data = f.read()

        __, content_type = guess_type(filename)
        return Response(data, content_type=content_type)
예제 #3
0
    def __call__(self, request):
        global frame_queue
        self.frame_queue = frame_queue
        self.request = request

        view_name = request.path_info.lstrip('/') or 'index'
        view_method = getattr(self, '%s_view' % view_name, None)
        if not callable(view_method):
            return HTTPNotFound()
        return view_method()

        return method()
예제 #4
0
 def sync(self, broker, args):
     (remote_sync, hash_, id_, created_at, put_timestamp, delete_timestamp,
      metadata) = args
     timemark = time.time()
     try:
         info = broker.get_replication_info()
     except (Exception, Timeout), e:
         if 'no such table' in str(e):
             self.logger.error(_("Quarantining DB %s") % broker.db_file)
             quarantine_db(broker.db_file, broker.db_type)
             return HTTPNotFound()
         raise
예제 #5
0
    def __get_filenode(self, cs, path):
        """
        Returns file_node or raise HTTP error.

        :param cs: given changeset
        :param path: path to lookup
        """

        try:
            file_node = cs.get_node(path)
            if file_node.is_dir():
                raise RepositoryError('given path is a directory')
        except ChangesetDoesNotExistError:
            msg = _('Such revision does not exist for this repository')
            h.flash(msg, category='error')
            raise HTTPNotFound()
        except RepositoryError as e:
            h.flash(e, category='error')
            raise HTTPNotFound()

        return file_node
예제 #6
0
 def sync(self, broker, args):
     (remote_sync, hash_, id_, created_at, put_timestamp,
      delete_timestamp, metadata) = args
     try:
         info = broker.get_replication_info()
     except Exception, e:
         if 'no such table' in str(e):
             # TODO(unknown): find a real logger
             print _("Quarantining DB %s") % broker.db_file
             quarantine_db(broker.db_file, broker.db_type)
             return HTTPNotFound()
         raise
    def change_password(self, request):
        """Changes the user's password

        Takes a classical authentication or a reset code
        """
        # the body is in plain text utf8 string
        new_password = request.body.decode('utf8')

        if not valid_password(request.user.get('username'), new_password):
            raise HTTPBadRequest('Password should be at least 8 '
                                 'characters and not the same as your '
                                 'username')

        key = request.headers.get('X-Weave-Password-Reset')

        if key is not None:
            user_id = self.auth.get_user_id(request.user)

            if user_id is None:
                raise HTTPNotFound()

            if not self.reset.verify_reset_code(request.user, key):
                log_cef('Invalid Reset Code submitted',
                        5,
                        request.environ,
                        self.app.config,
                        request.user['username'],
                        'InvalidResetCode',
                        submitedtoken=key)

                raise HTTPJsonBadRequest(ERROR_INVALID_RESET_CODE)

            if not self.auth.admin_update_password(request.user, new_password,
                                                   key):
                raise HTTPInternalServerError('Password change failed '
                                              'unexpectedly.')
        else:
            # classical auth
            self.app.auth.authenticate_user(request, self.app.config,
                                            request.user['username'])

            if request.user['userid'] is None:
                log_cef('User Authentication Failed', 5, request.environ,
                        self.app.config, request.user['username'],
                        AUTH_FAILURE)
                raise HTTPUnauthorized()

            if not self.auth.update_password(
                    request.user, request.user_password, new_password):
                raise HTTPInternalServerError('Password change failed '
                                              'unexpectedly.')

        return text_response('success')
예제 #8
0
    def update_component(self, req, id, component_meta):
        """
        Updates an existing component with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'modify_image')
        orig_component_meta = self.get_component_meta_or_404(req, id)

        # Do not allow any updates on a deleted image.
        # Fix for LP Bug #1060930
        if orig_component_meta['deleted']:
            msg = _("Forbidden to update deleted component.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        try:
            component_meta = registry.update_component_metadata(
                req.context, id, component_meta)

        except exception.Invalid as e:
            msg = (_("Failed to update component metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find component to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update component: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('Host operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('component.update', component_meta)

        return {'component_meta': component_meta}
예제 #9
0
    def delete(self, req, id):
        """
        Deletes the image and all its chunks from the Glance

        :param req: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :raises HttpBadRequest if image registry is invalid
        :raises HttpNotFound if image or any chunk is not available
        :raises HttpUnauthorized if image or any chunk is not
                deleteable by the requesting user
        """
        self._enforce(req, 'delete_image')

        image = self.get_image_meta_or_404(req, id)
        if image['protected']:
            msg = _("Image is protected")
            LOG.debug(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")

        if image['status'] == 'deleted':
            msg = _("Forbidden to delete a deleted image.")
            LOG.debug(msg)
            raise HTTPForbidden(explanation=msg, request=req,
                                content_type="text/plain")

        if image['location'] and CONF.delayed_delete:
            status = 'pending_delete'
        else:
            status = 'deleted'

        try:
            # Delete the image from the registry first, since we rely on it
            # for authorization checks.
            # See https://bugs.launchpad.net/glance/+bug/1065187
            registry.update_image_metadata(req.context, id, {'status': status})
            registry.delete_image_metadata(req.context, id)

            # The image's location field may be None in the case
            # of a saving or queued image, therefore don't ask a backend
            # to delete the image if the backend doesn't yet store it.
            # See https://bugs.launchpad.net/glance/+bug/747799
            if image['location']:
                self._initiate_deletion(req, image['location'], id)
        except exception.NotFound, e:
            msg = (_("Failed to find image to delete: %(e)s") % locals())
            for line in msg.split('\n'):
                LOG.info(line)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
예제 #10
0
    def show(self, request):
        """
        GET /v1.0/{account_id}/volumes/{id}

        Show volume info
        """
        try:
            volume = self.account_query(Volume).filter_by(id=self.id).one()
        except NoResultFound:
            raise HTTPNotFound("Cannot show non-existent volume '%s'" %
                               self.id)
        return Response(dict(volume))
예제 #11
0
    def cluster_config_set_progress(self, req, config_set_meta):
        role_list = []
        if 'cluster' in config_set_meta:
            orig_cluster = config_set_meta['cluster']
            self._raise_404_if_cluster_deleted(req, orig_cluster)
            try:
                if config_set_meta.get('role', None):
                    role_id_list = self._raise_404_if_role_exist(
                        req, config_set_meta)
                    if len(role_id_list) == len(config_set_meta['role']):
                        for role_id in role_id_list:
                            role_info = {}
                            role_meta = registry.get_role_metadata(
                                req.context, role_id)
                            role_info['role-name'] = role_meta['name']
                            role_info['config_set_update_progress'] = \
                                role_meta[
                                'config_set_update_progress']
                            role_list.append(role_info)
                    else:
                        msg = "the role is not exist"
                        LOG.error(msg)
                        raise HTTPNotFound(msg)
                else:
                    roles = registry.get_roles_detail(req.context)
                    for role in roles:
                        if role['cluster_id'] == config_set_meta['cluster']:
                            role_info = {}
                            role_info['role-name'] = role['name']
                            role_info['config_set_update_progress'] = role[
                                'config_set_update_progress']
                            role_list.append(role_info)

            except exception.Invalid as e:
                raise HTTPBadRequest(explanation=e.msg, request=req)
            return role_list
        else:
            msg = "the cluster is not exist"
            LOG.error(msg)
            raise HTTPNotFound(msg)
    def _dispatch_request(self, request):
        """Dispatch the request.

        This will dispatch the request either to a special internal handler
        or to one of the configured controller methods.
        """
        # XXX
        # removing the trailing slash - ambiguity on client side
        url = request.path_info.rstrip('/')
        if url != '':
            request.environ['PATH_INFO'] = request.path_info = url

        # the heartbeat page is called
        if url == '/%s' % self.heartbeat_page:
            # the app is shutting down, we want to return a 503
            if self.shutting:
                raise HTTPServiceUnavailable()

            # otherwise we do call the heartbeat page
            if (self.heartbeat_page is not None
                    and request.method in ('HEAD', 'GET')):
                return self._heartbeat(request)

        # the debug page is called
        if self.debug_page is not None and url == '/%s' % self.debug_page:
            return self._debug(request)

        # the request must be going to a controller method
        match = self.mapper.routematch(environ=request.environ)

        if match is None:
            # Check whether there is a match on just the path.
            # If not then it's a 404; if so then it's a 405.
            match = self.mapper.routematch(url=request.path_info)
            if match is None:
                return HTTPNotFound()
            else:
                return HTTPMethodNotAllowed()

        match, __ = match

        # if auth is enabled, wrap it around the call to the controller
        if self.auth is None:
            return self._dispatch_request_with_match(request, match)
        else:
            self.auth.check(request, match)
            try:
                response = self._dispatch_request_with_match(request, match)
            except HTTPException, response:
                self.auth.acknowledge(request, response)
                raise
            else:
예제 #13
0
파일: clone.py 프로젝트: pombredanne/lunr
    def create(self, req, lock):
        try:
            source = self.helper.volumes.get(self.volume_id)
        except NotFound:
            raise HTTPNotFound("No volume named '%s'" % self.volume_id)
        try:
            iqn = req.params['iqn']
        except KeyError:
            raise HTTPBadRequest("Must specify an export iqn")
        try:
            iscsi_ip = req.params['iscsi_ip']
        except KeyError:
            raise HTTPBadRequest("Must specify iscsi ip")
        try:
            iscsi_port = int(req.params.get('iscsi_port', 3260))
        except ValueError:
            raise HTTPPreconditionFailed("Port must be an integer")
        try:
            mgmt_host = req.params['mgmt_host']
        except KeyError:
            raise HTTPBadRequest("Must specify mgmt_host")
        try:
            mgmt_port = req.params['mgmt_port']
        except ValueError:
            raise HTTPBadRequest("Must specify mgmt_port")
        except KeyError:
            raise HTTPPreconditionFailed("Must specify mgmt_port")

        cinder = None
        account = req.params.get('account')
        if account:
            cinder = self.helper.get_cinder(account)

        def callback():
            path = '/volumes/%s/export' % self.id
            self.helper.node_request(mgmt_host, mgmt_port, 'DELETE', path)
            self.helper.make_api_request('volumes',
                                         self.id,
                                         data={'status': 'ACTIVE'})
            if cinder:
                cinder.delete_volume_metadata(self.id, 'clone-progress')

        self.helper.volumes.create_clone(self.volume_id,
                                         self.id,
                                         iqn,
                                         iscsi_ip,
                                         iscsi_port,
                                         cinder=cinder,
                                         callback=callback,
                                         lock=lock)

        return Response(source)
예제 #14
0
    def update_host_template(self, req, template_id, host_template):
        """
        Updates an existing Template with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'update_host_template')
        # orig_Template_meta = self.get_Template_meta_or_404(req, id)
        '''
        if orig_Template_meta['deleted']:
            msg = _("Forbidden to update deleted Template.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        '''
        try:
            host_template = registry.update_host_template_metadata(
                req.context, template_id, host_template)

        except exception.Invalid as e:
            msg = (_("Failed to update template metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find host_template to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update host_template: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('host_template operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('host_template.update', host_template)

        return {'host_template': host_template}
예제 #15
0
def _handle(context, request):
    hcol = request.get_collection("morpcc.endpointhandler")
    handlers = hcol.search(
        rulez.and_(
            rulez.field["endpoint_uuid"] == context.uuid,
            rulez.field["method"] == request.method,
        ))
    if not handlers:
        raise HTTPNotFound()
    handler = handlers[0].function()
    ctx = RestrictedContext(request)
    req = RestrictedRequest(request)
    return handler(ctx, req)
def _notfound(request):
    match = request.matchdict
    # the route exists, raising a 405
    if match is not None:
        pattern = request.matched_route.pattern
        service = request.registry['cornice_services'].get(pattern)
        if service is not None:
            res = HTTPMethodNotAllowed()
            res.allow = service.defined_methods
            return res

    # 404
    return HTTPNotFound()
예제 #17
0
    def get_item(self, request, full=True):  # always full
        """Returns a single WBO object."""
        collection_name = request.sync_info['collection']
        item_id = request.sync_info['item']
        user_id = request.user['userid']
        fields = _WBO_FIELDS
        storage = self._get_storage(request)
        res = storage.get_item(user_id, collection_name, item_id,
                               fields=fields)
        if res is None:
            raise HTTPNotFound()

        return json_response(res)
 def __call__(self, request:Request):
     for pattern, handler in self._Route.ROUTETABLE:
         matcher = pattern.match(request.path)
         if matcher:
             # 所有分组组成的元组,包含命名分组
             # 1,动态在对象上添加
             # 2,可以利用传参的方式
             request.groups = matcher.groups()
             request.groupdict = matcher.groupdict()
             # 匹配成功,则交由对应的handler处理程序处理
             return handler(request)
     # 所有都没有匹配则抛出找不到异常
     raise HTTPNotFound('<h1>ERROR PAGE</h1>')
예제 #19
0
    def show(self, gist_id, revision='tip', format='html', f_path=None):
        """GET /admin/gists/gist_id: Show a specific item"""
        # url('gist', gist_id=ID)
        c.gist = Gist.get_or_404(gist_id)

        #check if this gist is not expired
        if c.gist.gist_expires != -1:
            if time.time() > c.gist.gist_expires:
                log.error('Gist expired at %s' %
                          (time_to_datetime(c.gist.gist_expires)))
                raise HTTPNotFound()
        try:
            c.file_changeset, c.files = GistModel().get_gist_files(gist_id,
                                                            revision=revision)
        except VCSError:
            log.error(traceback.format_exc())
            raise HTTPNotFound()
        if format == 'raw':
            content = '\n\n'.join([f.content for f in c.files if (f_path is None or f.path == f_path)])
            response.content_type = 'text/plain'
            return content
        return render('admin/gists/show.html')
예제 #20
0
    def __get_commit_or_redirect(self,
                                 commit_id,
                                 repo_name,
                                 redirect_after=True):
        """
        This is a safe way to get commit. If an error occurs it redirects to
        tip with proper message

        :param commit_id: id of commit to fetch
        :param repo_name: repo name to redirect after
        :param redirect_after: toggle redirection
        """
        try:
            return c.rhodecode_repo.get_commit(commit_id)
        except EmptyRepositoryError:
            if not redirect_after:
                return None
            url_ = url('files_add_home',
                       repo_name=c.repo_name,
                       revision=0,
                       f_path='',
                       anchor='edit')
            if h.HasRepoPermissionAny('repository.write',
                                      'repository.admin')(c.repo_name):
                add_new = h.link_to(_('Click here to add a new file.'),
                                    url_,
                                    class_="alert-link")
            else:
                add_new = ""
            h.flash(h.literal(_('There are no files yet. %s') % add_new),
                    category='warning')
            redirect(h.url('summary_home', repo_name=repo_name))
        except (CommitDoesNotExistError, LookupError):
            msg = _('No such commit exists for this repository')
            h.flash(msg, category='error')
            raise HTTPNotFound()
        except RepositoryError as e:
            h.flash(safe_str(e), category='error')
            raise HTTPNotFound()
예제 #21
0
    def show(self, request):
        """
        GET /v1.0/{account_id}/backups/{id}

        Show backup info
        """
        try:
            backup = self.account_query(Backup).\
                filter_by(id=self.id).one()
        except NoResultFound:
            raise HTTPNotFound("Cannot show non-existent backup '%s'" %
                               self.id)
        return Response(dict(backup))
예제 #22
0
    def index(self):
        if c.rhodecode_repo.alias != 'hg':
            raise HTTPNotFound()

        c.repo_bookmarks = OrderedDict()

        bookmarks = [(name, c.rhodecode_repo.get_changeset(hash_)) for \
                 name, hash_ in c.rhodecode_repo._repo._bookmarks.items()]
        ordered_tags = sorted(bookmarks, key=lambda x: x[1].date, reverse=True)
        for name, cs_book in ordered_tags:
            c.repo_bookmarks[name] = cs_book

        return render('bookmarks/bookmarks.html')
예제 #23
0
    def guard(self, env, data):
        # XXX a syntax for multiple attributes
        request = env.request
        if isinstance(request, GuardedRequest):
            request = request.unwrap()
        if request.method not in self.methods:
            raise HTTPMethodNotAllowed()

        # we can skip parameters validation for cached views because
        # their usage is restricted by @cache wrapping request into a
        # GuardedRequest
        if self.params or (self.params is not None
                           and not isinstance(env.request, GuardedRequest)):
            checked_args = set()
            for key, value in request.GET.items():
                if key.startswith('utm_') or key.startswith('hc_'):
                    continue
                if key in checked_args or key not in self.params:
                    raise HTTPNotFound()
                checked_args.add(key)
                tp = self.params[key]
                if type(tp) in (list, tuple):
                    if value and not value in tp:
                        raise HTTPNotFound
                elif value and tp is not None and tp != "":
                    try:
                        tp(value)
                    except ValueError:  # XXX write validation
                        raise HTTPNotFound()
        if request.method == 'POST' and self.xsrf_check:
            xsrf_token1 = request.POST.get('sid', u'')
            xsrf_token2 = request.cookies.get('sid', u'')
            if not xsrf_token1 or xsrf_token1 != xsrf_token2:
                message = env.gettext(
                    u'Для отправки формы браузер '
                    u'должен поддерживать JavaScript и Cookie')
                return HTTPBadRequest(message)

        return self.next_handler(env, data)
예제 #24
0
def xattredit(context, request):
    if not context.update_view_enabled:
        raise HTTPNotFound()
    if not context.model.is_editable():
        request.notify("warning", "Readonly", "Object in readonly state")
        return morepath.redirect(request.link(context))

    xattrprovider = context.model.xattrprovider()
    if xattrprovider:
        xattrformschema = dc2colander.convert(
            xattrprovider.schema, request=request, default_tzinfo=request.timezone()
        )
    else:
        raise HTTPNotFound()

    data = xattrprovider.as_dict()
    return {
        "page_title": "Edit: %s" % html.escape(context.model.title()),
        "form_title": "Edit Extended Attributes",
        "form": deform.Form(xattrformschema(), buttons=("Submit",)),
        "form_data": data,
    }
예제 #25
0
    def get_concrete_response(self):
        try:
            result = self.get_data_response()
        except NoViewMethod as exc:
            return HTTPUnsupportedMediaType(body=render_error_page(
                415, exc, mimetype=self.mimetype),
                                            content_type="text/html")
        except InvalidInput as exc:
            ## if the model raises a InvalidInput, retry the request as
            ## a GET request for the same program, and set the code to 400.
            request = make_duplicate_request(self.request)
            request.method = 'GET'
            c = HTTPController(request,
                               self.manifest,
                               self.model_mock,
                               errors=exc)
            response = c.get_response()
            response.status_int = 400
            return response
        except NotAuthorized as exc:
            return HTTPForbidden(body=render_error_page(
                403, exc, mimetype=self.mimetype),
                                 content_type="text/html")
        except (DataNotFound, ProgramNotFound) as exc:
            return HTTPNotFound(body=render_error_page(404,
                                                       exc,
                                                       mimetype=self.mimetype),
                                content_type="text/html")

        if type(result['body']) == Redirection:
            response = HTTPFound(location=result['body'].path)
        else:
            lazy = None
            body = result['body']

            if type(body) == tuple:
                lazy = body
                body = ''

            if hasattr(body, 'read'):
                body = body.read()

            response = Response(
                status=200,
                body=body,
                content_type=result['mimetype'],
            )

            response.lazy_data = lazy

        return response
예제 #26
0
    def update_version(self, req, id, version_meta):
        """
        Updates an existing version with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'update_version')
        orig_version_meta = self.get_version_meta_or_404(req, id)

        if orig_version_meta['deleted']:
            msg = _("Forbidden to update deleted version.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        try:
            version_meta = registry.update_version_metadata(
                req.context, id, version_meta)

        except exception.Invalid as e:
            msg = (_("Failed to update version metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find version to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update version: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('Host operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('version.update', version_meta)

        return {'version_meta': version_meta}
예제 #27
0
def process_edit(context, request):
    if not context.update_view_enabled:
        raise HTTPNotFound()
    if not context.model.is_editable():
        request.notify("warning", "Readonly", "Object in readonly state")
        return morepath.redirect(request.link(context))
    formschema = dc2colander.convert(
        context.model.schema,
        request=request,
        mode="edit-process",
        include_fields=context.edit_include_fields,
        exclude_fields=context.edit_exclude_fields,
        include_schema_validators=False,
        default_tzinfo=request.timezone(),
    )
    fs = formschema()
    fs = fs.bind(context=context, request=request)
    data = context.model.data.as_dict()
    controls = list(request.POST.items())
    form = deform.Form(fs, buttons=("Submit",))

    failed = False
    try:
        data = form.validate(controls)
    except deform.ValidationFailure as e:
        form = e
        failed = True
    if not failed:
        try:
            context.model.update(data, deserialize=False)
        except ValidationError as e:
            failed = True
            for fe in e.field_errors:
                node = form
                if fe.path in form:
                    node = form[fe.path]
                node_error = colander.Invalid(node.widget, fe.message)
                node.widget.handle_error(node, node_error)
        if not failed:
            return morepath.redirect(request.link(context))

    @request.after
    def set_header(response):
        response.headers.add("X-MORP-FORM-FAILED", "True")

    return {
        "page_title": "Edit: %s" % html.escape(context.model.title()),
        "form_title": "Edit",
        "form": form,
        "form_data": data,
    }
예제 #28
0
파일: server.py 프로젝트: a4a881d4/swift
class AccountController(object):
    """WSGI controller for the account server."""
    def __init__(self, conf):
        self.logger = get_logger(conf, log_route='account-server')
        self.root = conf.get('devices', '/srv/node')
        self.mount_check = conf.get('mount_check', 'true').lower() in \
                              ('true', 't', '1', 'on', 'yes', 'y')
        self.replicator_rpc = ReplicatorRpc(self.root,
                                            DATADIR,
                                            AccountBroker,
                                            self.mount_check,
                                            logger=self.logger)
        self.auto_create_account_prefix = \
            conf.get('auto_create_account_prefix') or '.'
        swift.common.db.DB_PREALLOCATION = \
            conf.get('db_preallocation', 'f').lower() in TRUE_VALUES

    def _get_account_broker(self, drive, part, account):
        hsh = hash_path(account)
        db_dir = storage_directory(DATADIR, part, hsh)
        db_path = os.path.join(self.root, drive, db_dir, hsh + '.db')
        return AccountBroker(db_path, account=account, logger=self.logger)

    @public
    def DELETE(self, req):
        """Handle HTTP DELETE request."""
        start_time = time.time()
        try:
            drive, part, account = split_path(unquote(req.path), 3)
            validate_device_partition(drive, part)
        except ValueError, err:
            self.logger.increment('DELETE.errors')
            return HTTPBadRequest(body=str(err),
                                  content_type='text/plain',
                                  request=req)
        if self.mount_check and not check_mount(self.root, drive):
            self.logger.increment('DELETE.errors')
            return HTTPInsufficientStorage(drive=drive, request=req)
        if 'x-timestamp' not in req.headers or \
                    not check_float(req.headers['x-timestamp']):
            self.logger.increment('DELETE.errors')
            return HTTPBadRequest(body='Missing timestamp',
                                  request=req,
                                  content_type='text/plain')
        broker = self._get_account_broker(drive, part, account)
        if broker.is_deleted():
            self.logger.timing_since('DELETE.timing', start_time)
            return HTTPNotFound(request=req)
        broker.delete_db(req.headers['x-timestamp'])
        self.logger.timing_since('DELETE.timing', start_time)
        return HTTPNoContent(request=req)
예제 #29
0
    def account_update(self, req, account, container, broker):
        """
        Update the account server with latest container info.

        :param req: webob.Request object
        :param account: account name
        :param container: container name
        :param borker: container DB broker object
        :returns: if the account request returns a 404 error code,
                  HTTPNotFound response object, otherwise None.
        """
        account_host = req.headers.get('X-Account-Host')
        account_partition = req.headers.get('X-Account-Partition')
        account_device = req.headers.get('X-Account-Device')
        if all([account_host, account_partition, account_device]):
            account_ip, account_port = account_host.rsplit(':', 1)
            new_path = '/' + '/'.join([account, container])
            info = broker.get_info()
            account_headers = {'x-put-timestamp': info['put_timestamp'],
                'x-delete-timestamp': info['delete_timestamp'],
                'x-object-count': info['object_count'],
                'x-bytes-used': info['bytes_used'],
                'x-trans-id': req.headers.get('x-trans-id', '-')}
            if req.headers.get('x-account-override-deleted', 'no').lower() == \
                    'yes':
                account_headers['x-account-override-deleted'] = 'yes'
            try:
                with ConnectionTimeout(self.conn_timeout):
                    conn = http_connect(account_ip, account_port,
                        account_device, account_partition, 'PUT', new_path,
                        account_headers)
                with Timeout(self.node_timeout):
                    account_response = conn.getresponse()
                    account_response.read()
                    if account_response.status == 404:
                        return HTTPNotFound(request=req)
                    elif account_response.status < 200 or \
                            account_response.status > 299:
                        self.logger.error(_('ERROR Account update failed '
                            'with %(ip)s:%(port)s/%(device)s (will retry '
                            'later): Response %(status)s %(reason)s'),
                            {'ip': account_ip, 'port': account_port,
                             'device': account_device,
                             'status': account_response.status,
                             'reason': account_response.reason})
            except (Exception, Timeout):
                self.logger.exception(_('ERROR account update failed with '
                    '%(ip)s:%(port)s/%(device)s (will retry later)'),
                    {'ip': account_ip, 'port': account_port,
                     'device': account_device})
        return None
예제 #30
0
def process_xattredit(context, request):
    if not context.update_view_enabled:
        raise HTTPNotFound()
    if not context.model.is_editable():
        request.notify("warning", "Readonly", "Object in readonly state")
        return morepath.redirect(request.link(context))

    xattrprovider = context.model.xattrprovider()
    if xattrprovider:
        xattrformschema = dc2colander.convert(
            xattrprovider.schema, request=request, default_tzinfo=request.timezone()
        )
    else:
        raise HTTPNotFound()

    fs = xattrformschema()
    fs = fs.bind(context=context, request=request)
    data = xattrprovider.as_dict()
    controls = list(request.POST.items())
    form = deform.Form(fs, buttons=("Submit",))

    failed = False
    try:
        data = form.validate(controls)
    except deform.ValidationFailure as e:
        form = e
        failed = True
    if not failed:
        # FIXME: model update should allow datetime object
        xattrprovider.update(data)
        return morepath.redirect(request.link(context))

    return {
        "page_title": "Edit: %s" % html.escape(context.model.title()),
        "form_title": "Edit",
        "form": form,
        "form_data": data,
    }