//create crontab jobs from args
506025
func NewCrontab(args string, handlers ...Handler) (Crontab, error) {
	return buildCronab(args, handlers...)
}
1325552
func (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (*taskAPI.CreateTaskResponse, error) {
	log.G(ctx).Debugf("Create: %s", r.ID)

	// Hold the lock for the entire duration to avoid duplicate process creation.
	s.mu.Lock()
	defer s.mu.Unlock()

	_, err := namespaces.NamespaceRequired(ctx)
	if err != nil {
		return nil, errors.Wrap(err, "create namespace")
	}

	if r.Options != nil {
		v, err := typeurl.UnmarshalAny(r.Options)
		if err != nil {
			return nil, err
		}
		s.shimOpts = *v.(*options.Options)
	}

	if p := s.processes[r.ID]; p != nil {
		return nil, errdefs.ToGRPCf(errdefs.ErrAlreadyExists, "process %s already exists", r.ID)
	}
	if r.ID != s.id {
		return nil, errdefs.ToGRPCf(errdefs.ErrFailedPrecondition, "init process id '%s' != shim id '%s'", r.ID, s.id)
	}

	// Add the mounts to the layer paths
	if err := writeMountsToConfig(r.Bundle, r.Rootfs); err != nil {
		return nil, errdefs.ToGRPC(err)
	}

	// Create the IO for the process
	io, err := runc.NewPipeIO()
	if err != nil {
		return nil, errors.Wrap(err, "failed to create io pipes")
	}
	defer func() {
		if err != nil {
			io.Close()
		}
	}()
	// Create the upstream IO
	ps, err := newPipeSet(ctx, r.Stdin, r.Stdout, r.Stderr, r.Terminal)
	if err != nil {
		return nil, errors.Wrap(err, "failed to connect to upstream IO")
	}
	defer func() {
		if err != nil {
			ps.Close()
		}
	}()
	// Create the relay for them both.
	pr := newPipeRelay(ctx, ps, io)
	defer func() {
		if err != nil {
			pr.close()
		}
	}()

	if s.shimOpts.Debug {
		if s.debugLog == "" {
			if s.shimOpts.DebugType == options.Options_FILE {
				s.debugLog = filepath.Join(r.Bundle, fmt.Sprintf("runhcs-%s.log", r.ID))
			} else {
				logPath := safePipePrefix + fmt.Sprintf("runhcs-log-%s", r.ID)
				l, err := winio.ListenPipe(logPath, nil)
				if err != nil {
					return nil, err
				}
				s.debugLog = logPath
				s.debugListener = l

				// Accept connections and forward all logs for each runhcs.exe
				// invocation
				go func() {
					for {
						c, err := s.debugListener.Accept()
						if err != nil {
							if err == winio.ErrPipeListenerClosed {
								break
							}
							log.G(ctx).WithError(err).Debug("log accept failure")
							// Logrus error locally?
							continue
						}
						fields := map[string]interface{}{
							"log-source": "runhcs",
							"task-id":    r.ID,
						}
						go forwardRunhcsLogs(ctx, c, fields)
					}
				}()
			}
		}
	}

	pidfilePath := path.Join(r.Bundle, "runhcs-pidfile.pid")
	copts := &runhcs.CreateOpts{
		IO:      io,
		PidFile: pidfilePath,
	}
	rhcs := s.newRunhcs()
	if rhcs.Debug {
		if s.shimOpts.DebugType == options.Options_FILE {
			copts.ShimLog = filepath.Join(r.Bundle, fmt.Sprintf("runhcs-shim-%s.log", r.ID))
			copts.VMLog = filepath.Join(r.Bundle, fmt.Sprintf("runhcs-vmshim-%s.log", r.ID))
		} else {
			doForwardLogs := func(source, logPipeFmt string, opt *string) error {
				pipeName := fmt.Sprintf(logPipeFmt, r.ID)
				*opt = safePipePrefix + pipeName
				l, err := winio.ListenPipe(*opt, nil)
				if err != nil {
					return err
				}
				go func() {
					defer l.Close()
					c, err := l.Accept()
					if err != nil {
						log.G(ctx).
							WithField("task-id", r.ID).
							WithError(err).
							Errorf("failed to accept %s", pipeName)
					} else {
						fields := map[string]interface{}{
							"log-source": source,
							"task-id":    r.ID,
						}
						go forwardRunhcsLogs(ctx, c, fields)
					}
				}()
				return nil
			}

			err = doForwardLogs("runhcs-shim", "runhcs-shim-log-%s", &copts.ShimLog)
			if err != nil {
				return nil, err
			}

			err = doForwardLogs("runhcs--vm-shim", "runhcs-vm-shim-log-%s", &copts.VMLog)
			if err != nil {
				return nil, err
			}
		}
	}
	err = rhcs.Create(ctx, r.ID, r.Bundle, copts)
	if err != nil {
		return nil, err
	}

	// We successfully created the process. Convert from initpid to the container process.
	pid, err := runc.ReadPidFile(pidfilePath)
	if err != nil {
		return nil, errors.Wrap(err, "failed to read container pid from pidfile")
	}

	process, err := newProcess(
		ctx,
		s,
		r.ID,
		uint32(pid),
		pr,
		r.Bundle,
		r.Stdin,
		r.Stdout,
		r.Stderr,
		r.Terminal)

	if err != nil {
		return nil, err
	}
	s.processes[r.ID] = process

	s.publisher.Publish(ctx,
		runtime.TaskCreateEventTopic,
		&eventstypes.TaskCreate{
			ContainerID: process.id,
			Bundle:      process.bundle,
			Rootfs:      r.Rootfs,
			IO: &eventstypes.TaskIO{
				Stdin:    r.Stdin,
				Stdout:   r.Stdout,
				Stderr:   r.Stderr,
				Terminal: r.Terminal,
			},
			Checkpoint: "",
			Pid:        uint32(pid),
		})

	return &taskAPI.CreateTaskResponse{
		Pid: uint32(pid),
	}, nil
}
260746
func (s *AsyncjobService) NewListAsyncJobsParams() *ListAsyncJobsParams {
	p := &ListAsyncJobsParams{}
	p.p = make(map[string]interface{})
	return p
}
947916
func (a *AskPassCredentialHelper) args(prompt string) []string {
	if len(prompt) == 0 {
		return nil
	}
	return []string{prompt}
}
1063220
func (c *Crontab) Add(id string, job Job) {
	c.commandChan <- &command{true, id, job}
}
1239505
func (h *syncHandler) Args() bool {
	defer h.mutex.RUnlock()
	h.mutex.RLock()
	return h.handler.Args()
}
1275144
func In(duration time.Duration, job cron.Job) {
	go func() {
		time.Sleep(duration)
		New(job).Run()
	}()
}
41532
func Convert_v1beta1_CronJob_To_batch_CronJob(in *v1beta1.CronJob, out *batch.CronJob, s conversion.Scope) error {
	return autoConvert_v1beta1_CronJob_To_batch_CronJob(in, out, s)
}
812428
func (r *Runtime) Create() (err error) {
	var args []string
	args = append(args, "create")
	if r.PidFile != "" {
		args = append(args, "--pid-file", r.PidFile)
	}
	if r.BundleDir != "" {
		args = append(args, "--bundle", r.BundleDir)
	}
	if r.ID != "" {
		args = append(args, r.ID)
	}
	cmd := exec.Command(r.RuntimeCommand, args...)
	id := uuid.NewV4().String()
	r.stdout, err = os.OpenFile(filepath.Join(r.bundleDir(), fmt.Sprintf("stdout-%s", id)), os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		return err
	}
	cmd.Stdout = r.stdout
	r.stderr, err = os.OpenFile(filepath.Join(r.bundleDir(), fmt.Sprintf("stderr-%s", id)), os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		return err
	}
	cmd.Stderr = r.stderr

	err = cmd.Run()
	if err == nil {
		return err
	}

	if e, ok := err.(*exec.ExitError); ok {
		stdout, stderr, _ := r.ReadStandardStreams()
		if len(stderr) == 0 {
			stderr = stdout
		}
		e.Stderr = stderr
		return e
	}
	return err
}
448313
func NewCmdCreateCronJob(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := NewCreateCronJobOptions(ioStreams)
	cmd := &cobra.Command{
		Use:     "cronjob NAME --image=image --schedule='0/5 * * * ?' -- [COMMAND] [args...]",
		Aliases: []string{"cj"},
		Short:   cronjobLong,
		Long:    cronjobLong,
		Example: cronjobExample,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(f, cmd, args))
			cmdutil.CheckErr(o.Validate())
			cmdutil.CheckErr(o.Run())
		},
	}

	o.PrintFlags.AddFlags(cmd)

	cmdutil.AddApplyAnnotationFlags(cmd)
	cmdutil.AddValidateFlags(cmd)
	cmdutil.AddDryRunFlag(cmd)
	cmd.Flags().StringVar(&o.Image, "image", o.Image, "Image name to run.")
	cmd.Flags().StringVar(&o.Schedule, "schedule", o.Schedule, "A schedule in the Cron format the job should be run with.")
	cmd.Flags().StringVar(&o.Restart, "restart", o.Restart, "job's restart policy. supported values: OnFailure, Never")

	return cmd
}
1350130
func NewCronParser() *CronParser {
	return &CronParser{
		Environment: make(map[string]string),
		CronTab:     make([]*CronEntry, 0),
	}
}
1079185
func (m *MockBuildsServer) ScheduleBuild(arg0 context.Context, arg1 *ScheduleBuildRequest) (*Build, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "ScheduleBuild", arg0, arg1)
	ret0, _ := ret[0].(*Build)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
1296938
func (c *cronJobs) Create(cronJob *v1beta1.CronJob) (result *v1beta1.CronJob, err error) {
	result = &v1beta1.CronJob{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("cronjobs").
		Body(cronJob).
		Do().
		Into(result)
	return
}
1080762
func (c *FakeCronJobs) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.CronJob, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewPatchSubresourceAction(cronjobsResource, c.ns, name, pt, data, subresources...), &v1beta1.CronJob{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1beta1.CronJob), err
}
147986
func (c *Cluster) CreateContainerPullOptsSchedulerOpts(opts docker.CreateContainerOptions, pullOpts docker.PullImageOptions, pullAuth docker.AuthConfiguration, schedulerOpts SchedulerOptions, nodes ...string) (string, *docker.Container, error) {
	var (
		addr      string
		container *docker.Container
		err       error
	)
	useScheduler := len(nodes) == 0
	maxTries := 5
	for ; maxTries > 0; maxTries-- {
		if opts.Context != nil {
			select {
			case <-opts.Context.Done():
				return "", nil, opts.Context.Err()
			default:
			}
		}
		if useScheduler {
			node, scheduleErr := c.scheduler.Schedule(c, &opts, schedulerOpts)
			if scheduleErr != nil {
				if err != nil {
					scheduleErr = fmt.Errorf("Error in scheduler after previous errors (%s) trying to create container: %s", err.Error(), scheduleErr.Error())
				}
				return addr, nil, scheduleErr
			}
			addr = node.Address
		} else {
			addr = nodes[rand.Intn(len(nodes))]
		}
		if addr == "" {
			return addr, nil, errors.New("CreateContainer needs a non empty node addr")
		}
		err = c.runHookForAddr(HookEventBeforeContainerCreate, addr)
		if err != nil {
			log.Errorf("Error in before create container hook in node %q: %s. Trying again in another node...", addr, err)
		}
		if err == nil {
			container, err = c.createContainerInNode(opts, pullOpts, pullAuth, addr)
			if err == nil {
				c.handleNodeSuccess(addr)
				break
			}
			log.Errorf("Error trying to create container in node %q: %s. Trying again in another node...", addr, err.Error())
		}
		shouldIncrementFailures := false
		isCreateContainerErr := false
		baseErr := err
		if nodeErr, ok := baseErr.(DockerNodeError); ok {
			isCreateContainerErr = nodeErr.cmd == "createContainer"
			baseErr = nodeErr.BaseError()
		}
		if urlErr, ok := baseErr.(*url.Error); ok {
			baseErr = urlErr.Err
		}
		_, isNetErr := baseErr.(net.Error)
		if isNetErr || isCreateContainerErr || baseErr == docker.ErrConnectionRefused {
			shouldIncrementFailures = true
		}
		c.handleNodeError(addr, err, shouldIncrementFailures)
		if !useScheduler {
			return addr, nil, err
		}
	}
	if err != nil {
		return addr, nil, fmt.Errorf("CreateContainer: maximum number of tries exceeded, last error: %s", err.Error())
	}
	err = c.storage().StoreContainer(container.ID, addr)
	return addr, container, err
}
118335
func Scheduler(c context.Context, cfg *pb.ProjectConfig) error {
	// Sort jobs by ID.
	sort.Slice(cfg.Job, func(i, j int) bool {
		return cfg.Job[i].Id < cfg.Job[j].Id
	})
	sort.Slice(cfg.Trigger, func(i, j int) bool {
		return cfg.Trigger[i].Id < cfg.Trigger[j].Id
	})

	// ACL set name => list of ACLs.
	aclSets := make(map[string][]*pb.Acl)
	for _, s := range cfg.AclSets {
		aclSets[s.Name] = s.Acls
	}

	// Expand ACL sets.
	for _, x := range cfg.Job {
		x.Acls = normalizeACLs(x.Acls, x.AclSets, aclSets)
		x.AclSets = nil
	}
	for _, x := range cfg.Trigger {
		x.Acls = normalizeACLs(x.Acls, x.AclSets, aclSets)
		x.AclSets = nil
	}
	cfg.AclSets = nil

	// Normalize triggers.
	for _, x := range cfg.Trigger {
		sort.Strings(x.Triggers)
		if gt := x.Gitiles; gt != nil {
			for i, r := range gt.Refs {
				if !strings.HasPrefix(r, "regexp:") {
					gt.Refs[i] = "regexp:" + regexp.QuoteMeta(r)
				}
			}
			sort.Strings(gt.Refs)
		}
	}

	return nil
}
968804
func newCronJobs(c *BatchV2alpha1Client, namespace string) *cronJobs {
	return &cronJobs{
		client: c.RESTClient(),
		ns:     namespace,
	}
}