// Estimate runtime for job
356995
func (m *Machine) ETA() time.Duration {
	lastTool := -1
	lastToolSuggestion := -1
	var eta time.Duration
	var lx, ly, lz float64
	for _, pos := range m.Positions {
		if pos.State.ToolIndex != lastTool {
			if pos.State.ToolIndex == lastToolSuggestion {
				eta += 5 * time.Second
			} else {
				eta += 10 * time.Second
			}
		}
		lastTool = pos.State.ToolIndex
		lastToolSuggestion = pos.State.NextToolIndex

		feed := pos.State.Feedrate
		if feed <= 0 {
			// Just to use something...
			feed = 300
		}

		// Convert from minutes to microseconds
		feed /= 60000000

		switch pos.State.MoveMode {
		case MoveModeNone:
			continue
		case MoveModeRapid:
			// This is silly, but it gives something to calculate with
			feed *= 8
		case MoveModeDwell:
			eta += time.Duration(pos.State.DwellTime) * time.Second
			continue
		}
		dx, dy, dz := pos.X-lx, pos.Y-ly, pos.Z-lz
		lx, ly, lz = pos.X, pos.Y, pos.Z

		dist := math.Sqrt(math.Pow(dx, 2) + math.Pow(dy, 2) + math.Pow(dz, 2))
		eta += time.Duration(dist/feed) * time.Microsecond
	}
	return eta
}
518236
func getRandomJobAlloc(client *api.Client, jobID string) (string, error) {
	var runningAllocs []*api.AllocationListStub
	allocs, _, err := client.Jobs().Allocations(jobID, false, nil)

	// Check that the job actually has allocations
	if len(allocs) == 0 {
		return "", fmt.Errorf("job %q doesn't exist or it has no allocations", jobID)
	}

	for _, v := range allocs {
		if v.ClientStatus == "running" {
			runningAllocs = append(runningAllocs, v)
		}
	}
	// If we don't have any allocations running, use dead allocations
	if len(runningAllocs) < 1 {
		runningAllocs = allocs
	}

	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	allocID := runningAllocs[r.Intn(len(runningAllocs))].ID
	return allocID, err
}
246220
func RunningTime(pid int) int64 {
	upTimeFile, err := os.Open("/proc/uptime")
	if err != nil {
		panic(err)
	}
	defer upTimeFile.Close()
	bs, err := ioutil.ReadAll(upTimeFile)
	if err != nil {
		panic(err)
	}
	//uptime is first paramater in uptime file
	upTime, err := strconv.ParseFloat(strings.Split(string(bs), " ")[0], 64)
	if err != nil {
		panic(err)
	}
	stat, err := os.Open("/proc/" + strconv.Itoa(pid) + "/stat")
	if err != nil {
		panic(err)
	}
	defer stat.Close()
	bs, err = ioutil.ReadAll(stat)
	if err != nil {
		panic(err)
	}
	//startTime is 22nd paramater in the stat file
	startTime, err := strconv.ParseInt(strings.Split(string(bs), " ")[21], 10, 64)
	if err != nil {
		panic(err)
	}
	return int64(upTime*1000) - int64(startTime*1000)/sc_clk_tck
}
166125
func (m *MockRenderedJob) Job() job.Job {
	ret := m.ctrl.Call(m, "Job")
	ret0, _ := ret[0].(job.Job)
	return ret0
}
859938
func execTimeout(f JobFunc, job Job, timeout time.Duration) (r *result) {
	rslt := make(chan *result)
	defer close(rslt)
	go func() {
		defer func() { recover() }()
		d, e := f(job)
		rslt <- &result{data: d, err: e}
	}()
	select {
	case r = <-rslt:
	case <-time.After(timeout):
		return &result{err: ErrTimeOut}
	}
	return r
}
98872
func (t *Task) Canonicalize(job *Job, tg *TaskGroup) {
	// Ensure that an empty and nil map are treated the same to avoid scheduling
	// problems since we use reflect DeepEquals.
	if len(t.Meta) == 0 {
		t.Meta = nil
	}
	if len(t.Config) == 0 {
		t.Config = nil
	}
	if len(t.Env) == 0 {
		t.Env = nil
	}

	for _, service := range t.Services {
		service.Canonicalize(job.Name, tg.Name, t.Name)
	}

	// If Resources are nil initialize them to defaults, otherwise canonicalize
	if t.Resources == nil {
		t.Resources = DefaultResources()
	} else {
		t.Resources.Canonicalize()
	}

	// Set the default timeout if it is not specified.
	if t.KillTimeout == 0 {
		t.KillTimeout = DefaultKillTimeout
	}

	if t.Vault != nil {
		t.Vault.Canonicalize()
	}

	for _, template := range t.Templates {
		template.Canonicalize()
	}
}
598978
func (s *Server) monitorRuntime() {
	// Disable metrics when poll interval is zero.
	if s.metricInterval <= 0 {
		return
	}

	var m runtime.MemStats
	ticker := time.NewTicker(s.metricInterval)
	defer ticker.Stop()

	defer s.gcNotifier.Close()

	s.logger.Printf("runtime stats initializing (%s interval)", s.metricInterval)

	for {
		// Wait for tick or a close.
		select {
		case <-s.closing:
			return
		case <-s.gcNotifier.AfterGC():
			// GC just ran.
			s.holder.Stats.Count("garbage_collection", 1, 1.0)
		case <-ticker.C:
		}

		// Record the number of go routines.
		s.holder.Stats.Gauge("goroutines", float64(runtime.NumGoroutine()), 1.0)

		openFiles, err := countOpenFiles()
		// Open File handles.
		if err == nil {
			s.holder.Stats.Gauge("OpenFiles", float64(openFiles), 1.0)
		}

		// Runtime memory metrics.
		runtime.ReadMemStats(&m)
		s.holder.Stats.Gauge("HeapAlloc", float64(m.HeapAlloc), 1.0)
		s.holder.Stats.Gauge("HeapInuse", float64(m.HeapInuse), 1.0)
		s.holder.Stats.Gauge("StackInuse", float64(m.StackInuse), 1.0)
		s.holder.Stats.Gauge("Mallocs", float64(m.Mallocs), 1.0)
		s.holder.Stats.Gauge("Frees", float64(m.Frees), 1.0)
	}
}
447650
func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) {
	b.mu.Lock()
	defer b.mu.Unlock()

	// Determine the lowest and highest possible gas limits to binary search in between
	var (
		lo  uint64 = params.TxGas - 1
		hi  uint64
		cap uint64
	)
	if call.Gas >= params.TxGas {
		hi = call.Gas
	} else {
		hi = b.pendingBlock.GasLimit()
	}
	cap = hi

	// Create a helper to check if a gas allowance results in an executable transaction
	executable := func(gas uint64) bool {
		call.Gas = gas

		snapshot := b.pendingState.Snapshot()
		_, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
		b.pendingState.RevertToSnapshot(snapshot)

		if err != nil || failed {
			return false
		}
		return true
	}
	// Execute the binary search and hone in on an executable gas limit
	for lo+1 < hi {
		mid := (hi + lo) / 2
		if !executable(mid) {
			lo = mid
		} else {
			hi = mid
		}
	}
	// Reject the transaction as invalid if it still fails at the highest allowance
	if hi == cap {
		if !executable(hi) {
			return 0, errGasEstimationFailed
		}
	}
	return hi, nil
}
212282
func (conf *Config) GetRuntime(name string) *types.Runtime {
	conf.Lock()
	defer conf.Unlock()
	if rt, ok := conf.Runtimes[name]; ok {
		return &rt
	}
	return nil
}
1286403
func CaptureRuntimeMemStats(r Registry, d time.Duration) {
	for range time.Tick(d) {
		CaptureRuntimeMemStatsOnce(r)
	}
}
1215995
func (d *Daemon) queueJob(do jobFunc) job.ID {
	id := job.ID(guid.New())
	enqueuedAt := time.Now()
	d.Jobs.Enqueue(&job.Job{
		ID: id,
		Do: func(logger log.Logger) error {
			queueDuration.Observe(time.Since(enqueuedAt).Seconds())
			_, err := d.executeJob(id, do, logger)
			if err != nil {
				return err
			}
			return nil
		},
	})
	queueLength.Set(float64(d.Jobs.Len()))
	d.JobStatusCache.SetStatus(id, job.Status{StatusString: job.StatusQueued})
	return id
}
270351
func (m *MockInstallation) Job() installation.InstalledJob {
	ret := m.ctrl.Call(m, "Job")
	ret0, _ := ret[0].(installation.InstalledJob)
	return ret0
}
621206
func (s *InstallationSettings) FindJobInstanceCount(productID string, jobID string) int {
	count := 0

	for _, product := range s.Products {
		identifier := product.Identifier
		if identifier == productID {
			for _, job := range product.Jobs {
				if jobID == job.Identifier {
					if job.Instances != nil {
						count = job.Instances[0].Value
					} else {
						count = job.Partitions[0].InstanceCount + count
					}
				}
			}
		}
	}
	return count
}
177705
func (job *AnalyzeJob) Update(rowCount int64) {
	now := time.Now()
	job.Mutex.Lock()
	job.RowCount += rowCount
	job.updateTime = now
	job.Mutex.Unlock()
}
523154
func (p compiledPackageApplierProvider) JobSpecific(jobName string) Applier {
	enablePath := path.Join(p.jobSpecificEnablePath, jobName)
	packagesBc := boshbc.NewFileBundleCollection(
		p.installPath,
		enablePath,
		p.name,
		os.FileMode(0755),
		p.fs,
		p.timeProvider,
		p.compressor,
		p.logger,
	)
	return NewCompiledPackageApplier(packagesBc, false, p.blobstore, p.fs, p.logger)
}
282608
func (d *namespacedResourcesDeleter) estimateGracefulTerminationForPods(ns string) (int64, error) {
	klog.V(5).Infof("namespace controller - estimateGracefulTerminationForPods - namespace %s", ns)
	estimate := int64(0)
	podsGetter := d.podsGetter
	if podsGetter == nil || reflect.ValueOf(podsGetter).IsNil() {
		return estimate, fmt.Errorf("unexpected: podsGetter is nil. Cannot estimate grace period seconds for pods")
	}
	items, err := podsGetter.Pods(ns).List(metav1.ListOptions{})
	if err != nil {
		return estimate, err
	}
	for i := range items.Items {
		pod := items.Items[i]
		// filter out terminal pods
		phase := pod.Status.Phase
		if v1.PodSucceeded == phase || v1.PodFailed == phase {
			continue
		}
		if pod.Spec.TerminationGracePeriodSeconds != nil {
			grace := *pod.Spec.TerminationGracePeriodSeconds
			if grace > estimate {
				estimate = grace
			}
		}
	}
	return estimate, nil
}
987944
func (p *ReadOnlySchedulerClient) PopulateJobConfig(ctx context.Context, description *JobConfiguration) (r *Response, err error) {
  var _args68 ReadOnlySchedulerPopulateJobConfigArgs
  _args68.Description = description
  var _result69 ReadOnlySchedulerPopulateJobConfigResult
  if err = p.Client_().Call(ctx, "populateJobConfig", &_args68, &_result69); err != nil {
    return
  }
  return _result69.GetSuccess(), nil
}