// NewLXDProfileAPI returns a new LXDProfileAPI. Currently both
// GetAuthFuncs can used to determine current permissions.
505126
func NewLXDProfileAPI(
	backend LXDProfileBackend,
	resources facade.Resources,
	authorizer facade.Authorizer,
	accessUnit common.GetAuthFunc,
	logger loggo.Logger,
) *LXDProfileAPI {
	logger.Tracef("NewLXDProfileAPI called with %s", authorizer.GetAuthTag())
	return &LXDProfileAPI{
		backend:    backend,
		resources:  resources,
		accessUnit: accessUnit,
		logger:     logger,
	}
}
126222
func isProfileAllowed(profile string, allowedProfiles []string) bool {
	// for backwards compatibility and PSPs without a defined list of allowed profiles.
	// If a PSP does not have allowedProfiles set then we should allow an empty profile.
	// This will mean that the runtime default is used.
	if len(allowedProfiles) == 0 && profile == "" {
		return true
	}

	for _, p := range allowedProfiles {
		if profile == p || p == allowAnyProfile {
			return true
		}
	}
	return false
}
1269809
func newXLMetaFromXLMeta(meta xlMetaV1) xlMetaV1 {
	xlMeta := meta
	xlMeta.Erasure.Checksums = nil
	xlMeta.Parts = nil
	return xlMeta
}
1334849
func NewMultiAuthExampleAPI(spec *loads.Document) *MultiAuthExampleAPI {
	return &MultiAuthExampleAPI{
		handlers:            make(map[string]map[string]http.Handler),
		formats:             strfmt.Default,
		defaultConsumes:     "application/json",
		defaultProduces:     "application/json",
		customConsumers:     make(map[string]runtime.Consumer),
		customProducers:     make(map[string]runtime.Producer),
		ServerShutdown:      func() {},
		spec:                spec,
		ServeError:          errors.ServeError,
		BasicAuthenticator:  security.BasicAuth,
		APIKeyAuthenticator: security.APIKeyAuth,
		BearerAuthenticator: security.BearerAuth,
		JSONConsumer:        runtime.JSONConsumer(),
		JSONProducer:        runtime.JSONProducer(),
		AddOrderHandler: AddOrderHandlerFunc(func(params AddOrderParams, principal *models.Principal) middleware.Responder {
			return middleware.NotImplemented("operation AddOrder has not yet been implemented")
		}),
		GetAccountHandler: GetAccountHandlerFunc(func(params GetAccountParams, principal *models.Principal) middleware.Responder {
			return middleware.NotImplemented("operation GetAccount has not yet been implemented")
		}),
		GetItemsHandler: GetItemsHandlerFunc(func(params GetItemsParams) middleware.Responder {
			return middleware.NotImplemented("operation GetItems has not yet been implemented")
		}),
		GetOrderHandler: GetOrderHandlerFunc(func(params GetOrderParams, principal *models.Principal) middleware.Responder {
			return middleware.NotImplemented("operation GetOrder has not yet been implemented")
		}),
		GetOrdersForItemHandler: GetOrdersForItemHandlerFunc(func(params GetOrdersForItemParams, principal *models.Principal) middleware.Responder {
			return middleware.NotImplemented("operation GetOrdersForItem has not yet been implemented")
		}),

		HasRoleAuth: func(token string, scopes []string) (*models.Principal, error) {
			return nil, errors.NotImplemented("oauth2 bearer auth (hasRole) has not yet been implemented")
		},

		// Applies when the Authorization header is set with the Basic scheme
		IsRegisteredAuth: func(user string, pass string) (*models.Principal, error) {
			return nil, errors.NotImplemented("basic auth  (isRegistered) has not yet been implemented")
		},

		// Applies when the "X-Custom-Key" header is set
		IsResellerAuth: func(token string) (*models.Principal, error) {
			return nil, errors.NotImplemented("api key auth (isReseller) X-Custom-Key from header param [X-Custom-Key] has not yet been implemented")
		},
		// Applies when the "CustomKeyAsQuery" query is set
		IsResellerQueryAuth: func(token string) (*models.Principal, error) {
			return nil, errors.NotImplemented("api key auth (isResellerQuery) CustomKeyAsQuery from query param [CustomKeyAsQuery] has not yet been implemented")
		},

		// default authorizer is authorized meaning no requests are blocked
		APIAuthorizer: security.Authorized(),
	}
}
561079
func NewFileAWSCredentials(filename string, profile string) *Credentials {
	return New(&FileAWSCredentials{
		filename: filename,
		profile:  profile,
	})
}
995858
func NewBearerAuthFileRoundTripper(bearerFile string, rt http.RoundTripper) http.RoundTripper {
	return &bearerAuthFileRoundTripper{bearerFile, rt}
}
1302949
func (bot *BotAPI) GetUserProfilePhotos(config UserProfilePhotosConfig) (UserProfilePhotos, error) {
	v := url.Values{}
	v.Add("user_id", strconv.Itoa(config.UserID))
	if config.Offset != 0 {
		v.Add("offset", strconv.Itoa(config.Offset))
	}
	if config.Limit != 0 {
		v.Add("limit", strconv.Itoa(config.Limit))
	}

	resp, err := bot.MakeRequest("getUserProfilePhotos", v)
	if err != nil {
		return UserProfilePhotos{}, err
	}

	var profilePhotos UserProfilePhotos
	json.Unmarshal(resp.Result, &profilePhotos)

	bot.debugLog("GetUserProfilePhoto", v, profilePhotos)

	return profilePhotos, nil
}
640002
func (p *ProvisionerAPI) machineLXDProfileNames(m *state.Machine, env environs.Environ) ([]string, error) {
	profileEnv, ok := env.(environs.LXDProfiler)
	if !ok {
		logger.Tracef("LXDProfiler not implemented by environ")
		return nil, nil
	}
	units, err := m.Units()
	if err != nil {
		return nil, errors.Trace(err)
	}
	var names []string
	for _, unit := range units {
		app, err := unit.Application()
		if err != nil {
			return nil, errors.Trace(err)
		}
		ch, _, err := app.Charm()
		if err != nil {
			return nil, errors.Trace(err)
		}
		profile := ch.LXDProfile()
		if profile == nil || (profile != nil && profile.Empty()) {
			continue
		}
		pName := lxdprofile.Name(p.m.Name(), app.Name(), ch.Revision())
		// Lock here, we get a new env for every call to ProvisioningInfo().
		p.mu.Lock()
		if err := profileEnv.MaybeWriteLXDProfile(pName, profile); err != nil {
			p.mu.Unlock()
			return nil, errors.Trace(err)
		}
		p.mu.Unlock()
		names = append(names, pName)
	}
	return names, nil
}
949172
func NewProvisionerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*ProvisionerAPI, error) {
	if !authorizer.AuthMachineAgent() && !authorizer.AuthController() {
		return nil, common.ErrPerm
	}
	getAuthFunc := func() (common.AuthFunc, error) {
		isModelManager := authorizer.AuthController()
		isMachineAgent := authorizer.AuthMachineAgent()
		authEntityTag := authorizer.GetAuthTag()

		return func(tag names.Tag) bool {
			if isMachineAgent && tag == authEntityTag {
				// A machine agent can always access its own machine.
				return true
			}
			switch tag := tag.(type) {
			case names.MachineTag:
				parentId := state.ParentId(tag.Id())
				if parentId == "" {
					// All top-level machines are accessible by the controller.
					return isModelManager
				}
				// All containers with the authenticated machine as a
				// parent are accessible by it.
				// TODO(dfc) sometimes authEntity tag is nil, which is fine because nil is
				// only equal to nil, but it suggests someone is passing an authorizer
				// with a nil tag.
				return isMachineAgent && names.NewMachineTag(parentId) == authEntityTag
			default:
				return false
			}
		}, nil
	}
	getCanModify := func() (common.AuthFunc, error) {
		return authorizer.AuthOwner, nil
	}
	getAuthOwner := func() (common.AuthFunc, error) {
		return authorizer.AuthOwner, nil
	}
	model, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	configGetter := stateenvirons.EnvironConfigGetter{State: st, Model: model}
	isCaasModel := model.Type() == state.ModelTypeCAAS

	var env storage.ProviderRegistry
	if isCaasModel {
		env, err = stateenvirons.GetNewCAASBrokerFunc(caas.New)(st)
	} else {
		env, err = environs.GetEnviron(configGetter, environs.New)
	}
	if err != nil {
		return nil, errors.Trace(err)
	}
	storageProviderRegistry := stateenvirons.NewStorageProviderRegistry(env)

	urlGetter := common.NewToolsURLGetter(model.UUID(), st)
	callCtx := state.CallContext(st)
	api := &ProvisionerAPI{
		Remover:                 common.NewRemover(st, false, getAuthFunc),
		StatusSetter:            common.NewStatusSetter(st, getAuthFunc),
		StatusGetter:            common.NewStatusGetter(st, getAuthFunc),
		DeadEnsurer:             common.NewDeadEnsurer(st, getAuthFunc),
		PasswordChanger:         common.NewPasswordChanger(st, getAuthFunc),
		LifeGetter:              common.NewLifeGetter(st, getAuthFunc),
		StateAddresser:          common.NewStateAddresser(st),
		APIAddresser:            common.NewAPIAddresser(st, resources),
		ModelWatcher:            common.NewModelWatcher(model, resources, authorizer),
		ModelMachinesWatcher:    common.NewModelMachinesWatcher(st, resources, authorizer),
		ControllerConfigAPI:     common.NewStateControllerConfig(st),
		NetworkConfigAPI:        networkingcommon.NewNetworkConfigAPI(st, callCtx, getCanModify),
		st:                      st,
		m:                       model,
		resources:               resources,
		authorizer:              authorizer,
		configGetter:            configGetter,
		storageProviderRegistry: storageProviderRegistry,
		storagePoolManager:      poolmanager.New(state.NewStateSettings(st), storageProviderRegistry),
		getAuthFunc:             getAuthFunc,
		getCanModify:            getCanModify,
		providerCallContext:     callCtx,
	}
	if isCaasModel {
		return api, nil
	}
	api.InstanceIdGetter = common.NewInstanceIdGetter(st, getAuthFunc)
	api.ToolsFinder = common.NewToolsFinder(configGetter, st, urlGetter)
	api.ToolsGetter = common.NewToolsGetter(st, configGetter, st, urlGetter, getAuthOwner)
	return api, nil
}
1009143
func NewProfileSnapshotArgs(snapshotID SnapshotID) *ProfileSnapshotArgs {
	args := new(ProfileSnapshotArgs)
	args.SnapshotID = snapshotID
	return args
}
236110
func WriteProfileFunctions() error {
	if runtime.GOOS != "linux" {
		logger.Debugf("skipping profile funcs install")
		return nil
	}
	filename := profileFilename()
	if err := ioutil.WriteFile(filename, []byte(bashFuncs), 0644); err != nil {
		return errors.Annotate(err, "writing introspection bash funcs")
	}
	return nil
}
983080
func getHeapProfile(w http.ResponseWriter, r *http.Request) {
	// Ensure up-to-date data.
	runtime.GC()
	w.Header().Set("Content-Type", "application/octet-stream")
	if err := pprof.Lookup("heap").WriteTo(w, 0); err != nil {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Could not get heap profile: %s\n", err)
	}
}
1369195
func NewAuthSampleAPI(spec *loads.Document) *AuthSampleAPI {
	return &AuthSampleAPI{
		handlers:            make(map[string]map[string]http.Handler),
		formats:             strfmt.Default,
		defaultConsumes:     "application/json",
		defaultProduces:     "application/json",
		customConsumers:     make(map[string]runtime.Consumer),
		customProducers:     make(map[string]runtime.Producer),
		ServerShutdown:      func() {},
		spec:                spec,
		ServeError:          errors.ServeError,
		BasicAuthenticator:  security.BasicAuth,
		APIKeyAuthenticator: security.APIKeyAuth,
		BearerAuthenticator: security.BearerAuth,
		JSONConsumer:        runtime.JSONConsumer(),
		JSONProducer:        runtime.JSONProducer(),
		CustomersCreateHandler: customers.CreateHandlerFunc(func(params customers.CreateParams, principal *models.Principal) middleware.Responder {
			return middleware.NotImplemented("operation CustomersCreate has not yet been implemented")
		}),
		CustomersGetIDHandler: customers.GetIDHandlerFunc(func(params customers.GetIDParams, principal *models.Principal) middleware.Responder {
			return middleware.NotImplemented("operation CustomersGetID has not yet been implemented")
		}),

		// Applies when the "x-token" header is set
		KeyAuth: func(token string) (*models.Principal, error) {
			return nil, errors.NotImplemented("api key auth (key) x-token from header param [x-token] has not yet been implemented")
		},

		// default authorizer is authorized meaning no requests are blocked
		APIAuthorizer: security.Authorized(),
	}
}
1312733
func (mr *MockLXDProfilerMockRecorder) LXDProfile() *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LXDProfile", reflect.TypeOf((*MockLXDProfiler)(nil).LXDProfile))
}
607548
func NewUniterAPIV11(context facade.Context) (*UniterAPIV11, error) {
	uniterAPI, err := NewUniterAPI(context)
	if err != nil {
		return nil, err
	}
	authorizer := context.Auth()
	st := context.State()
	resources := context.Resources()
	accessUnit := unitAccessor(authorizer, st)
	return &UniterAPIV11{
		LXDProfileAPI: NewExternalLXDProfileAPI(st, resources, authorizer, accessUnit, logger),
		UniterAPI:     *uniterAPI,
	}, nil
}
988717
func StartVolumePluginAPI(
	name, sdkUds string,
	pluginBase string,
	pluginPort uint16,
	authProviderType secrets.AuthTokenProviders,
	authProvider osecrets.Secrets,
) error {
	var secretsStore secrets.Auth
	var err error

	// Only initialize secrets store if we have a valid auth provider.
	if authProvider != nil && authProviderType != secrets.TypeNone {
		secretsStore, err = secrets.NewAuth(authProviderType, authProvider)
		if err != nil {
			return err
		}
	}

	volPluginApi := newVolumePlugin(name, sdkUds, secretsStore)
	if _, _, err := startServer(
		name,
		pluginBase,
		pluginPort,
		volPluginApi,
	); err != nil {
		return err
	}
	return nil
}
1054061
func (m *MockLXDProfiler) LXDProfile() lxdprofile.LXDProfile {
	ret := m.ctrl.Call(m, "LXDProfile")
	ret0, _ := ret[0].(lxdprofile.LXDProfile)
	return ret0
}