// Initiailizing an unchanged saved backend
961136
func (m *Meta) backend_C_r_S_unchanged(c *configs.Backend, cHash int, sMgr *state.LocalState) (backend.Backend, tfdiags.Diagnostics) {
	var diags tfdiags.Diagnostics

	s := sMgr.State()

	// it's possible for a backend to be unchanged, and the config itself to
	// have changed by moving a parameter from the config to `-backend-config`
	// In this case we only need to update the Hash.
	if c != nil && s.Backend.Hash != uint64(cHash) {
		s.Backend.Hash = uint64(cHash)
		if err := sMgr.WriteState(s); err != nil {
			diags = diags.Append(err)
			return nil, diags
		}
	}

	// Get the backend
	f := backendInit.Backend(s.Backend.Type)
	if f == nil {
		diags = diags.Append(fmt.Errorf(strings.TrimSpace(errBackendSavedUnknown), s.Backend.Type))
		return nil, diags
	}
	b := f()

	// The configuration saved in the working directory state file is used
	// in this case, since it will contain any additional values that
	// were provided via -backend-config arguments on terraform init.
	schema := b.ConfigSchema()
	configVal, err := s.Backend.Config(schema)
	if err != nil {
		diags = diags.Append(tfdiags.Sourceless(
			tfdiags.Error,
			"Failed to decode current backend config",
			fmt.Sprintf("The backend configuration created by the most recent run of \"terraform init\" could not be decoded: %s. The configuration may have been initialized by an earlier version that used an incompatible configuration structure. Run \"terraform init -reconfigure\" to force re-initialization of the backend.", err),
		))
		return nil, diags
	}

	// Validate the config and then configure the backend
	newVal, validDiags := b.PrepareConfig(configVal)
	diags = diags.Append(validDiags)
	if validDiags.HasErrors() {
		return nil, diags
	}
	configVal = newVal

	configDiags := b.Configure(configVal)
	diags = diags.Append(configDiags)
	if configDiags.HasErrors() {
		return nil, diags
	}

	return b, diags
}
145888
func (a *Authenticator) checkInitialized() (bool, error) {
	if a.err != nil || a.baseToken != nil {
		return true, a.err
	}
	return false, nil
}
574790
func (r *Runner) init() {
	r.initOnce.Do(func() {
		r.workC = make(chan WorkItem)
		r.dispatchFinishedC = make(chan struct{})

		go r.dispatchLoop(r.Sustained, r.Maximum)
	})
}
305767
func (pvcr *persistentVolumeClaimResize) ValidateInitialization() error {
	if pvcr.scLister == nil {
		return fmt.Errorf("missing storageclass lister")
	}
	return nil
}
940361
func Init(ctx context.Context, hc discovery.HealthCheck, serv srvtopo.Server, cell string, retryCount int, tabletTypesToWait []topodatapb.TabletType) *VTGate {
	if rpcVTGate != nil {
		log.Fatalf("VTGate already initialized")
	}

	// vschemaCounters needs to be initialized before planner to
	// catch the initial load stats.
	vschemaCounters = stats.NewCountersWithSingleLabel("VtgateVSchemaCounts", "Vtgate vschema counts", "changes")

	// Build objects from low to high level.
	// Start with the gateway. If we can't reach the topology service,
	// we can't go on much further, so we log.Fatal out.
	var gw gateway.Gateway
	if !*disableLocalGateway {
		gw = gateway.GetCreator()(ctx, hc, serv, cell, retryCount)
		gw.RegisterStats()
		if err := gateway.WaitForTablets(gw, tabletTypesToWait); err != nil {
			log.Fatalf("gateway.WaitForTablets failed: %v", err)
		}
	}

	// Check we have something to do.
	if gw == nil {
		log.Fatalf("'-disable_local_gateway' cannot be specified if 'l2vtgate_addrs' is also empty, otherwise this vtgate has no backend")
	}

	// If we want to filter keyspaces replace the srvtopo.Server with a
	// filtering server
	if len(gateway.KeyspacesToWatch) > 0 {
		log.Infof("Keyspace filtering enabled, selecting %v", gateway.KeyspacesToWatch)
		var err error
		serv, err = srvtopo.NewKeyspaceFilteringServer(serv, gateway.KeyspacesToWatch)
		if err != nil {
			log.Fatalf("Unable to construct SrvTopo server: %v", err.Error())
		}
	}

	tc := NewTxConn(gw, getTxMode())
	// ScatterConn depends on TxConn to perform forced rollbacks.
	sc := NewScatterConn("VttabletCall", tc, gw, hc)
	srvResolver := srvtopo.NewResolver(serv, gw, cell)
	resolver := NewResolver(srvResolver, serv, cell, sc)

	rpcVTGate = &VTGate{
		executor: NewExecutor(ctx, serv, cell, "VTGateExecutor", resolver, *normalizeQueries, *streamBufferSize, *queryPlanCacheSize, *legacyAutocommit),
		resolver: resolver,
		txConn:   tc,
		gw:       gw,
		timings: stats.NewMultiTimings(
			"VtgateApi",
			"VtgateApi timings",
			[]string{"Operation", "Keyspace", "DbType"}),
		rowsReturned: stats.NewCountersWithMultiLabels(
			"VtgateApiRowsReturned",
			"Rows returned through the VTgate API",
			[]string{"Operation", "Keyspace", "DbType"}),

		logExecute:                  logutil.NewThrottledLogger("Execute", 5*time.Second),
		logStreamExecute:            logutil.NewThrottledLogger("StreamExecute", 5*time.Second),
		logExecuteShards:            logutil.NewThrottledLogger("ExecuteShards", 5*time.Second),
		logExecuteKeyspaceIds:       logutil.NewThrottledLogger("ExecuteKeyspaceIds", 5*time.Second),
		logExecuteKeyRanges:         logutil.NewThrottledLogger("ExecuteKeyRanges", 5*time.Second),
		logExecuteEntityIds:         logutil.NewThrottledLogger("ExecuteEntityIds", 5*time.Second),
		logExecuteBatchShards:       logutil.NewThrottledLogger("ExecuteBatchShards", 5*time.Second),
		logExecuteBatchKeyspaceIds:  logutil.NewThrottledLogger("ExecuteBatchKeyspaceIds", 5*time.Second),
		logStreamExecuteKeyspaceIds: logutil.NewThrottledLogger("StreamExecuteKeyspaceIds", 5*time.Second),
		logStreamExecuteKeyRanges:   logutil.NewThrottledLogger("StreamExecuteKeyRanges", 5*time.Second),
		logStreamExecuteShards:      logutil.NewThrottledLogger("StreamExecuteShards", 5*time.Second),
		logUpdateStream:             logutil.NewThrottledLogger("UpdateStream", 5*time.Second),
		logMessageStream:            logutil.NewThrottledLogger("MessageStream", 5*time.Second),
	}

	errorCounts = stats.NewCountersWithMultiLabels("VtgateApiErrorCounts", "Vtgate API error counts per error type", []string{"Operation", "Keyspace", "DbType", "Code"})

	qpsByOperation = stats.NewRates("QPSByOperation", stats.CounterForDimension(rpcVTGate.timings, "Operation"), 15, 1*time.Minute)
	qpsByKeyspace = stats.NewRates("QPSByKeyspace", stats.CounterForDimension(rpcVTGate.timings, "Keyspace"), 15, 1*time.Minute)
	qpsByDbType = stats.NewRates("QPSByDbType", stats.CounterForDimension(rpcVTGate.timings, "DbType"), 15*60/5, 5*time.Second)

	errorsByOperation = stats.NewRates("ErrorsByOperation", stats.CounterForDimension(errorCounts, "Operation"), 15, 1*time.Minute)
	errorsByKeyspace = stats.NewRates("ErrorsByKeyspace", stats.CounterForDimension(errorCounts, "Keyspace"), 15, 1*time.Minute)
	errorsByDbType = stats.NewRates("ErrorsByDbType", stats.CounterForDimension(errorCounts, "DbType"), 15, 1*time.Minute)
	errorsByCode = stats.NewRates("ErrorsByCode", stats.CounterForDimension(errorCounts, "Code"), 15, 1*time.Minute)

	warnings = stats.NewCountersWithSingleLabel("VtGateWarnings", "Vtgate warnings", "type", "IgnoredSet")

	servenv.OnRun(func() {
		for _, f := range RegisterVTGates {
			f(rpcVTGate)
		}
	})
	rpcVTGate.registerDebugHealthHandler()
	err := initQueryLogger(rpcVTGate)
	if err != nil {
		log.Fatalf("error initializing query logger: %v", err)
	}

	initAPI(ctx, hc)

	return rpcVTGate
}
829711
func (u *uploader) init() {
	if u.cfg.Concurrency == 0 {
		u.cfg.Concurrency = DefaultUploadConcurrency
	}
	if u.cfg.PartSize == 0 {
		u.cfg.PartSize = DefaultUploadPartSize
	}
	if u.cfg.MaxUploadParts == 0 {
		u.cfg.MaxUploadParts = MaxUploadParts
	}

	u.bufferPool = sync.Pool{
		New: func() interface{} { return make([]byte, u.cfg.PartSize) },
	}

	// Try to get the total size for some optimizations
	u.initSize()
}
165794
func init() {
	wallet.UseLogger(walletLog)
	wtxmgr.UseLogger(txmgrLog)
	chain.UseLogger(chainLog)
	rpcclient.UseLogger(chainLog)
	rpcserver.UseLogger(grpcLog)
	legacyrpc.UseLogger(legacyRPCLog)
	neutrino.UseLogger(btcnLog)
}
709261
func init() {

	docsProvider := func() map[string]interface{} {
		docs := make(map[string]interface{})

		var chromaLexers []interface{}

		sort.Sort(lexers.Registry.Lexers)

		for _, l := range lexers.Registry.Lexers {

			config := l.Config()

			var filenames []string
			filenames = append(filenames, config.Filenames...)
			filenames = append(filenames, config.AliasFilenames...)

			aliases := config.Aliases

			for _, filename := range filenames {
				alias := strings.TrimSpace(strings.TrimPrefix(filepath.Ext(filename), "."))
				if alias != "" {
					aliases = append(aliases, alias)
				}
			}

			sort.Strings(aliases)
			aliases = UniqueStrings(aliases)

			lexerEntry := struct {
				Name    string
				Aliases []string
			}{
				config.Name,
				aliases,
			}

			chromaLexers = append(chromaLexers, lexerEntry)

			docs["lexers"] = chromaLexers
		}
		return docs

	}

	docshelper.AddDocProvider("chroma", docsProvider)
}
1169906
func (ci *containerInitialiser) Initialise() error {
	localSeries, err := hostSeries()
	if err != nil {
		return errors.Trace(err)
	}

	if err := ensureDependencies(localSeries); err != nil {
		return errors.Trace(err)
	}
	err = configureLXDBridge()
	if err != nil {
		return errors.Trace(err)
	}
	proxies := proxy.DetectProxies()
	err = ConfigureLXDProxies(proxies)
	if err != nil {
		return errors.Trace(err)
	}

	// LXD init is only run on Xenial and later.
	if localSeries == "trusty" {
		return nil
	}

	output, err := ci.getExecCommand(
		"lxd",
		"init",
		"--auto",
	).CombinedOutput()

	if err == nil {
		return nil
	}

	out := string(output)
	if strings.Contains(out, "You have existing containers or images. lxd init requires an empty LXD.") {
		// this error means we've already run lxd init. Just ignore it.
		return nil
	}

	return errors.Annotate(err, "running lxd init --auto: "+out)
}
1214256
func Init(backendAddress, advertiseAddress string, clusterOpts map[string]string) (Reloader, error) {
	heartbeat, backend, err := parseDiscoveryOptions(backendAddress, clusterOpts)
	if err != nil {
		return nil, err
	}

	reloader := &daemonDiscoveryReloader{
		backend: backend,
		ticker:  time.NewTicker(heartbeat),
		term:    make(chan bool),
		readyCh: make(chan struct{}),
	}
	// We call Register() on the discovery backend in a loop for the whole lifetime of the daemon,
	// but we never actually Watch() for nodes appearing and disappearing for the moment.
	go reloader.advertiseHeartbeat(advertiseAddress)
	return reloader, nil
}
747149
func (l loader) Init(ctx context.Context, path, username, email string) (backend.RCS, error) {
	return Init(ctx, path)
}
1100059
func init() {
	dcrsqlite.UseLogger(sqliteLog)
	dcrpg.UseLogger(postgresqlLog)
	stakedb.UseLogger(stakedbLog)
	blockdata.UseLogger(BlockdataLog)
	rpcclient.UseLogger(clientLog)
	rpcutils.UseLogger(clientLog)
	mempool.UseLogger(mempoolLog)
	explorer.UseLogger(expLog)
	api.UseLogger(apiLog)
	insight.UseLogger(iapiLog)
	middleware.UseLogger(apiLog)
	notify.UseLogger(notifyLog)
	pubsub.UseLogger(pubsubLog)
	exchanges.UseLogger(xcBotLog)
	agendas.UseLogger(agendasLog)
	politeia.UseLogger(proposalsLog)
}
552981
func init() {
	DefaultCallback.Delete().Register("gorm:begin_transaction", beginTransactionCallback)
	DefaultCallback.Delete().Register("gorm:before_delete", beforeDeleteCallback)
	DefaultCallback.Delete().Register("gorm:delete", deleteCallback)
	DefaultCallback.Delete().Register("gorm:after_delete", afterDeleteCallback)
	DefaultCallback.Delete().Register("gorm:commit_or_rollback_transaction", commitOrRollbackTransactionCallback)
}
1267907
func (p *Plugin) Init() error {
	// write initial status data into ETCD
	p.agentStat = &status.AgentStatus{
		State:        status.OperationalState_INIT,
		BuildVersion: agent.BuildVersion,
		BuildDate:    agent.BuildDate,
		CommitHash:   agent.CommitHash,
		StartTime:    time.Now().Unix(),
		LastChange:   time.Now().Unix(),
	}

	// initial empty interface status
	p.interfaceStat = &status.InterfaceStats{}

	// init pluginStat map
	p.pluginStat = make(map[string]*status.PluginStatus)

	// init map with plugin state probes
	p.pluginProbe = make(map[string]PluginStateProbe)

	// prepare context for all go routines
	p.ctx, p.cancel = context.WithCancel(context.Background())

	return nil
}
214416
func init() {
	gob.Register(Store{})
	gob.Register(Entry{})
	gob.Register(time.Time{})
}
871220
func (e *DefaultEndorsement) Init(dependencies ...Dependency) error {
	for _, dep := range dependencies {
		sIDFetcher, isSigningIdentityFetcher := dep.(SigningIdentityFetcher)
		if !isSigningIdentityFetcher {
			continue
		}
		e.SigningIdentityFetcher = sIDFetcher
		return nil
	}
	return errors.New("could not find SigningIdentityFetcher in dependencies")
}
432297
func (r Resource) Init(container *restful.Container, resource interface{}) {
	log.WithField("Resource", r.Name).Info("Registering Resource")
	ws := new(restful.WebService)
	r.Parent = resource

	ws.Path("/" + r.Config.PathPrefix + r.Endpoint).
		Doc(r.Doc).
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON)

	isDatabaseItem := false
	if resource, ok := resource.(GetIDSupported); ok {
		isDatabaseItem = true
		route := ws.GET("/{id:*}").To(r.GetByIDs).
			Doc("get item by id").
			Returns(http.StatusOK, "OK", resource.Returns()).
			Returns(http.StatusNotFound, "Not found", ErrorResponse{}).
			Param(ws.PathParameter("id", "ID of "+r.TypeName).
				DataType("string").
				Required(true).
				AllowMultiple(false))

		if resource.GetByIDsAuthRequired() {
			route.Returns(http.StatusUnauthorized, "Authorization required", ErrorResponse{})
			route.Param(restful.QueryParameter("accesstoken", "accesstoken required for auth").
				DataType("string").
				Required(true).
				AllowMultiple(false))
		}

		ws.Route(route)
	}

	isGetSupported := false
	if resource, ok := resource.(GetSupported); ok {
		isGetSupported = true
		route := ws.GET("").To(r.Get).
			Doc(resource.GetDoc()).
			Returns(http.StatusOK, "OK", resource.Returns()).
			Returns(http.StatusNotFound, "Not found", ErrorResponse{})

		if resource.GetAuthRequired() {
			route.Returns(http.StatusUnauthorized, "Authorization required", ErrorResponse{})
			route.Param(restful.QueryParameter("accesstoken", "accesstoken required for auth").
				DataType("string").
				Required(true).
				AllowMultiple(false))
		}

		for _, p := range resource.GetParams() {
			route.Param(p)
		}
		if isDatabaseItem {
			route.Param(ws.QueryParameter("ids[]", "IDs of "+r.TypeName+"s").
				DataType("string").
				// Required(true).
				AllowMultiple(true))
		}
		ws.Route(route)
	}

	if isDatabaseItem && !isGetSupported {
		route := ws.GET("").To(r.GetByIDs).
			Doc("get "+r.TypeName+" by ids").
			Returns(http.StatusNotFound, "Not found", ErrorResponse{}).
			Param(ws.QueryParameter("ids[]", "IDs of "+r.TypeName+"s").
				DataType("string").
				// Required(true).
				AllowMultiple(true))

		ws.Route(route)
	}

	if resource, ok := resource.(PostSupported); ok {
		route := ws.POST("").To(r.Post).
			Doc(resource.PostDoc()).
			Reads(reflect.Indirect(reflect.ValueOf(resource.Reads())).Interface()).
			Returns(http.StatusOK, "OK", resource.Returns()).
			Returns(http.StatusBadRequest, "Invalid post data", ErrorResponse{})

		if resource.PostAuthRequired() {
			route.Returns(http.StatusUnauthorized, "Authorization required", ErrorResponse{})
			route.Param(restful.QueryParameter("accesstoken", "accesstoken required for auth").
				DataType("string").
				Required(true).
				AllowMultiple(false))
		}

		for _, p := range resource.PostParams() {
			route.Param(p)
		}

		ws.Route(route)
	}

	if resource, ok := resource.(PutSupported); ok {
		route := ws.PUT("/{"+r.TypeName+"-id}").To(r.Put).
			Doc(resource.PutDoc()).
			Reads(reflect.Indirect(reflect.ValueOf(resource.Reads())).Interface()).
			Returns(http.StatusOK, "OK", resource.Returns()).
			Returns(http.StatusNotFound, "Not found", ErrorResponse{}).
			Returns(http.StatusBadRequest, "Invalid put data", ErrorResponse{})

		if resource.PutAuthRequired() {
			route.Returns(http.StatusUnauthorized, "Authorization required", ErrorResponse{})
			route.Param(restful.QueryParameter("accesstoken", "accesstoken required for auth").
				DataType("string").
				Required(true).
				AllowMultiple(false))
		}

		for _, p := range resource.PutParams() {
			route.Param(p)
		}

		route.Param(restful.PathParameter(r.TypeName+"-id", "ID of a "+r.TypeName).
			Required(true).
			AllowMultiple(false))

		ws.Route(route)
	}

	if resource, ok := resource.(PatchSupported); ok {
		route := ws.PATCH("/{"+r.TypeName+"-id").To(r.Patch).
			Doc(resource.PatchDoc()).
			Reads(reflect.Indirect(reflect.ValueOf(resource.Reads())).Interface()).
			Returns(http.StatusOK, "OK", resource.Returns()).
			Returns(http.StatusNotFound, "Not found", ErrorResponse{}).
			Returns(http.StatusBadRequest, "Invalid patch data", ErrorResponse{})

		if resource.PatchAuthRequired() {
			route.Returns(http.StatusUnauthorized, "Authorization required", ErrorResponse{})
			route.Param(restful.QueryParameter("accesstoken", "accesstoken required for auth").
				DataType("string").
				Required(true).
				AllowMultiple(false))
		}

		for _, p := range resource.PatchParams() {
			route.Param(p)
		}

		route.Param(restful.PathParameter(r.TypeName+"-id", "ID of a "+r.TypeName).
			Required(true).
			AllowMultiple(false))

		ws.Route(route)
	}

	if resource, ok := resource.(DeleteSupported); ok {
		route := ws.DELETE("/{"+r.TypeName+"-id}").To(r.Delete).
			Doc(resource.DeleteDoc()).
			Returns(http.StatusNotFound, "Not found", ErrorResponse{})

		if resource.DeleteAuthRequired() {
			route.Returns(http.StatusUnauthorized, "Authorization required", ErrorResponse{})
			route.Param(restful.QueryParameter("accesstoken", "accesstoken required for auth").
				DataType("string").
				Required(true).
				AllowMultiple(false))
		}

		for _, p := range resource.DeleteParams() {
			route.Param(p)
		}

		route.Param(restful.PathParameter(r.TypeName+"-id", "ID of a "+r.TypeName).
			Required(true).
			AllowMultiple(false))

		ws.Route(route)
	}

	container.Add(ws)
}