<commit_before>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This file defines functions to work with the metrics generated from the
// external probe process output.

package payload

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/google/cloudprober/logger"
	"github.com/google/cloudprober/metrics"
	configpb "github.com/google/cloudprober/metrics/payload/proto"
)

// Parser encapsulates the config for parsing payloads to metrics.
type Parser struct {
	defaultEM *metrics.EventMetrics
	aggregate bool
	l         *logger.Logger
}

// NewParser returns a new payload parser, based on the config provided.
func NewParser(opts *configpb.OutputMetricsOptions, ptype, probeName string, defaultKind metrics.Kind, l *logger.Logger) (*Parser, error) {
	parser := &Parser{
		aggregate: opts.GetAggregateInCloudprober(),
		l:         l,
	}

	em := metrics.NewEventMetrics(time.Now()).
		AddLabel("ptype", ptype).
		AddLabel("probe", probeName)

	switch opts.GetMetricsKind() {
	case configpb.OutputMetricsOptions_CUMULATIVE:
		em.Kind = metrics.CUMULATIVE
	case configpb.OutputMetricsOptions_GAUGE:
		if opts.GetAggregateInCloudprober() {
			return nil, errors.New("payload.NewParser: invalid config, GAUGE metrics should not have aggregate_in_cloudprober enabled")
		}
		em.Kind = metrics.GAUGE
	case configpb.OutputMetricsOptions_UNDEFINED:
		em.Kind = defaultKind
	}

	// Labels are specified in the probe config.
	if opts.GetAdditionalLabels() != "" {
		for _, label := range strings.Split(opts.GetAdditionalLabels(), ",") {
			labelKV := strings.Split(label, "=")
			if len(labelKV) != 2 {
				return nil, fmt.Errorf("payload.NewParser: invlaid config, wrong label format: %v", labelKV)
			}
			em.AddLabel(labelKV[0], labelKV[1])
		}
	}

	// If there are any distribution metrics, build them now itself.
	for name, distMetric := range opts.GetDistMetric() {
		d, err := metrics.NewDistributionFromProto(distMetric)
		if err != nil {
			return nil, err
		}
		em.AddMetric(name, d)
	}

	parser.defaultEM = em

	return parser, nil
}

func updateMetricValue(mv metrics.Value, val string) error {
	// If a distribution, process it through processDistValue.
	if mVal, ok := mv.(*metrics.Distribution); ok {
		if err := processDistValue(mVal, val); err != nil {
			return fmt.Errorf("error parsing distribution value (%s): %v", val, err)
		}
	}<commit_msg>When updating a metric value for a distribution always return after parsing the distribution value.<commit_after>// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This file defines functions to work with the metrics generated from the
// external probe process output.

package payload

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/google/cloudprober/logger"
	"github.com/google/cloudprober/metrics"
	configpb "github.com/google/cloudprober/metrics/payload/proto"
)

// Parser encapsulates the config for parsing payloads to metrics.
type Parser struct {
	defaultEM *metrics.EventMetrics
	aggregate bool
	l         *logger.Logger
}

// NewParser returns a new payload parser, based on the config provided.
func NewParser(opts *configpb.OutputMetricsOptions, ptype, probeName string, defaultKind metrics.Kind, l *logger.Logger) (*Parser, error) {
	parser := &Parser{
		aggregate: opts.GetAggregateInCloudprober(),
		l:         l,
	}

	em := metrics.NewEventMetrics(time.Now()).
		AddLabel("ptype", ptype).
		AddLabel("probe", probeName)

	switch opts.GetMetricsKind() {
	case configpb.OutputMetricsOptions_CUMULATIVE:
		em.Kind = metrics.CUMULATIVE
	case configpb.OutputMetricsOptions_GAUGE:
		if opts.GetAggregateInCloudprober() {
			return nil, errors.New("payload.NewParser: invalid config, GAUGE metrics should not have aggregate_in_cloudprober enabled")
		}
		em.Kind = metrics.GAUGE
	case configpb.OutputMetricsOptions_UNDEFINED:
		em.Kind = defaultKind
	}

	// Labels are specified in the probe config.
	if opts.GetAdditionalLabels() != "" {
		for _, label := range strings.Split(opts.GetAdditionalLabels(), ",") {
			labelKV := strings.Split(label, "=")
			if len(labelKV) != 2 {
				return nil, fmt.Errorf("payload.NewParser: invlaid config, wrong label format: %v", labelKV)
			}
			em.AddLabel(labelKV[0], labelKV[1])
		}
	}

	// If there are any distribution metrics, build them now itself.
	for name, distMetric := range opts.GetDistMetric() {
		d, err := metrics.NewDistributionFromProto(distMetric)
		if err != nil {
			return nil, err
		}
		em.AddMetric(name, d)
	}

	parser.defaultEM = em

	return parser, nil
}

func updateMetricValue(mv metrics.Value, val string) error {
	// If a distribution, process it through processDistValue.
	if mVal, ok := mv.(*metrics.Distribution); ok {
		if err := processDistValue(mVal, val); err != nil {
			return fmt.Errorf("error parsing distribution value (%s): %v", val, err)
		}
		return nil
	}
{'fraction_non_alphanumeric': 0.10803977751559077, 'fraction_numerical': 0.003708073487274566, 'mean_word_length': 4.003372681281619, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5494403', 'n_tokens_mistral': 1891, 'n_tokens_neox': 1775, 'n_words': 588}