示例#1
0
    def handle(self):
        payload = self.request.input.get('payload')
        if payload:
            payload = b64decode(payload)
            payload = payload_from_request(self.server.json_parser, self.cid,
                                           payload,
                                           self.request.input.data_format,
                                           self.request.input.transport)

        id = self.request.input.get('id')
        name = self.request.input.get('name')
        pid = self.request.input.get('pid') or 0
        all_pids = self.request.input.get('all_pids')
        timeout = self.request.input.get('timeout') or None

        channel = self.request.input.get('channel')
        data_format = self.request.input.get('data_format')
        transport = self.request.input.get('transport')
        expiration = self.request.input.get(
            'expiration') or BROKER.DEFAULT_EXPIRATION

        if name and id:
            raise ZatoException(
                'Cannot accept both id:`{}` and name:`{}`'.format(id, name))

        if self.request.input.get('is_async'):

            if id:
                impl_name = self.server.service_store.id_to_impl_name[id]
                name = self.server.service_store.service_data(
                    impl_name)['name']

            # If PID is given on input it means we must invoke this particular server process by it ID
            if pid and pid != self.server.pid:
                response = self.server.invoke_by_pid(name, payload, pid)
            else:
                response = self.invoke_async(name, payload, channel,
                                             data_format, transport,
                                             expiration)

        else:
            # This branch the same as above in is_async branch, except in is_async there was no all_pids

            # It is possible that we were given the all_pids flag on input but we know
            # ourselves that there is only one process, the current one, so we can just
            # invoke it directly instead of going through IPC.
            if all_pids and self.server.fs_server_config.main.gunicorn_workers > 1:
                use_all_pids = True
            else:
                use_all_pids = False

            if use_all_pids:
                args = (name, payload, timeout) if timeout else (name, payload)
                response = dumps(self.server.invoke_all_pids(*args))
            else:
                if pid and pid != self.server.pid:
                    response = self.server.invoke(name,
                                                  payload,
                                                  pid=pid,
                                                  data_format=data_format)
                else:
                    func, id_ = (self.invoke,
                                 name) if name else (self.invoke_by_id, id)
                    response = func(id_,
                                    payload,
                                    channel,
                                    data_format,
                                    transport,
                                    serialize=True)

        if isinstance(response, basestring):
            if response:
                response = response if isinstance(
                    response, bytes) else response.encode('utf8')
                self.response.payload.response = b64encode(response).decode(
                    'utf8') if response else ''
示例#2
0
文件: scheduler.py 项目: danlg/zato
def index(req):
    try:
        jobs = []
        meta = None

        # Build a list of schedulers for a given Zato cluster.
        if req.zato.cluster_id and req.method == 'GET':

            # We have a cluster to pick the schedulers from, try to invoke it now.

            request = {
                'cluster_id': req.zato.cluster_id,
                'paginate': True,
                'cur_page': req.GET.get('cur_page', 1),
                'query': req.GET.get('query', '')
            }

            data, meta = parse_response_data(req.zato.client.invoke('zato.scheduler.job.get-list', request))

            for job_elem in data:

                id = job_elem.id
                name = job_elem.name
                is_active = job_elem.is_active
                job_type = job_elem.job_type
                start_date = job_elem.start_date
                service_name = job_elem.service_name
                extra = job_elem.extra
                job_type_friendly = job_type_friendly_names[job_type]

                job = Job(id, name, is_active, job_type,
                          from_utc_to_user(start_date+'+00:00', req.zato.user_profile),
                          extra, service_name=service_name,
                          job_type_friendly=job_type_friendly)

                if job_type == SCHEDULER.JOB_TYPE.ONE_TIME:
                    definition_text=_one_time_job_def(req.zato.user_profile, start_date)

                elif job_type == SCHEDULER.JOB_TYPE.INTERVAL_BASED:
                    definition_text = _interval_based_job_def(req.zato.user_profile,
                        _get_start_date(job_elem.start_date),
                        job_elem.repeats, job_elem.weeks, job_elem.days,
                        job_elem.hours, job_elem.minutes, job_elem.seconds)

                    weeks = job_elem.weeks or ''
                    days = job_elem.days or ''
                    hours = job_elem.hours or ''
                    minutes = job_elem.minutes or ''
                    seconds = job_elem.seconds or ''
                    repeats = job_elem.repeats or ''

                    ib_job = IntervalBasedJob(None, None, weeks, days, hours, minutes, seconds, repeats)
                    job.interval_based = ib_job

                elif job_type == SCHEDULER.JOB_TYPE.CRON_STYLE:
                    cron_definition = job_elem.cron_definition or ''
                    definition_text=_cron_style_job_def(req.zato.user_profile, start_date, cron_definition)

                    cs_job = CronStyleJob(None, None, cron_definition)
                    job.cron_style = cs_job

                else:
                    msg = 'Unrecognized job type, name:`{}`, type:`{}`'.format(name, job_type)
                    logger.error(msg)
                    raise ZatoException(msg)

                job.definition_text = definition_text
                jobs.append(job)

        if req.method == 'POST':

            action = req.POST.get('zato_action', '')
            if not action:
                msg = 'req.POST contains no [zato_action] parameter.'
                logger.error(msg)
                return HttpResponseServerError(msg)

            job_type = req.POST.get('job_type', '')
            if action != 'execute' and not job_type:
                msg = 'req.POST contains no [job_type] parameter.'
                logger.error(msg)
                return HttpResponseServerError(msg)

            job_name = req.POST['{0}-{1}-name'.format(action, job_type)]

            # Try to match the action and a job type with an action handler..
            handler_name = '_' + action
            if action != 'execute':
                handler_name += '_' + job_type

            handler = globals().get(handler_name)
            if not handler:
                msg = ('No handler found for action [{0}], job_type:[{1}], '
                       'req.POST:[{2}], req.GET:[{3}].'.format(action, job_type,
                          pprint(req.POST), pprint(req.GET)))

                logger.error(msg)
                return HttpResponseServerError(msg)

            # .. invoke the action handler.
            try:
                response = handler(req.zato.client, req.zato.user_profile, req.zato.cluster, req.POST)
                response = response if response else ''
                if response:
                    response['message'] = _get_success_message(action, job_type, job_name)
                    response = dumps(response)
                return HttpResponse(response, content_type='application/javascript')
            except Exception:
                msg = 'Could not invoke action `{}`, job_type:`{}`, e:`{}` req.POST:`{}`, req.GET:`{}'.format(
                    action, job_type, format_exc(), req.POST, req.GET)
                logger.error(msg)
                return HttpResponseServerError(msg)

        template_name = 'zato/scheduler.html'

        return_data = {'zato_clusters':req.zato.clusters,
            'cluster_id':req.zato.cluster_id,
            'search_form':req.zato.search_form,
            'jobs':jobs,
            'friendly_names':job_type_friendly_names.items(),
            'create_one_time_form':OneTimeSchedulerJobForm(create_one_time_prefix, req),
            'create_interval_based_form':IntervalBasedSchedulerJobForm(create_interval_based_prefix, req),
            'create_cron_style_form':CronStyleSchedulerJobForm(create_cron_style_prefix, req),
            'edit_one_time_form':OneTimeSchedulerJobForm(edit_one_time_prefix, req),
            'edit_interval_based_form':IntervalBasedSchedulerJobForm(edit_interval_based_prefix, req),
            'edit_cron_style_form':CronStyleSchedulerJobForm(edit_cron_style_prefix, req),
            'paginate':True,
            'meta': meta,
            'req': req,
            'zato_template_name': template_name,
            }

        return_data.update(get_js_dt_format(req.zato.user_profile))

        return TemplateResponse(req, template_name, return_data)
    except Exception:
        msg = '<pre>Method could not be invoked, e:`{}`</pre>'.format(format_exc())
        logger.error(msg)
        return HttpResponseServerError(msg)
示例#3
0
 def _exception():
     msg = 'A mapping between system1:[{}], key1:[{}], value1:[{}] and system2:[{}], key2:[{}] already exists'.format(
         system1, key1, value1, system2, key2)
     self.logger.error(msg)
     raise ZatoException(self.cid, msg)
示例#4
0
文件: sql.py 项目: HarshCasper/zato
 def validate_extra(self, cid, extra):
     if extra and not '=' in extra:
         raise ZatoException(
             cid,
             'extra should be a list of key=value parameters, possibly one-element long, instead of `{}`'
             .format(extra))
示例#5
0
文件: __init__.py 项目: danlg/zato
    def __call__(self, req, initial_input_dict={}, initial_return_data={}, *args, **kwargs):
        """ Handles the request, taking care of common things and delegating
        control to the subclass for fetching this view-specific data.
        """
        self.input_dict.clear()
        self.clear_user_message()

        try:
            super(CreateEdit, self).__call__(req, *args, **kwargs)
            self.set_input()
            self.populate_initial_input_dict(initial_input_dict)

            input_dict = {'cluster_id': self.cluster_id}
            post_id = self.req.POST.get('id')

            if post_id:
                input_dict['id'] = post_id

            input_dict.update(initial_input_dict)

            for name in chain(self.SimpleIO.input_required, self.SimpleIO.input_optional):
                if name not in input_dict and name not in self.input_dict:
                    value = self.input.get(name)
                    value = self.pre_process_item(name, value)
                    if value != SKIP_VALUE:
                        input_dict[name] = value

            self.input_dict.update(input_dict)
            self.pre_process_input_dict(self.input_dict)

            logger.info('Request self.input_dict %s', self.input_dict)
            logger.info('Request self.SimpleIO.input_required %s', self.SimpleIO.input_required)
            logger.info('Request self.SimpleIO.input_optional %s', self.SimpleIO.input_optional)
            logger.info('Request self.input %s', self.input)
            logger.info('Request self.req.GET %s', self.req.GET)
            logger.info('Request self.req.POST %s', self.req.POST)

            logger.info('Sending `%s` to `%s`', self.input_dict, self.service_name)

            response = self.req.zato.client.invoke(self.service_name, self.input_dict)

            if response.ok:
                return_data = {
                    'message': self.success_message(response.data)
                    }

                return_data.update(initial_return_data)

                for name in chain(self.SimpleIO.output_optional, self.SimpleIO.output_required):
                    if name not in initial_return_data:
                        value = getattr(response.data, name, None)
                        if value:
                            value = str(value)
                        return_data[name] = value

                self.post_process_return_data(return_data)

                logger.info('CreateEdit data for frontend `%s`', return_data)

                return HttpResponse(dumps(return_data), content_type='application/javascript')
            else:
                msg = 'response:`{}`, details.response.details:`{}`'.format(response, response.details)
                logger.error(msg)
                raise ZatoException(msg=msg)

        except Exception:
            return HttpResponseServerError(format_exc())