// NewWithAppInsightsConfig returns an initialised logrus hook for Application Insights
336593
func NewWithAppInsightsConfig(name string, conf *appinsights.TelemetryConfiguration) (*AppInsightsHook, error) {
	if conf == nil {
		return nil, fmt.Errorf("Nil configuration provided")
	}
	if conf.InstrumentationKey == "" {
		return nil, fmt.Errorf("InstrumentationKey is required in configuration")
	}
	telemetryClient := appinsights.NewTelemetryClientFromConfig(conf)
	if name != "" {
		telemetryClient.Context().Cloud().SetRoleName(name)
	}
	return &AppInsightsHook{
		client:       telemetryClient,
		levels:       defaultLevels,
		ignoreFields: make(map[string]struct{}),
		filters:      make(map[string]func(interface{}) interface{}),
	}, nil
}
1293301
func NewConfig() *Config {
	return &Config{
		Preferences: *NewPreferences(),
		Clusters:    make(map[string]*Cluster),
		AuthInfos:   make(map[string]*AuthInfo),
		Contexts:    make(map[string]*Context),
		Extensions:  make(map[string]runtime.Object),
	}
}
318176
func NewInsightApiRouter(app *InsightApi, useRealIP, compression bool) ApiMux {
	// chi router
	mux := chi.NewRouter()

	// Create a rate limiter struct.
	limiter := tollbooth.NewLimiter(app.ReqPerSecLimit, nil)

	if useRealIP {
		mux.Use(middleware.RealIP)
		// RealIP sets RemoteAddr
		limiter.SetIPLookups([]string{"RemoteAddr"})
	} else {
		limiter.SetIPLookups([]string{"X-Forwarded-For", "X-Real-IP", "RemoteAddr"})
	}

	// Put the limiter after RealIP
	mux.Use(tollbooth_chi.LimitHandler(limiter))

	mux.Use(middleware.Logger)
	mux.Use(middleware.Recoverer)
	mux.Use(middleware.StripSlashes)
	if compression {
		mux.Use(middleware.NewCompressor(3).Handler())
	}

	// Block endpoints
	mux.With(BlockDateLimitQueryCtx).Get("/blocks", app.getBlockSummaryByTime)
	mux.With(m.BlockIndexOrHashPathCtx).Get("/block/{idxorhash}", app.getBlockSummary)
	mux.With(m.BlockIndexOrHashPathCtx).Get("/block-index/{idxorhash}", app.getBlockHash)
	mux.With(m.BlockIndexOrHashPathCtx).Get("/rawblock/{idxorhash}", app.getRawBlock)

	// Transaction endpoints
	mux.With(middleware.AllowContentType("application/json"),
		app.ValidatePostCtx, m.PostBroadcastTxCtx).Post("/tx/send", app.broadcastTransactionRaw)
	mux.With(m.TransactionHashCtx).Get("/tx/{txid}", app.getTransaction)
	mux.With(m.TransactionHashCtx).Get("/rawtx/{txid}", app.getTransactionHex)
	mux.With(m.TransactionsCtx).Get("/txs", app.getTransactions)

	// Status and Utility
	mux.With(app.StatusInfoCtx).Get("/status", app.getStatusInfo)
	mux.Get("/sync", app.getSyncInfo)
	mux.With(NbBlocksCtx).Get("/utils/estimatefee", app.getEstimateFee)
	mux.Get("/peer", app.GetPeerStatus)

	// Addresses endpoints
	mux.Route("/addrs", func(rd chi.Router) {
		rd.Route("/{address}", func(ra chi.Router) {
			ra.Use(m.AddressPathCtx, FromToPaginationCtx)
			ra.Get("/txs", app.getAddressesTxn)
			ra.Get("/utxo", app.getAddressesTxnOutput)
		})
		// POST methods
		rd.With(middleware.AllowContentType("application/json"),
			app.ValidatePostCtx, PostAddrsTxsCtx).Post("/txs", app.getAddressesTxn)
		rd.With(middleware.AllowContentType("application/json"),
			app.ValidatePostCtx, PostAddrsUtxoCtx).Post("/utxo", app.getAddressesTxnOutput)
	})

	// Address endpoints
	mux.Route("/addr/{address}", func(rd chi.Router) {
		rd.Use(m.AddressPathCtx)
		rd.With(FromToPaginationCtx, NoTxListCtx).Get("/", app.getAddressInfo)
		rd.Get("/utxo", app.getAddressesTxnOutput)
		rd.Route("/{command}", func(ra chi.Router) {
			ra.With(AddressCommandCtx).Get("/", app.getAddressInfo)
		})
	})

	return ApiMux{mux}
}
799066
func CreateAppNw(app *contivModel.AppProfile) error {
	aciPresent, aErr := master.IsAciConfigured()
	if aErr != nil {
		log.Errorf("Couldn't read global config %v", aErr)
		return aErr
	}

	if !aciPresent {
		log.Debugf("ACI not configured")
		return nil
	}

	// Get the state driver
	stateDriver, uErr := utils.GetStateDriver()
	if uErr != nil {
		return uErr
	}

	eMap := &epgMap{}
	eMap.Specs = make(map[string]epgSpec)
	eMap.Contracts = make(map[string]*contrSpec)
	ans := &appNwSpec{}

	ans.ACIGwAPIVersion = aciGwAPIVersion
	gwConfig := contivModel.FindAciGw("aciGw")
	if gwConfig == nil {
		log.Infof("aciGw object not found -- gw will use env settings")
	} else {
		ans.GWConfig = gwConfig
		log.Infof("gwConfig: %+v", gwConfig)
	}
	ans.TenantName = app.TenantName
	ans.AppName = app.AppProfileName

	// Gather all basic epg info into the epg map
	for epgKey := range app.LinkSets.EndpointGroups {
		epgObj := contivModel.FindEndpointGroup(epgKey)
		if epgObj == nil {
			err := fmt.Sprintf("Epg %v does not exist", epgKey)
			log.Errorf("%v", err)
			return errors.New(err)
		}

		if err := appendEpgInfo(eMap, epgObj, stateDriver); err != nil {
			log.Errorf("Error getting epg info %v", err)
			return err
		}
	}

	// walk the map and add to ANS
	for _, epg := range eMap.Specs {
		ans.Epgs = append(ans.Epgs, epg)
		log.Debugf("Added epg %v", epg.Name)
	}

	for _, contract := range eMap.Contracts {
		ans.ContractDefs = append(ans.ContractDefs, *contract)
		log.Debugf("Added contract %v", contract.Name)
	}

	log.Infof("Launching appNwSpec: %+v", ans)
	lErr := ans.launch()
	time.Sleep(2 * time.Second)
	ans.notifyDP()

	return lErr
}
16455
func New(appName, appOwner string, cfgs ...Configurator) *Bootstrapper {
	b := &Bootstrapper{
		AppName:      appName,
		AppOwner:     appOwner,
		AppSpawnDate: time.Now(),
		Application:  iris.New(),
	}

	for _, cfg := range cfgs {
		cfg(b)
	}

	return b
}
76659
func CreateMissingApplicationConfig(pool *StatePool) error {
	st := pool.SystemState()
	settingsColl, settingsCloser := st.db().GetRawCollection(settingsC)
	defer settingsCloser()

	var applicationConfigIDs []struct {
		ID string `bson:"_id"`
	}
	settingsColl.Find(bson.M{
		"_id": bson.M{"$regex": bson.RegEx{"#application$", ""}}}).All(&applicationConfigIDs)

	allIDs := set.NewStrings()
	for _, id := range applicationConfigIDs {
		allIDs.Add(id.ID)
	}

	appsColl, appsCloser := st.db().GetRawCollection(applicationsC)
	defer appsCloser()

	var applicationNames []struct {
		Name      string `bson:"name"`
		ModelUUID string `bson:"model-uuid"`
	}
	appsColl.Find(nil).All(&applicationNames)

	var newAppConfigOps []txn.Op
	emptySettings := make(map[string]interface{})
	for _, app := range applicationNames {
		appConfID := fmt.Sprintf("%s:%s", app.ModelUUID, applicationConfigKey(app.Name))
		if !allIDs.Contains(appConfID) {
			newOp := createSettingsOp(settingsC, appConfID, emptySettings)
			// createSettingsOp assumes you're using a model-specific state, which will auto-inject the ModelUUID
			// since we're doing this globally, cast it to the underlying type and add it.
			newOp.Insert.(*settingsDoc).ModelUUID = app.ModelUUID
			newAppConfigOps = append(newAppConfigOps, newOp)
		}
	}
	err := st.db().RunRawTransaction(newAppConfigOps)
	if err != nil {
		return errors.Annotate(err, "writing application configs")
	}
	return nil
}
782416
func createAppConfigDir(dirPath string) error {
	// check
	if _, err := ioutil.ReadDir(dirPath); err == nil {
		return nil
	}

	// create dir
	return os.Mkdir(dirPath, os.FileMode(0755))
}
683989
func newApp(c *model.CommandConfig) (err error) {
	// Check for an existing folder so we don't clobber it
	_, err = build.Import(c.ImportPath, "", build.FindOnly)
	if err == nil || !utils.Empty(c.AppPath) {
		return utils.NewBuildError("Abort: Import path already exists.", "path", c.ImportPath)
	}

	// checking and setting skeleton
	if err=setSkeletonPath(c);err!=nil {
		return
	}

	// Create application path
	if err := os.MkdirAll(c.AppPath, os.ModePerm); err != nil {
		return utils.NewBuildError("Abort: Unable to create app path.", "path", c.AppPath)
	}

	if c.New.Vendored {
		utils.Logger.Info("Creating a new vendor app")

		vendorPath := filepath.Join(c.AppPath, "vendor")
		if !utils.DirExists(vendorPath) {

			if err := os.MkdirAll(vendorPath, os.ModePerm); err != nil {
				return utils.NewBuildError("Failed to create "+vendorPath, "error", err)
			}
		}

		// In order for dep to run there needs to be a source file in the folder
		tempPath := filepath.Join(c.AppPath, "tmp")
		utils.Logger.Info("Checking for temp folder for source code", "path", tempPath)
		if !utils.DirExists(tempPath) {
			if err := os.MkdirAll(tempPath, os.ModePerm); err != nil {
				return utils.NewBuildIfError(err, "Failed to create "+vendorPath)
			}

			if err = utils.GenerateTemplate(filepath.Join(tempPath, "main.go"), NEW_MAIN_FILE, nil); err != nil {
				return utils.NewBuildIfError(err, "Failed to create main file "+vendorPath)
			}
		}

		// Create a package template file if it does not exist
		packageFile := filepath.Join(c.AppPath, "Gopkg.toml")
		utils.Logger.Info("Checking for Gopkg.toml", "path", packageFile)
		if !utils.Exists(packageFile) {
			utils.Logger.Info("Generating Gopkg.toml", "path", packageFile)
			if err := utils.GenerateTemplate(packageFile, VENDOR_GOPKG, nil); err != nil {
				return utils.NewBuildIfError(err, "Failed to generate template")
			}
		} else {
			utils.Logger.Info("Package file exists in skeleto, skipping adding")
		}

		getCmd := exec.Command("dep", "ensure", "-v")
		utils.CmdInit(getCmd, c.AppPath)

		utils.Logger.Info("Exec:", "args", getCmd.Args, "env", getCmd.Env, "workingdir",getCmd.Dir)
		getOutput, err := getCmd.CombinedOutput()
		if err != nil {
			return utils.NewBuildIfError(err, string(getOutput))
		}
	}

	// checking and setting application
	if err = setApplicationPath(c); err != nil {
		return err
	}
	// At this point the versions can be set
	c.SetVersions()

	// copy files to new app directory
	if err = copyNewAppFiles(c);err != nil {
		return
	}

	// Rerun the dep tool if vendored
	if c.New.Vendored {
		getCmd := exec.Command("dep", "ensure", "-v")
		utils.CmdInit(getCmd, c.AppPath)
		utils.Logger.Info("Exec:", "args", getCmd.Args)
		getOutput, err := getCmd.CombinedOutput()
		if err != nil {
			utils.Logger.Fatal(string(getOutput))
		}
	}

	// goodbye world
	fmt.Fprintln(os.Stdout, "Your application has been created in:\n  ", c.AppPath)
	// Check to see if it should be run right off
	if c.New.Run {
		runApp(c)
	} else {
		fmt.Fprintln(os.Stdout, "\nYou can run it with:\n   revel run -a ", c.ImportPath)
	}
	return
}
282119
func (c *Client) ApplicationConfig(applicationName string) (application.ConfigAttributes, error) {
	var results params.ApplicationGetConfigResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: names.NewApplicationTag(applicationName).String()}},
	}
	err := c.facade.FacadeCall("ApplicationsConfig", args, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != len(args.Entities) {
		return nil, errors.Errorf("expected %d result(s), got %d", len(args.Entities), len(results.Results))
	}
	return application.ConfigAttributes(results.Results[0].Config), nil
}
1374674
func NewWithOptions(out io.Writer, prefix string, flags int) gournal.Appender {
	return &appender{log.New(out, prefix, flags)}
}
859777
func NewWithOptions(
	out io.Writer,
	lvl logrus.Level,
	formatter logrus.Formatter) gournal.Appender {

	return &appender{&logrus.Logger{Out: out, Level: lvl, Formatter: formatter}}
}
201010
func RequiresAppInPing(requiresAppInPing bool) Option {
	return func(r *Ringpop) error {
		r.config.RequiresAppInPing = requiresAppInPing
		return nil
	}
}
826387
func NewConfig() *spotinst.Config {
	config := spotinst.DefaultConfig()

	config.WithCredentials(NewCredentials())
	config.WithLogger(NewStdLogger())
	config.WithUserAgent("kubernetes-kops/" + kopsv.Version)

	return config
}
585653
func WithMetricsConfig(metricsConfigs ...interface{}) Option {
	return func(opts *options) error {
		c, err := metricsCfg.BuildConfigMetricsFromOptions(metricsConfigs...)
		if err != nil {
			return err
		}
		opts.metricsConfig = c
		return nil
	}
}
1138034
func NewConfigMapPayload(cm *apiv1.ConfigMap) (Payload, error) {
	if cm == nil {
		return nil, fmt.Errorf("ConfigMap must be non-nil")
	} else if cm.ObjectMeta.UID == "" {
		return nil, fmt.Errorf("ConfigMap must have a non-empty UID")
	} else if cm.ObjectMeta.ResourceVersion == "" {
		return nil, fmt.Errorf("ConfigMap must have a non-empty ResourceVersion")
	}

	return &configMapPayload{cm}, nil
}
943539
func CreateApplyAnnotation(info *resource.Info) error {
	modified, err := GetModifiedConfiguration(info, false)
	if err != nil {
		return err
	}
	return SetOriginalConfiguration(info, modified)
}
660262
func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config {
	res := Config{
		contextType:   contextType,
		endpointTypes: make(map[string]TypeGetter),
	}
	for _, e := range endpoints {
		res.endpointTypes[e.name] = e.typeGetter
	}
	return res
}