Execute a single mail job
331545
public function executeAction($preview = false)
    {
        $jobId = intval($this->getParam(\MUtil_Model::REQUEST_ID));

        $batch = $this->loader->getTaskRunnerBatch('commjob-execute-' . $jobId);
        $batch->setMessageLogFile($this->project->getCronLogfile());
        $batch->minimalStepDurationMs = 3000; // 3 seconds max before sending feedback

        if (!$batch->isLoaded() && !is_null(($jobId))) {
            $batch->addMessage(sprintf(
                    $this->_('Starting single %s mail job %s'),
                    $this->project->getName(),
                    $jobId
                    ));

            // Check for unprocessed tokens
            $tracker = $this->loader->getTracker();
            $tracker->loadCompletedTokensBatch($batch, null, $this->currentUser->getUserId());

            // We could skip this, but a check before starting the batch is better
            $sql = $this->db->select()->from('gems__comm_jobs', array('gcj_id_job'))
                    ->where('gcj_active > 0')
                    ->where('gcj_id_job = ?', $jobId);

            $job = $this->db->fetchOne($sql);

            if (!empty($job)) {
                $batch->addTask('Mail\\ExecuteMailJobTask', $job, null, null, $preview);
            } else {
                $batch->reset();
                $this->addMessage($this->_("Mailjob is inactive and won't be executed"), 'danger');
            }
            
            if ($preview === true) {
                $batch->autoStart = true;
            }
        }

        if ($batch->isFinished()) {
            // Add the messages to the view and forward
            $messages = $batch->getMessages(true);
            if (count($messages)) {
                $this->addMessage($messages, 'info');
            }

            $this->_reroute(array('action'=>'show'));
        }
        
        if ($preview === true) {
            $title = sprintf($this->_('Preview single mail job %s'), $jobId);
        } else {
            $title = sprintf($this->_('Executing single mail job %s'), $jobId);
        }

        $this->_helper->BatchRunner($batch, $title, $this->accesslog);
    }
561052
function(to,tmpName,obj,cb){
    fs.readFile(
      path.join(__dirname, 'emailBoiler.html'),
      'utf8',
      function(err, data) {
        if (err){
          return cb(err);
        }
        var tmp = cfg.templates[tmpName];
        var locals = {
          title: '',
          content: tmp.text,
        };

        var html = ejs.render(data, locals);
        obj.link = '<a href="' + obj.url + '">' + tmp.linkText + '</a>';
        html = ejs.render(html,obj);

        var subject = ejs.render(tmp.subject,obj);

        sendEmail(to,subject,html,cb);
      }
    );
  }
118758
def run_job(key, node):
    """"""
    try:
        result = node.apply()
        return ResultMessage(key, 'done', result, None)

    except Exception as exc:
        return ResultMessage(key, 'error', None, exc)
1119895
def _execute(self, workdir, with_mpirun=False, exec_args=None):
        
        qadapter = self.manager.qadapter
        if not with_mpirun: qadapter.name = None
        if self.verbose:
            print("Working in:", workdir)

        script = qadapter.get_script_str(
            job_name=self.name,
            launch_dir=workdir,
            executable=self.executable,
            qout_path="qout_file.path",
            qerr_path="qerr_file.path",
            stdin=self.stdin_fname,
            stdout=self.stdout_fname,
            stderr=self.stderr_fname,
            exec_args=exec_args
        )

        # Write the script.
        script_file = os.path.join(workdir, "run" + self.name + ".sh")
        with open(script_file, "w") as fh:
            fh.write(script)
            os.chmod(script_file, 0o740)

        qjob, process = qadapter.submit_to_queue(script_file)
        self.stdout_data, self.stderr_data = process.communicate()
        self.returncode = process.returncode
        #raise self.Error("%s returned %s\n cmd_str: %s" % (self, self.returncode, self.cmd_str))

        return self.returncode
1085153
function execute(req, res) {
  var proxy = req.exec ? req.exec.proxy : this.proxy;
  res.send(null, proxy(req, res));
}
1293232
def submit(command_filename, workingdir, send_mail = False, username = None):
    ''''''

    # Open streams
    command_filename = command_filename
    outfile = command_filename + ".out"
    file_stdout = open(outfile, 'w')

    # Form command
    command = ['qsub']

    if send_mail and username:
        #username = 'Shane.OConnor@ucsf.edu'
        command.extend(['-m', 'eas', '-M', '%s@chef.compbio.ucsf.edu' % username])
    command.append(command_filename)

    # Submit the job and capture output.
    try:
        subp = subprocess.Popen(command, stdout=file_stdout, stderr=file_stdout, cwd=workingdir)
    except Exception, e:
        colortext.error('Failed running qsub command: %s in cwd %s.' % (command, workingdir))
        raise

    waitfor = 0
    errorcode = subp.wait()
    file_stdout.close()

    file_stdout = open(outfile, 'r')
    output = file_stdout.read().strip()
    file_stdout.close()

    if errorcode != 0:
        colortext.error('Failed running qsub command: %s in cwd %s.' % (command, workingdir))
        raise Exception(output)

    # Match job id
    # This part of the script may be error-prone as it depends on the server message.
    matches = re.match('Your job-array (\d+).(\d+)-(\d+):(\d+)', output)
    if not matches:
        matches = re.match('Your job (\d+) \(".*"\) has been submitted.*', output)

    if matches:
        jobid = int(matches.group(1))
    else:
        jobid = -1

    output = output.replace('"', "'")
    if output.startswith("qsub: ERROR"):
        raise Exception(output)

    os.remove(outfile)
    #os.remove(command_filename)

    return jobid, output
286546
def execute_job(self, job_request):
        
        # Run the Job's Actions
        job_response = JobResponse()
        job_switches = RequestSwitchSet(job_request['context']['switches'])
        for i, raw_action_request in enumerate(job_request['actions']):
            action_request = EnrichedActionRequest(
                action=raw_action_request['action'],
                body=raw_action_request.get('body', None),
                switches=job_switches,
                context=job_request['context'],
                control=job_request['control'],
                client=job_request['client'],
                async_event_loop=job_request['async_event_loop'],
                run_coroutine=job_request['run_coroutine'],
            )
            action_in_class_map = action_request.action in self.action_class_map
            if action_in_class_map or action_request.action in ('status', 'introspect'):
                # Get action to run
                if action_in_class_map:
                    action = self.action_class_map[action_request.action](self.settings)
                elif action_request.action == 'introspect':
                    from pysoa.server.action.introspection import IntrospectionAction
                    action = IntrospectionAction(server=self)
                else:
                    if not self._default_status_action_class:
                        from pysoa.server.action.status import make_default_status_action_class
                        self._default_status_action_class = make_default_status_action_class(self.__class__)
                    action = self._default_status_action_class(self.settings)
                # Wrap it in middleware
                wrapper = self.make_middleware_stack(
                    [m.action for m in self.middleware],
                    action,
                )
                # Execute the middleware stack
                try:
                    action_response = wrapper(action_request)
                except ActionError as e:
                    # Error: an error was thrown while running the Action (or Action middleware)
                    action_response = ActionResponse(
                        action=action_request.action,
                        errors=e.errors,
                    )
            else:
                # Error: Action not found.
                action_response = ActionResponse(
                    action=action_request.action,
                    errors=[Error(
                        code=ERROR_CODE_UNKNOWN,
                        message='The action "{}" was not found on this server.'.format(action_request.action),
                        field='action',
                    )],
                )

            job_response.actions.append(action_response)
            if (
                action_response.errors and
                not job_request['control'].get('continue_on_error', False)
            ):
                # Quit running Actions if an error occurred and continue_on_error is False
                break

        return job_response
532149
def send_mail(self, sender, subject, recipients, message, response_id=None, html_message=False):
        """"""

        params = {
            'sender': sender,
            'subject': subject,
            'dests': recipients,
            'message': message,
            'html_message': html_message,
        }

        if response_id:
            params['response_id'] = response_id

        return self._request('mail/', postParams=params, verb='POST')
306865
async def _execute(self, appt):
        '''
        
        '''
        user = self.core.auth.user(appt.useriden)
        if user is None:
            logger.warning('Unknown user %s in stored appointment', appt.useriden)
            await self._markfailed(appt)
            return
        await self.core.boss.execute(self._runJob(user, appt), f'Agenda {appt.iden}', user)
394320
def execute_single(self, request):
        
        if self.logger:
            self.logger.debug('Executing single request: %s', request)

        self.removeRequest(request)

        body = remoting.encode(self.getAMFRequest([request]), strict=self.strict)

        http_request = urllib2.Request(self._root_url, body.getvalue(),
            self._get_execute_headers())

        if self.proxy_args:
            http_request.set_proxy(*self.proxy_args)

        envelope = self._getResponse(http_request)

        return envelope[request.id]
962269
def run_job(self, job_id, array_id = None):
    """"""
    # set the job's status in the database
    try:
      # get the job from the database
      self.lock()
      jobs = self.get_jobs((job_id,))
      if not len(jobs):
        # it seems that the job has been deleted in the meanwhile
        return
      job = jobs[0]

      # get the machine name we are executing on; this might only work at idiap
      machine_name = socket.gethostname()

      # set the 'executing' status to the job
      job.execute(array_id, machine_name)

      self.session.commit()
    except Exception as e:
      logger.error("Caught exception '%s'", e)
      pass
    finally:
      self.unlock()

    # get the command line of the job from the database; does not need write access
    self.lock()
    job = self.get_jobs((job_id,))[0]
    command_line = job.get_command_line()
    exec_dir = job.get_exec_dir()
    self.unlock()

    logger.info("Starting job %d: %s", job_id, " ".join(command_line))

    # execute the command line of the job, and wait until it has finished
    try:
      result = subprocess.call(command_line, cwd=exec_dir)
      logger.info("Job %d finished with result %s", job_id, str(result))
    except Exception as e:
      logger.error("The job with id '%d' could not be executed: %s", job_id, e)
      result = 69 # ASCII: 'E'

    # set a new status and the results of the job
    try:
      self.lock()
      jobs = self.get_jobs((job_id,))
      if not len(jobs):
        # it seems that the job has been deleted in the meanwhile
        logger.error("The job with id '%d' could not be found in the database!", job_id)
        self.unlock()
        return

      job = jobs[0]
      job.finish(result, array_id)

      self.session.commit()

      # This might not be working properly, so use with care!
      if job.stop_on_failure and job.status == 'failure':
        # the job has failed
        # stop this and all dependent jobs from execution
        dependent_jobs = job.get_jobs_waiting_for_us()
        dependent_job_ids = set([dep.unique for dep in dependent_jobs] + [job.unique])
        while len(dependent_jobs):
          dep = dependent_jobs.pop(0)
          new = dep.get_jobs_waiting_for_us()
          dependent_jobs += new
          dependent_job_ids.update([dep.unique for dep in new])

        self.unlock()
        deps = sorted(list(dependent_job_ids))
        self.stop_jobs(deps)
        logger.warn ("Stopped dependent jobs '%s' since this job failed.", str(deps))

    except Exception as e:
      logger.error("Caught exception '%s'", e)
      pass
    finally:
      if hasattr(self, 'session'):
        self.unlock()
190420
def execute(call, out_file, prefix: ' ')
      rakefile = call.path
      
      profile = *call.profile.map(&:to_s)

      if Grably.export_path
        data = [ rakefile, out_file, { 'target' => call.task, 'profile' => profile, 'params' => params } ]
        puts "remote_grably_request:#{JSON.generate(data)}"
        $stdout.flush
        $stdin.each do |l|
          raise "error in remote (slave) grably" unless l.strip == 'remote_grab_finished'
          break
        end
      else
        key = { rakefile: rakefile, profile: profile }
        
        process = @child_processes[key]
        
        unless process
          env = { 'config' => nil }
          cmd = [
            RbConfig.ruby,
            File.expand_path(File.join(__dir__, 'runner.rb')),
            '-f',
            File.basename(rakefile),
            "mp=#{profile.join(',')}"
          ]
          cmd << "--trace" if Rake.application.options.trace
          
          stdin, stdout, thread = Open3.popen2(*[env, cmd, { :err => [ :child, :out], :chdir => File.dirname(rakefile) }].flatten)
          stdout.sync = true
          stdin.sync = true
          
          process = { stdin: stdin, stdout: stdout, thread: thread }
          @child_processes[key] = process
        end
        
        process[:stdin].puts("build|#{out_file}|#{[call.task].flatten.join('|')}")
        
        ok = false
        process[:stdout].each do |l|
          ls = l.strip
          if ls == 'remote_grab_finished'
            ok = true
            break
          end
          
          if ls.start_with?('remote_grab_request:')
            data = JSON.parse(ls['remote_grab_request:'.size..-1])
            execute(data[0], data[1], "#{prefix}  ", { target: data[2]['target'], profile: data[2]['profile'], params: data[2]['params']})
            process[:stdin].puts('remote_grab_finished')
          else
            log_msg "#{prefix}#{l}"
          end
        end
        
        raise 'error in remote grab' unless ok
      end
    end
575198
def launch(self):
        """"""
        # Make script file #
        self.make_script()
        # Do it #
        sbatch_out = sh.sbatch(self.script_path)
        jobs.expire()
        # Message #
        print Color.i_blu + "SLURM:" + Color.end + " " + str(sbatch_out),
        # Return id #
        self.id = int(re.findall("Submitted batch job ([0-9]+)", str(sbatch_out))[0])
        return self.id
1093772
def execute(self, processProtocol, command, env={},
                path=None, uid=None, gid=None, usePTY=0, childFDs=None):
        
        raise NotImplementedError()
131449
def _execute(task):
  
  print "[%s] -- %s -- START" % (datetime.datetime.now(), task['id'])
  try:
    with get_app().app_context():
      exec task['code'] in {}, {}
      print "[%s] -- %s -- COMPLETE" % (datetime.datetime.now(), task['id'])
  except Exception as e:
    if isinstance(e, PyCodeError):
      err_msg = "%s: %s\n%s" % (e.data['name'], e.data['message'],
                                ''.join(e.data['traceback']))
    else:
      err_msg = traceback.format_exc()
    sys.stderr.write(err_msg)
    sys.stderr.write("[%s] -- %s -- FAIL\n" % (datetime.datetime.now(),
                                               task['id']))
    email_msg = 'Task %s failed at %s\n\n%s' % (task['id'],
                                                datetime.datetime.now(),
                                                err_msg)
    send_mail(get_app().config['SCHEDULER_FAILURE_EMAILS'],
              'Scheduler Failure', email_msg)
  finally:
    return task
1014444
def run(self, target, payload, instance=None, hook_id=None, **kwargs):
        
        self.post_data(target, payload, hook_id)
339185
def main():
    
    description = 'Letter - a commandline interface'
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('--gmail', action='store_true', help='Send via Gmail', )
    args = parser.parse_args()

    to       = raw_input('To address > ')
    subject  = raw_input('Subject > ')
    body     = raw_input('Your Message > ')


    if args.gmail:
        user = fromaddr = raw_input('Gmail Address > ')
        pw   = getpass.getpass()
        postie = letter.GmailPostman(user=user, pw=pw)
    else:
        postie = letter.Postman() # Unauthorized SMTP, localhost:25
        fromaddr = raw_input('From address > ')

    class Message(letter.Letter):
        Postie     = postie

        From       = fromaddr
        To         = to
        Subject    = subject
        Body       = body

    return 0