def __init__(self, parent=None):
     try:
         c_sname = CronjobConfigModel.objects.get(key='server_host').value
         c_sport = CronjobConfigModel.objects.get(key='server_port').value
         conn = rpyc.connect(
             c_sname if c_sname is not None else 'localhost',
             int(c_sport) if c_sport is not None else 12345)
         self.jobs = conn.root
         print(self.jobs)
     except Exception as e:
         logger.error('Cronjob\'s Server Error: {0}'.format(e))
Beispiel #2
0
def receive_bds_survey(request):
    logger.error("HERE")
    # This will be a list of assessments for follow up tests
    return_list = []

    if request.method == 'POST':
        # dictionary to keep track of value for each domain
        request = request.data
        domains = {}
        user = None

        try:
            # TODO: Implemenet users and screener logic
            # TODO: Along with auth
            user = request.get('user')
            screener = request.get('screener')
        except Exception:
            logger.warning('No user recorded with survey')

        try:
            # create a record to add to the database
            record = UserResponse.objects.create(screener=screener,
                                                 date=date.today())

            for answer in (request.get('answers')):
                question = Question.objects.get(id=answer.get('question_id'))

                user_answer = UserAnswer.objects.create(
                    value=answer.get('value'), question_id=question)
                record.answers.add(user_answer)

                # Add up total value for each domain
                domain = question.domain
                domains[domain] = domains.get(domain, 0) + answer.get('value')

            # Save database
            record.save()
            # check each domain against the assessment and threshold lists
            for dom in domains:

                if domains.get(dom) >= BPDS_THRESHHOLDS.get(dom):
                    return_list.append(BPDS_ASSESSMENTS.get(dom))

            return Response({"results": list(set(return_list))},
                            status=status.HTTP_201_CREATED)

        except Exception:
            logger.exception("No response data")
            return Response({'Error': "Not correct format"},
                            status=status.HTTP_400_BAD_REQUEST)

    return Response({'Error': "Not correct format"},
                    status=status.HTTP_400_BAD_REQUEST)
    def addJob(self, job):
        result = False
        try:
            _job = JobInstance(job)
            _job_id = 'ID-{0}:{1}:{2}'.format(job.id, job.code, job.title)
            print(_job_id)
            if job.type == 1:
                # 指定执行时间(仅执行一次)
                self.jobs.add_job(
                    'server:addjob',
                    'date',
                    args=[job.id],
                    id=_job_id,
                    run_date=job.start_date.strftime("%Y-%m-%d %H:%M:%S"))
            else:
                # 定时重复执行
                self.jobs.add_job(
                    'server:addjob',
                    'cron',
                    args=[job.id],
                    id=_job_id,
                    year=job.yr,
                    month=job.mo,
                    week=job.wk,
                    day=job.dy,
                    day_of_week=job.dy_of_week,
                    hour=job.hr,
                    minute=job.mi,
                    second=job.se,
                    start_date=job.start_date.strftime("%Y-%m-%d %H:%M:%S"),
                    end_date=job.end_date.strftime("%Y-%m-%d %H:%M:%S"))
            # 运行启动记录
            if (self.jobs.get_job(_job_id)):
                self.addCronjobStatus(job, action=1)
                logger.info('Add Cronjob {0}'.format(job.title))
                result = True
            else:
                self.addCronjobStatus(job, action=1, status=2)
                logger.error('Error Add Cronjob {0}: {1}'.format(
                    job.title, '启动失败'))

        except Exception as e:
            self.addCronjobStatus(job, action=1, status=2)
            logger.error('Error Add Cronjob {0}: {1}'.format(
                job.title, str(e)))

        return result
    def runJob(self):
        self._begin_time = datetime.datetime.now(tz=pytz.timezone(settings.TIME_ZONE))
        _status = 2
        _msg = ''
        logger.info('Run Begin Cronjob: {0} ==========='.format(self.title))
        try:
            # 系统内部程序调用
            if self.command_type == 1 or self.command_type == 3:
                if self.command is not None and self.command != '':
                    try:
                        _content = eval(self.command)
                        _status = 1
                        _msg = 'Complated Cronjob {0}: {1}'.format(self.title, _content)
                    except Exception as e:
                        _status = 3
                        _msg = 'Error Cronjob {0} : {1}'.format(self.title, e)
                else:
                    _status = 2
                    _msg ='Error Cronjob {0}: Command is null'.format(self.title)

            # 操作系统程序调用
            else:
                if self.command is not None and self.command != '':
                    try:
                        _result = self.execcmdCommand(self.command)
                        _status = 1
                        _msg = 'Complated Cronjob {0}: {1}'.format(self.title, _result)
                    except Exception as e:
                        _status = 3
                        _msg = 'Error Cronjob {0} : {1}'.format(self.title, e)
                else:
                    _status = 2
                    _msg ='Error Cronjob {0}: Command is null'.format(self.title)


            self._end_time = datetime.datetime.now(tz=pytz.timezone(settings.TIME_ZONE))
            self.addCronjobLogs(job=self.job, status=_status, content=_msg, date_begin=self._begin_time, date_end=self._end_time)

            logger.info(_msg)

        except Exception as e:
            self._end_time = datetime.datetime.now(tz=pytz.timezone(settings.TIME_ZONE))
            self.addCronjobLogs(job=self.job, status=3, content=e, date_begin=self._begin_time, date_end=self._end_time)
            logger.error('Error Cronjob {0}: {1}'.format(self.title, e))
    def stopJob(self, job):
        result = False
        try:
            _job_id = 'ID-{0}:{1}:{2}'.format(job.id, job.code, job.title)

            if (self.jobs.get_job(_job_id)):
                self.jobs.remove_job(_job_id)
                logger.info('{0} 已经停止'.format(_job_id))
                self.addCronjobStatus(job, action=2)

                result = True
            else:
                self.addCronjobStatus(job, action=2, status=2)
                logger.error('Error Stop Cronjob {0}: {1}'.format(
                    job.title, '任务不存在'))

        except Exception as e:
            self.addCronjobStatus(job, action=2, status=2)
            logger.error('Error Stop Cronjob {0}: {1}'.format(
                job.title, ''.join(e)))

        return result