// Initialize a Permissions struct with all the default settings.
// This will also connect to the redis host at localhost:6379.
480689
func New2() (*Permissions, error) {
	userstate, err := NewUserStateSimple2()
	if err != nil {
		return nil, err
	}
	return NewPermissions(userstate), nil
}
1052539
func init() {
	revel.RegisterServerEngine("fasthttp", func() revel.ServerEngine {
		return &FastHTTPServer{}
	})
	revel.RegisterModuleInit(func(m *revel.Module) {
		serverLog = m.Log
	})
}
798865
func init() {
	// Unset localhost defaults if certificate file can not be found.
	certFileExists, err := cfgutil.FileExists(opts.RPCCertificateFile)
	if err != nil {
		fatalf("%v", err)
	}
	if !certFileExists {
		opts.RPCConnect = ""
		opts.RPCCertificateFile = ""
	}

	_, err = flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	if opts.TestNet3 && opts.SimNet {
		fatalf("Multiple bitcoin networks may not be used simultaneously")
	}
	var activeNet = &netparams.MainNetParams
	if opts.TestNet3 {
		activeNet = &netparams.TestNet3Params
	} else if opts.SimNet {
		activeNet = &netparams.SimNetParams
	}

	if opts.RPCConnect == "" {
		fatalf("RPC hostname[:port] is required")
	}
	rpcConnect, err := cfgutil.NormalizeAddress(opts.RPCConnect, activeNet.RPCServerPort)
	if err != nil {
		fatalf("Invalid RPC network address `%v`: %v", opts.RPCConnect, err)
	}
	opts.RPCConnect = rpcConnect

	if opts.RPCUsername == "" {
		fatalf("RPC username is required")
	}

	certFileExists, err = cfgutil.FileExists(opts.RPCCertificateFile)
	if err != nil {
		fatalf("%v", err)
	}
	if !certFileExists {
		fatalf("RPC certificate file `%s` not found", opts.RPCCertificateFile)
	}

	if opts.FeeRate.Amount > 1e6 {
		fatalf("Fee rate `%v/kB` is exceptionally high", opts.FeeRate.Amount)
	}
	if opts.FeeRate.Amount < 1e2 {
		fatalf("Fee rate `%v/kB` is exceptionally low", opts.FeeRate.Amount)
	}
	if opts.SourceAccount == opts.DestinationAccount {
		fatalf("Source and destination accounts should not be equal")
	}
	if opts.RequiredConfirmations < 0 {
		fatalf("Required confirmations must be non-negative")
	}
}
1308010
func (is *InfoSyncer) Init(ctx context.Context) error {
	return is.newSessionAndStoreServerInfo(ctx, owner.NewSessionDefaultRetryCnt)
}
932216
func initialize() {
	if lowPort+maxBlocks*blockSize > 65535 {
		panic("freeport: block size too big or too many blocks requested")
	}

	rand.Seed(time.Now().UnixNano())
	firstPort, lockLn = alloc()
}
375765
func Init(homeDir, mobileSharedHome, logFile, runModeStr string,
	accessGroupOverride bool, externalDNSNSFetcher ExternalDNSNSFetcher, nvh NativeVideoHelper) (err error) {
	defer func() {
		err = flattenError(err)
		if err == nil {
			setInited()
		}
	}()

	fmt.Printf("Go: Initializing: home: %s mobileSharedHome: %s\n", homeDir, mobileSharedHome)
	var ekLogFile string
	if logFile != "" {
		fmt.Printf("Go: Using log: %s\n", logFile)
		ekLogFile = logFile + ".ek"
		fmt.Printf("Go: Using eklog: %s\n", ekLogFile)
	}

	// Reduce OS threads on mobile so we don't have too much contention with JS thread
	oldProcs := runtime.GOMAXPROCS(0)
	newProcs := oldProcs / 2
	runtime.GOMAXPROCS(newProcs)
	fmt.Printf("Go: setting GOMAXPROCS to: %d previous: %d\n", newProcs, oldProcs)

	startTrace(logFile)

	dnsNSFetcher := newDNSNSFetcher(externalDNSNSFetcher)
	dnsServers := dnsNSFetcher.GetServers()
	for _, srv := range dnsServers {
		fmt.Printf("Go: DNS Server: %s\n", srv)
	}

	kbCtx = libkb.NewGlobalContext()
	kbCtx.Init()
	kbCtx.SetProofServices(externals.NewProofServices(kbCtx))

	// 10k uid -> FullName cache entries allowed
	kbCtx.SetUIDMapper(uidmap.NewUIDMap(10000))
	usage := libkb.Usage{
		Config:    true,
		API:       true,
		KbKeyring: true,
	}
	runMode, err := libkb.StringToRunMode(runModeStr)
	if err != nil {
		return err
	}
	config := libkb.AppConfig{
		HomeDir:                        homeDir,
		MobileSharedHomeDir:            mobileSharedHome,
		LogFile:                        logFile,
		EKLogFile:                      ekLogFile,
		RunMode:                        runMode,
		Debug:                          true,
		LocalRPCDebug:                  "",
		VDebugSetting:                  "mobile", // use empty string for same logging as desktop default
		SecurityAccessGroupOverride:    accessGroupOverride,
		ChatInboxSourceLocalizeThreads: 5,
		LinkCacheSize:                  1000,
	}
	err = kbCtx.Configure(config, usage)
	if err != nil {
		return err
	}

	svc := service.NewService(kbCtx, false)
	err = svc.StartLoopbackServer()
	if err != nil {
		return err
	}
	kbCtx.SetService()
	uir := service.NewUIRouter(kbCtx)
	kbCtx.SetUIRouter(uir)
	kbCtx.SetDNSNameServerFetcher(dnsNSFetcher)
	svc.SetupCriticalSubServices()
	svc.SetupChatModules(nil)
	svc.RunBackgroundOperations(uir)
	kbChatCtx = svc.ChatContextified.ChatG()
	kbChatCtx.NativeVideoHelper = newVideoHelper(nvh)

	logs := libkb.Logs{
		Service: config.GetLogFile(),
		EK:      config.GetEKLogFile(),
	}

	fmt.Printf("Go: Using config: %+v\n", kbCtx.Env.GetLogFileConfig(config.GetLogFile()))

	logSendContext = libkb.LogSendContext{
		Contextified: libkb.NewContextified(kbCtx),
		Logs:         logs,
	}

	// open the connection
	if err = Reset(); err != nil {
		return err
	}

	go func() {
		kbfsCtx := env.NewContextFromGlobalContext(kbCtx)
		kbfsParams := libkbfs.DefaultInitParams(kbfsCtx)
		// Setting this flag will enable KBFS debug logging to always
		// be true in a mobile setting. Change these back to the
		// commented-out values if we need to make a mobile release
		// before KBFS-on-mobile is ready.
		kbfsParams.Debug = true                         // false
		kbfsParams.Mode = libkbfs.InitConstrainedString // libkbfs.InitMinimalString
		kbfsConfig, _ = libkbfs.Init(
			context.Background(), kbfsCtx, kbfsParams, serviceCn{}, func() error { return nil },
			kbCtx.Log)
	}()

	return nil
}
154439
func (role *StdRole) Permissions() []Permission {
	role.RLock()
	result := make([]Permission, 0, len(role.permissions))
	for _, p := range role.permissions {
		result = append(result, p)
	}
	role.RUnlock()
	return result
}
1335363
func (c *Client) init() error {
	c.HTTPClient = cleanhttp.DefaultClient()
	tlsConfig := &tls.Config{}
	if os.Getenv(atlasTLSNoVerifyEnvVar) != "" {
		tlsConfig.InsecureSkipVerify = true
	}
	err := rootcerts.ConfigureTLS(tlsConfig, &rootcerts.Config{
		CAFile: os.Getenv(atlasCAFileEnvVar),
		CAPath: os.Getenv(atlasCAPathEnvVar),
	})
	if err != nil {
		return err
	}
	t := cleanhttp.DefaultTransport()
	t.TLSClientConfig = tlsConfig
	c.HTTPClient.Transport = t
	return nil
}
1024504
func NewWithConf(connectionString string) (*Permissions, error) {
	state, err := NewUserState(connectionString, true)
	if err != nil {
		return nil, err
	}
	return NewPermissions(state), nil
}
253354
func Init() {
	if *ldapAuthConfigFile == "" && *ldapAuthConfigString == "" {
		log.Infof("Not configuring AuthServerLdap because mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are empty")
		return
	}
	if *ldapAuthConfigFile != "" && *ldapAuthConfigString != "" {
		log.Infof("Both mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are non-empty, can only use one.")
		return
	}
	if *ldapAuthMethod != mysql.MysqlClearPassword && *ldapAuthMethod != mysql.MysqlDialog {
		log.Exitf("Invalid mysql_ldap_auth_method value: only support mysql_clear_password or dialog")
	}
	ldapAuthServer := &AuthServerLdap{
		Client:       &ClientImpl{},
		ServerConfig: ServerConfig{},
		Method:       *ldapAuthMethod,
	}

	data := []byte(*ldapAuthConfigString)
	if *ldapAuthConfigFile != "" {
		var err error
		data, err = ioutil.ReadFile(*ldapAuthConfigFile)
		if err != nil {
			log.Exitf("Failed to read mysql_ldap_auth_config_file: %v", err)
		}
	}
	if err := json.Unmarshal(data, ldapAuthServer); err != nil {
		log.Exitf("Error parsing AuthServerLdap config: %v", err)
	}
	mysql.RegisterAuthServerImpl("ldap", ldapAuthServer)
}
963076
func (c *clientACLResolver) init() error {
	// Create the ACL object cache
	var err error
	c.aclCache, err = lru.New2Q(aclCacheSize)
	if err != nil {
		return err
	}
	c.policyCache, err = lru.New2Q(policyCacheSize)
	if err != nil {
		return err
	}
	c.tokenCache, err = lru.New2Q(tokenCacheSize)
	if err != nil {
		return err
	}
	return nil
}
568871
func (c *Client) Permissions(context.Context) chronograf.Permissions {
	all := chronograf.Allowances{
		"NoPermissions",
		"ViewAdmin",
		"ViewChronograf",
		"CreateDatabase",
		"CreateUserAndRole",
		"AddRemoveNode",
		"DropDatabase",
		"DropData",
		"ReadData",
		"WriteData",
		"Rebalance",
		"ManageShard",
		"ManageContinuousQuery",
		"ManageQuery",
		"ManageSubscription",
		"Monitor",
		"CopyShard",
		"KapacitorAPI",
		"KapacitorConfigAPI",
	}

	return chronograf.Permissions{
		{
			Scope:   chronograf.AllScope,
			Allowed: all,
		},
		{
			Scope:   chronograf.DBScope,
			Allowed: all,
		},
	}
}
159711
func (c *changePasswordCommand) Init(args []string) error {
	var err error
	c.User, err = cmd.ZeroOrOneArgs(args)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
916519
func (s *Service) Permissions(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	srcID, err := paramID("id", r)
	if err != nil {
		Error(w, http.StatusUnprocessableEntity, err.Error(), s.Logger)
		return
	}

	src, err := s.Store.Sources(ctx).Get(ctx, srcID)
	if err != nil {
		notFound(w, srcID, s.Logger)
		return
	}

	ts, err := s.TimeSeries(src)
	if err != nil {
		msg := fmt.Sprintf("unable to connect to source %d: %v", srcID, err)
		Error(w, http.StatusBadRequest, msg, s.Logger)
		return
	}

	if err = ts.Connect(ctx, &src); err != nil {
		msg := fmt.Sprintf("unable to connect to source %d: %v", srcID, err)
		Error(w, http.StatusBadRequest, msg, s.Logger)
		return
	}

	perms := ts.Permissions(ctx)
	if err != nil {
		Error(w, http.StatusBadRequest, err.Error(), s.Logger)
		return
	}
	httpAPISrcs := "/chronograf/v1/sources"
	res := struct {
		Permissions chronograf.Permissions `json:"permissions"`
		Links       map[string]string      `json:"links"` // Links are URI locations related to user
	}{
		Permissions: perms,
		Links: map[string]string{
			"self":   fmt.Sprintf("%s/%d/permissions", httpAPISrcs, srcID),
			"source": fmt.Sprintf("%s/%d", httpAPISrcs, srcID),
		},
	}
	encodeJSON(w, http.StatusOK, res, s.Logger)
}
1340366
func (p *Policy) init() {
	if !p.initialized {
		p.elsAndAttrs = make(map[string]map[string]attrPolicy)
		p.globalAttrs = make(map[string]attrPolicy)
		p.allowURLSchemes = make(map[string]urlPolicy)
		p.setOfElementsAllowedWithoutAttrs = make(map[string]struct{})
		p.setOfElementsToSkipContent = make(map[string]struct{})
		p.initialized = true
	}
}
682107
func init() {
	// Registry archci database models.
	models.RegisterModels()

	// Initialize database with environment variables.
	server := ""
	username := "root"
	password := "root"
	database := "mysql"

	if os.Getenv(ENV_MYSQL_SERVER) != "" {
		server = os.Getenv(ENV_MYSQL_SERVER)
	}
	if os.Getenv(ENV_MYSQL_USERNAME) != "" {
		username = os.Getenv(ENV_MYSQL_USERNAME)
	}
	if os.Getenv(ENV_MYSQL_PASSWORD) != "" {
		password = os.Getenv(ENV_MYSQL_PASSWORD)
	}
	if os.Getenv(ENV_MYSQL_DATABASE) != "" {
		database = os.Getenv(ENV_MYSQL_DATABASE)
	}

	// The datasource looks like "root:root@/archci?charset=utf8".
	DATASOURCE := username + ":" + password + "@" + server + "/" + database + "?charset=utf8"
	fmt.Println("Connect to database with " + DATASOURCE)

	orm.RegisterDriver(MYSQL_DRIVER, orm.DR_MySQL)
	orm.RegisterDataBase("default", MYSQL_DRIVER, DATASOURCE, 30)
	orm.RunSyncdb("default", false, true)
}
474520
func (c *StatusCommand) Initialize(app *kingpin.Application, config *service.Config) {
	c.config = config
	c.status = app.Command("status", "Report cluster status")
}