<commit_before>// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package service

import (
	"fmt"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"go.uber.org/fx/config"
	"go.uber.org/zap"

	"github.com/pkg/errors"
)

const (
	defaultStartupWait = 10 * time.Second
)

// A ExitCallback is a function to handle a service shutdown and provide
// an exit code
type ExitCallback func(shutdown Exit) int

// Implements Manager interface
type manager struct {
	serviceCore
	locked         bool
	observer       Observer
	moduleWrappers []*moduleWrapper
	roles          map[string]bool
	stateMu        sync.Mutex

	// Shutdown fields.
	shutdownMu     sync.Mutex
	inShutdown     bool  // Protected by shutdownMu
	shutdownReason *Exit // Protected by shutdownMu
	closeChan      chan Exit
	started        bool
}

// TODO(glib): manager is both an Manager and a Host?
var _ Host = &manager{}
var _ Manager = &manager{}

// newManager creates a service Manager from a Builder.
func newManager(builder *Builder) (Manager, error) {
	m := &manager{
		// TODO: get these out of config struct instead
		moduleWrappers: []*moduleWrapper{},
		serviceCore:    serviceCore{},
	}
	m.roles = map[string]bool{}
	for _, r := range m.standardConfig.Roles {
		m.roles[r] = true
	}
	for _, opt := range builder.options {
		if optionErr := opt(m); optionErr != nil {
			return nil, errors.Wrap(optionErr, "option failed to apply")
		}
	}
	if m.configProvider == nil {
		// If the user didn't pass in a configuration provider, load the standard.
		// Bypassing standard config load is pretty much only used for tests, although it could be
		// useful in certain circumstances.
		m.configProvider = config.Load()
	}
	if err := m.setupStandardConfig(); err != nil {
		return nil, err
	}
	// Initialize metrics. If no metrics reporters were Registered, do nop
	// TODO(glib): add a logging reporter and use it by default, rather than nop
	m.setupMetrics()
	if err := m.setupLogging(); err != nil {
		return nil, err
	}
	m.setupAuthClient()
	if err := m.setupRuntimeMetricsCollector(); err != nil {
		return nil, err
	}
	m.setupVersionMetricsEmitter()
	if err := m.setupTracer(); err != nil {
		return nil, err
	}
	// if we have an observer, look for a property called "config" and load the service
	// node into that config.
	m.setupObserver()
	m.transitionState(Initialized)<commit_msg>Use roles after standard config is set (#456)<commit_after>// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package service

import (
	"fmt"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"go.uber.org/fx/config"
	"go.uber.org/zap"

	"github.com/pkg/errors"
)

const (
	defaultStartupWait = 10 * time.Second
)

// A ExitCallback is a function to handle a service shutdown and provide
// an exit code
type ExitCallback func(shutdown Exit) int

// Implements Manager interface
type manager struct {
	serviceCore
	locked         bool
	observer       Observer
	moduleWrappers []*moduleWrapper
	roles          map[string]bool
	stateMu        sync.Mutex

	// Shutdown fields.
	shutdownMu     sync.Mutex
	inShutdown     bool  // Protected by shutdownMu
	shutdownReason *Exit // Protected by shutdownMu
	closeChan      chan Exit
	started        bool
}

// TODO(glib): manager is both an Manager and a Host?
var _ Host = &manager{}
var _ Manager = &manager{}

// newManager creates a service Manager from a Builder.
func newManager(builder *Builder) (Manager, error) {
	m := &manager{
		// TODO: get these out of config struct instead
		moduleWrappers: []*moduleWrapper{},
		serviceCore:    serviceCore{},
	}
	for _, opt := range builder.options {
		if optionErr := opt(m); optionErr != nil {
			return nil, errors.Wrap(optionErr, "option failed to apply")
		}
	}
	if m.configProvider == nil {
		// If the user didn't pass in a configuration provider, load the standard.
		// Bypassing standard config load is pretty much only used for tests, although it could be
		// useful in certain circumstances.
		m.configProvider = config.Load()
	}
	if err := m.setupStandardConfig(); err != nil {
		return nil, err
	}

	m.roles = map[string]bool{}
	for _, r := range m.standardConfig.Roles {
		m.roles[r] = true
	}

	// Initialize metrics. If no metrics reporters were Registered, do nop
	// TODO(glib): add a logging reporter and use it by default, rather than nop
	m.setupMetrics()
	if err := m.setupLogging(); err != nil {
		return nil, err
	}
	m.setupAuthClient()
	if err := m.setupRuntimeMetricsCollector(); err != nil {
		return nil, err
	}
	m.setupVersionMetricsEmitter()
	if err := m.setupTracer(); err != nil {
		return nil, err
	}
	// if we have an observer, look for a property called "config" and load the service
	// node into that config.
	m.setupObserver()
	m.transitionState(Initialized)
{'fraction_non_alphanumeric': 0.0931144683323649, 'fraction_numerical': 0.002178965717606043, 'mean_word_length': 3.5, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '2712856', 'n_tokens_mistral': 2065, 'n_tokens_neox': 1951, 'n_words': 850}