<commit_before>// Copyright (c) 2017 Cisco and/or its affiliates.
//
// 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.

package prometheus

import (
	"errors"
	"github.com/ligato/cn-infra/flavors/local"
	"github.com/ligato/cn-infra/rpc/rest"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/unrolled/render"
	"net/http"
	"strings"
	"sync"
)

// DefaultMetricsPath default Prometheus metrics URL
const DefaultRegistry = "/metrics"

var (
	// PathInvalidFormatError is returned if the path doesn't start with slash
	PathInvalidFormatError = errors.New("path is invalid, it must start with '/' character")
	// PathAlreadyRegistryError is returned on attempt to register a path used by a registry
	PathAlreadyRegistryError = errors.New("registry with the path is already registered")
	// RegistryNotFoundError is returned on attempt to use register that has not been created
	RegistryNotFoundError = errors.New("registry was not found")
)

// Plugin struct holds all plugin-related data.
type Plugin struct {
	Deps
	sync.Mutex
	// regs is a map of URL path(symbolic names) to registries. Registries group metrics and can be exposed at different urls.
	regs map[string]*registry
}

// Deps lists dependencies of the plugin.
type Deps struct {
	local.PluginInfraDeps // inject
	// HTTP server used to expose metrics
	HTTP rest.HTTPHandlers // inject
}

type registry struct {
	prometheus.Gatherer
	prometheus.Registerer
	// httpOpts applied when exposing registry using http
	httpOpts promhttp.HandlerOpts
}

// Init initializes the internal structures
func (p *Plugin) Init() (err error) {

	p.regs = map[string]*registry{}

	// add default registry
	p.regs[DefaultRegistry] = &registry{
		Gatherer:   prometheus.DefaultGatherer,
		Registerer: prometheus.DefaultRegisterer,
	}

	return nil
}

// AfterInit registers HTTP handlers.
func (p *Plugin) AfterInit() error {
	if p.HTTP != nil {
		for path, reg := range p.regs {
			p.HTTP.RegisterHTTPHandler(path, p.createHandlerHandler(reg.Gatherer), "GET")
			p.Log.Infof("Serving %s on port %d", path, p.HTTP.GetPort())

		}
	} else {
		p.Log.Info("Unable to register Prometheus metrics handlers, HTTP is nil")
	}

	return nil<commit_msg>Add missing lock in prometheus plugin<commit_after>// Copyright (c) 2017 Cisco and/or its affiliates.
//
// 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.

package prometheus

import (
	"errors"
	"github.com/ligato/cn-infra/flavors/local"
	"github.com/ligato/cn-infra/rpc/rest"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/unrolled/render"
	"net/http"
	"strings"
	"sync"
)

// DefaultMetricsPath default Prometheus metrics URL
const DefaultRegistry = "/metrics"

var (
	// PathInvalidFormatError is returned if the path doesn't start with slash
	PathInvalidFormatError = errors.New("path is invalid, it must start with '/' character")
	// PathAlreadyRegistryError is returned on attempt to register a path used by a registry
	PathAlreadyRegistryError = errors.New("registry with the path is already registered")
	// RegistryNotFoundError is returned on attempt to use register that has not been created
	RegistryNotFoundError = errors.New("registry was not found")
)

// Plugin struct holds all plugin-related data.
type Plugin struct {
	Deps
	sync.Mutex
	// regs is a map of URL path(symbolic names) to registries. Registries group metrics and can be exposed at different urls.
	regs map[string]*registry
}

// Deps lists dependencies of the plugin.
type Deps struct {
	local.PluginInfraDeps // inject
	// HTTP server used to expose metrics
	HTTP rest.HTTPHandlers // inject
}

type registry struct {
	prometheus.Gatherer
	prometheus.Registerer
	// httpOpts applied when exposing registry using http
	httpOpts promhttp.HandlerOpts
}

// Init initializes the internal structures
func (p *Plugin) Init() (err error) {

	p.regs = map[string]*registry{}

	// add default registry
	p.regs[DefaultRegistry] = &registry{
		Gatherer:   prometheus.DefaultGatherer,
		Registerer: prometheus.DefaultRegisterer,
	}

	return nil
}

// AfterInit registers HTTP handlers.
func (p *Plugin) AfterInit() error {
	if p.HTTP != nil {
		p.Lock()
		defer p.Unlock()
		for path, reg := range p.regs {
			p.HTTP.RegisterHTTPHandler(path, p.createHandlerHandler(reg.Gatherer), "GET")
			p.Log.Infof("Serving %s on port %d", path, p.HTTP.GetPort())

		}
	} else {
		p.Log.Info("Unable to register Prometheus metrics handlers, HTTP is nil")
	}

	return nil
{'fraction_non_alphanumeric': 0.09583632447954056, 'fraction_numerical': 0.002871500358937545, 'mean_word_length': 4.034327009936766, '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': '4926059', 'n_tokens_mistral': 1703, 'n_tokens_neox': 1627, 'n_words': 597}