// processUnits converts time unit words like "minute" into the correct millisecond multiplier
551511
func (h humanTime) processUnits(time string) (int, error) {

	if strings.TrimSpace(time) == "" {
		return 0, nil
	}

	fields := strings.Fields(time)
	if len(fields) < 2 {
		return 0, errors.New("No usable time literals found")
	}
	num, err := strconv.ParseFloat(fields[0], 10)
	if err != nil {
		num = 1
	}
	unit := h.unitRegexp.FindString(time)
	var unitNum float64
	switch unit {
	case "second":
		unitNum = Second
	case "minute":
		unitNum = Minute
	case "hour":
		unitNum = Hour
	case "day":
		unitNum = Day
	case "week":
		unitNum = Week
	case "month":
		unitNum = Month
	case "year":
		unitNum = Year
	}

	return int(unitNum * num), nil
}
33280
func (c *templateProcessor) Process(in *templatev1.Template) (*templatev1.Template, error) {
	template := &templatev1.Template{}
	err := c.client.Post().
		Namespace(c.ns).
		Resource("processedTemplates").
		Body(in).Do().Into(template)
	return template, err
}
1111461
func (t *Twemproxy) processStat(
	acc telegraf.Accumulator,
	tags map[string]string,
	data map[string]interface{},
) {
	if source, ok := data["source"]; ok {
		if val, ok := source.(string); ok {
			tags["source"] = val
		}
	}

	fields := make(map[string]interface{})
	metrics := []string{"total_connections", "curr_connections", "timestamp"}
	for _, m := range metrics {
		if value, ok := data[m]; ok {
			if val, ok := value.(float64); ok {
				fields[m] = val
			}
		}
	}
	acc.AddFields("twemproxy", fields, tags)

	for _, pool := range t.Pools {
		if poolStat, ok := data[pool]; ok {
			if data, ok := poolStat.(map[string]interface{}); ok {
				poolTags := copyTags(tags)
				poolTags["pool"] = pool
				t.processPool(acc, poolTags, data)
			}
		}
	}
}
1105047
func (p *Parser) ProcessLines(lines <-chan string, send chan<- event.Event, prefixRegex *parsers.ExtRegexp) {
	wg := sync.WaitGroup{}
	for i := 0; i < numParsers; i++ {
		wg.Add(1)
		go func() {
			for line := range lines {
				line = strings.TrimSpace(line)
				// take care of any headers on the line
				var prefixFields map[string]string
				if prefixRegex != nil {
					var prefix string
					prefix, prefixFields = prefixRegex.FindStringSubmatchMap(line)
					line = strings.TrimPrefix(line, prefix)
				}

				values, err := p.lineParser.ParseLine(line)
				// we get a bunch of errors from the parser on ArangoDB logs, skip em
				if err == nil {
					timestamp, err := p.parseTimestamp(values)
					if err != nil {
						logSkipped(line, "couldn't parse logline timestamp, skipping")
						continue
					}

					// merge the prefix fields and the parsed line contents
					for k, v := range prefixFields {
						values[k] = v
					}

					logrus.WithFields(logrus.Fields{
						"line":   line,
						"values": values,
					}).Debug("Successfully parsed line")

					// we'll be putting the timestamp in the Event
					// itself, no need to also have it in the Data
					delete(values, timestampFieldName)

					send <- event.Event{
						Timestamp: timestamp,
						Data:      values,
					}
				} else {
					logSkipped(line, "logline didn't parse, skipping.")
				}
			}
			wg.Done()
		}()
	}
	wg.Wait()
	logrus.Debug("lines channel is closed, ending arangodb processor")
}
142542
func (p *pluginControl) ProcessMetrics(metrics []core.Metric, config map[string]ctypes.ConfigValue, taskID, pluginName string, pluginVersion int) ([]core.Metric, []error) {
	// If control is not started we don't want tasks to be able to
	// go through a workflow.
	if !p.Started {
		return nil, []error{ErrControllerNotStarted}
	}
	// merge global plugin config into the config for this request
	// without over-writing the task specific config
	cfg := p.Config.Plugins.getPluginConfigDataNode(core.ProcessorPluginType, pluginName, pluginVersion).Table()
	merged := make(map[string]ctypes.ConfigValue)
	for k, v := range cfg {
		merged[k] = v
	}
	for k, v := range config {
		merged[k] = v
	}

	return p.pluginRunner.AvailablePlugins().processMetrics(metrics, pluginName, pluginVersion, merged, taskID)
}
606484
func (h *eventHub) processEvents() {
	for {
		select {
		case connection := <-h.register:
			h.connections.Register(connection)
		case connection := <-h.unregister:
			h.connections.Unregister(connection)
		case msg := <-h.broadcast:
			h.connections.Broadcast(msg)
		}
	}
}
429736
func (c *Client) HandleMeasures(time time.Time, measures ...stats.Measure) {

	// If there are no tags to add, call HandleMeasures with measures directly
	if len(c.tags) == 0 {
		c.Client.HandleMeasures(time, measures...)
		return
	}

	finalMeasures := make([]stats.Measure, len(measures))
	for i, _ := range measures {
		finalMeasures[i] = measures[i].Clone()
		finalMeasures[i].Tags = append(measures[i].Tags, c.tags...)
	}

	c.Client.HandleMeasures(time, finalMeasures...)
}
53656
func ConvertUnits(val float64, from Unit, to Unit) float64 {
	value := Unit(val)
	// convert to I unit by multiplying with the current unit
	value *= from
	// convert to the target unit by dividing by it
	if to == I {
		return math.Round(float64(value))
	}
	value /= to
	return float64(value)
}
1157144
func (a *Application) SetMinUnits(minUnits int) (err error) {
	defer errors.DeferredAnnotatef(&err, "cannot set minimum units for application %q", a)
	defer func() {
		if err == nil {
			a.doc.MinUnits = minUnits
		}
	}()
	if minUnits < 0 {
		return errors.New("cannot set a negative minimum number of units")
	}
	app := &Application{st: a.st, doc: a.doc}
	// Removing the document never fails. Racing clients trying to create the
	// document generate one failure, but the second attempt should succeed.
	// If one client tries to update the document, and a racing client removes
	// it, the former should be able to re-create the document in the second
	// attempt. If the referred-to application advanced its life cycle to a not
	// alive state, an error is returned after the first failing attempt.
	buildTxn := func(attempt int) ([]txn.Op, error) {
		if attempt > 0 {
			if err := app.Refresh(); err != nil {
				return nil, err
			}
		}
		if app.doc.Life != Alive {
			return nil, errors.New("application is no longer alive")
		}
		if minUnits == app.doc.MinUnits {
			return nil, jujutxn.ErrNoOperations
		}
		return setMinUnitsOps(app, minUnits), nil
	}
	return a.st.db().Run(buildTxn)
}
359156
func (s *BudgetPerformanceHistory) SetTimeUnit(v string) *BudgetPerformanceHistory {
	s.TimeUnit = &v
	return s
}
1372742
func (m *MaxReplicationLagModule) ProcessRecords() {
	defer m.wg.Done()

	for lagRecord := range m.lagRecords {
		m.processRecord(lagRecord)
	}
}
849110
func (s *Budget) SetTimeUnit(v string) *Budget {
	s.TimeUnit = &v
	return s
}
301058
func (wc *watchChan) processEvent(wg *sync.WaitGroup) {
	defer wg.Done()

	for {
		select {
		case e := <-wc.incomingEventChan:
			res := wc.transform(e)
			if res == nil {
				continue
			}
			if len(wc.resultChan) == outgoingBufSize {
				klog.V(3).Infof("Fast watcher, slow processing. Number of buffered events: %d."+
					"Probably caused by slow dispatching events to watchers", outgoingBufSize)
			}
			// If user couldn't receive results fast enough, we also block incoming events from watcher.
			// Because storing events in local will cause more memory usage.
			// The worst case would be closing the fast watcher.
			select {
			case wc.resultChan <- *res:
			case <-wc.ctx.Done():
				return
			}
		case <-wc.ctx.Done():
			return
		}
	}
}
398222
func (m *upgradeSeriesMachine) Units() ([]UpgradeSeriesUnit, error) {
	units, err := m.Machine.Units()
	if err != nil {
		return nil, errors.Trace(err)
	}

	wrapped := make([]UpgradeSeriesUnit, len(units))
	for i, u := range units {
		wrapped[i] = u
	}
	return wrapped, nil
}
98358
func timeToEpochMilliseconds(t time.Time) int64 {
	return t.UnixNano() / int64(time.Millisecond)
}
104101
func Pids() ([]int32, error) {
	var ret []int32
	pid, err := process.Pids()
	if err != nil {
		return ret, err
	}

	return pid, err
}
733309
func (st *State) MetricBatchesForUnit(unit string) ([]MetricBatch, error) {
	_, err := st.Unit(unit)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return st.queryMetricBatches(bson.M{"unit": unit})
}