// NewModelManagerAPIClient returns an API client for the
// ModelManager on the current controller using the current credentials.
545743
func (c *ControllerCommandBase) NewModelManagerAPIClient() (*modelmanager.Client, error) {
	root, err := c.NewAPIRoot()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return modelmanager.NewClient(root), nil
}
435702
func newAPIHandler(srv *Server, st *state.State, rpcConn *rpc.Conn, modelUUID string, connectionID uint64, serverHost string) (*apiHandler, error) {
	m, err := st.Model()
	if err != nil {
		if !errors.IsNotFound(err) {
			return nil, errors.Trace(err)
		}

		// If this model used to be hosted on this controller but got
		// migrated allow clients to connect and wait for a login
		// request to decide whether the users should be redirected to
		// the new controller for this model or not.
		if _, migErr := st.LatestRemovedModelMigration(); migErr != nil {
			return nil, errors.Trace(err) // return original NotFound error
		}
	}

	r := &apiHandler{
		state:        st,
		model:        m,
		resources:    common.NewResources(),
		shared:       srv.shared,
		rpcConn:      rpcConn,
		modelUUID:    modelUUID,
		connectionID: connectionID,
		serverHost:   serverHost,
	}

	if err := r.resources.RegisterNamed("machineID", common.StringResource(srv.tag.Id())); err != nil {
		return nil, errors.Trace(err)
	}
	if err := r.resources.RegisterNamed("dataDir", common.StringResource(srv.dataDir)); err != nil {
		return nil, errors.Trace(err)
	}
	if err := r.resources.RegisterNamed("logDir", common.StringResource(srv.logDir)); err != nil {
		return nil, errors.Trace(err)
	}

	// Facades involved with managing application offers need the auth context
	// to mint and validate macaroons.
	localOfferAccessEndpoint := url.URL{
		Scheme: "https",
		Host:   serverHost,
		Path:   localOfferAccessLocationPath,
	}
	offerAuthCtxt := srv.offerAuthCtxt.WithDischargeURL(localOfferAccessEndpoint.String())
	if err := r.resources.RegisterNamed(
		"offerAccessAuthContext",
		common.ValueResource{Value: offerAuthCtxt},
	); err != nil {
		return nil, errors.Trace(err)
	}
	return r, nil
}
978263
func NewCredentialManagerAPI(ctx facade.Context) (*CredentialManagerAPI, error) {
	return internalNewCredentialManagerAPI(newStateShim(ctx.State()), ctx.Resources(), ctx.Auth())
}
598367
func NewClient(caller base.APICaller, newWatcher NewWatcherFunc) *Client {
	return &Client{
		caller:            base.NewFacadeCaller(caller, "MigrationMaster"),
		newWatcher:        newWatcher,
		httpClientFactory: caller.HTTPClient,
	}
}
616514
func (m *ModelManagerAPI) CreateModel(args params.ModelCreateArgs) (params.ModelInfo, error) {
	result := params.ModelInfo{}

	// Get the controller model first. We need it both for the state
	// server owner and the ability to get the config.
	controllerModel, err := m.ctlrState.Model()
	if err != nil {
		return result, errors.Trace(err)
	}

	var cloudTag names.CloudTag
	cloudRegionName := args.CloudRegion
	if args.CloudTag != "" {
		var err error
		cloudTag, err = names.ParseCloudTag(args.CloudTag)
		if err != nil {
			return result, errors.Trace(err)
		}
	} else {
		cloudTag = names.NewCloudTag(controllerModel.Cloud())
	}
	if cloudRegionName == "" && cloudTag.Id() == controllerModel.Cloud() {
		cloudRegionName = controllerModel.CloudRegion()
	}

	isAdmin, err := m.authorizer.HasPermission(permission.SuperuserAccess, m.state.ControllerTag())
	if err != nil {
		return result, errors.Trace(err)
	}
	if !isAdmin {
		canAddModel, err := m.checkAddModelPermission(cloudTag.Id(), m.apiUser)
		if err != nil {
			return result, errors.Trace(err)
		}
		if !canAddModel {
			return result, common.ErrPerm
		}
	}

	ownerTag, err := names.ParseUserTag(args.OwnerTag)
	if err != nil {
		return result, errors.Trace(err)
	}

	// a special case of ErrPerm will happen if the user has add-model permission but is trying to
	// create a model for another person, which is not yet supported.
	if !m.isAdmin && ownerTag != m.apiUser {
		return result, errors.Annotatef(common.ErrPerm, "%q permission does not permit creation of models for different owners", permission.AddModelAccess)
	}

	cloud, err := m.state.Cloud(cloudTag.Id())
	if err != nil {
		if errors.IsNotFound(err) && args.CloudTag != "" {
			// A cloud was specified, and it was not found.
			// Annotate the error with the supported clouds.
			clouds, err := m.state.Clouds()
			if err != nil {
				return result, errors.Trace(err)
			}
			cloudNames := make([]string, 0, len(clouds))
			for tag := range clouds {
				cloudNames = append(cloudNames, tag.Id())
			}
			sort.Strings(cloudNames)
			return result, errors.NewNotFound(err, fmt.Sprintf(
				"cloud %q not found, expected one of %q",
				cloudTag.Id(), cloudNames,
			))
		}
		return result, errors.Annotate(err, "getting cloud definition")
	}

	var cloudCredentialTag names.CloudCredentialTag
	if args.CloudCredentialTag != "" {
		var err error
		cloudCredentialTag, err = names.ParseCloudCredentialTag(args.CloudCredentialTag)
		if err != nil {
			return result, errors.Trace(err)
		}
	} else {
		if ownerTag == controllerModel.Owner() {
			cloudCredentialTag, _ = controllerModel.CloudCredential()
		} else {
			// TODO(axw) check if the user has one and only one
			// cloud credential, and if so, use it? For now, we
			// require the user to specify a credential unless
			// the cloud does not require one.
			var hasEmpty bool
			for _, authType := range cloud.AuthTypes {
				if authType != jujucloud.EmptyAuthType {
					continue
				}
				hasEmpty = true
				break
			}
			if !hasEmpty {
				return result, errors.NewNotValid(nil, "no credential specified")
			}
		}
	}

	var credential *jujucloud.Credential
	if cloudCredentialTag != (names.CloudCredentialTag{}) {
		credentialValue, err := m.state.CloudCredential(cloudCredentialTag)
		if err != nil {
			return result, errors.Annotate(err, "getting credential")
		}
		cloudCredential := jujucloud.NewNamedCredential(
			credentialValue.Name,
			jujucloud.AuthType(credentialValue.AuthType),
			credentialValue.Attributes,
			credentialValue.Revoked,
		)
		credential = &cloudCredential
	}

	cloudSpec, err := environs.MakeCloudSpec(cloud, cloudRegionName, credential)
	if err != nil {
		return result, errors.Trace(err)
	}

	var model common.Model

	if jujucloud.CloudIsCAAS(cloud) {
		model, err = m.newCAASModel(
			cloudSpec,
			args,
			cloudTag,
			cloudCredentialTag,
			ownerTag)
	} else {
		model, err = m.newModel(
			cloudSpec,
			args,
			controllerModel,
			cloudTag,
			cloudRegionName,
			cloudCredentialTag,
			ownerTag)
	}
	if err != nil {
		return result, errors.Trace(err)
	}
	return m.getModelInfo(model.ModelTag())
}
1119362
func NewClientWithCache(caller base.APICallCloser, cache *MacaroonCache) *Client {
	frontend, backend := base.NewClientFacade(caller, "CrossModelRelations")
	return &Client{
		ClientFacade: frontend,
		facade:       backend,
		cache:        cache,
	}
}
1356751
func NewAPIClient(cfg *Configuration) *APIClient {
	if cfg.HTTPClient == nil {
		cfg.HTTPClient = http.DefaultClient
	}

	c := &APIClient{}
	c.cfg = cfg
	c.common.client = c

	// API Services
	c.APIInfoApi = (*APIInfoApiService)(&c.common)
	c.AccountProvisioningApi = (*AccountProvisioningApiService)(&c.common)
	c.ApplicationSettingsApi = (*ApplicationSettingsApiService)(&c.common)
	c.CallHandlingSettingsApi = (*CallHandlingSettingsApiService)(&c.common)
	c.CallLogApi = (*CallLogApiService)(&c.common)
	c.CompanyContactsApi = (*CompanyContactsApiService)(&c.common)
	c.CompanySettingsApi = (*CompanySettingsApiService)(&c.common)
	c.GlipApi = (*GlipApiService)(&c.common)
	c.MeetingsApi = (*MeetingsApiService)(&c.common)
	c.MessagesApi = (*MessagesApiService)(&c.common)
	c.PhoneNumbersApi = (*PhoneNumbersApiService)(&c.common)
	c.PresenceApi = (*PresenceApiService)(&c.common)
	c.PushNotificationsApi = (*PushNotificationsApiService)(&c.common)
	c.RegionalSettingsApi = (*RegionalSettingsApiService)(&c.common)
	c.ReportingApi = (*ReportingApiService)(&c.common)
	c.RingOutApi = (*RingOutApiService)(&c.common)
	c.RolesAndPermissionsApi = (*RolesAndPermissionsApiService)(&c.common)
	c.SCIMApi = (*SCIMApiService)(&c.common)
	c.UserContactsApi = (*UserContactsApiService)(&c.common)
	c.UserSettingsApi = (*UserSettingsApiService)(&c.common)

	return c
}
487605
func NewFacadeV5(ctx facade.Context) (*ModelManagerAPIV5, error) {
	v6, err := NewFacadeV6(ctx)
	if err != nil {
		return nil, err
	}
	return &ModelManagerAPIV5{v6}, nil
}
732888
func NewModelConfigAPI(backend Backend, authorizer facade.Authorizer) (*ModelConfigAPIV2, error) {
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}
	client := &ModelConfigAPI{
		backend: backend,
		auth:    authorizer,
		check:   common.NewBlockChecker(backend),
	}
	return &ModelConfigAPIV2{client}, nil
}
882537
func NewAPI(caller base.APICaller) *API {
	facadeCaller := base.NewFacadeCaller(caller, cleanerFacade)
	return &API{facade: facadeCaller}
}
148629
func NewControllerAPIv5(ctx facade.Context) (*ControllerAPIv5, error) {
	v6, err := NewControllerAPIv6(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &ControllerAPIv5{v6}, nil
}
686023
func (c *cloudImageMetadataCommandBase) NewImageMetadataAPI() (*imagemetadatamanager.Client, error) {
	root, err := c.NewAPIRoot()
	if err != nil {
		return nil, err
	}
	return imagemetadatamanager.NewClient(root), nil
}
205760
func NewControllerAPIv7(ctx facade.Context) (*ControllerAPI, error) {
	st := ctx.State()
	authorizer := ctx.Auth()
	pool := ctx.StatePool()
	resources := ctx.Resources()
	presence := ctx.Presence()
	hub := ctx.Hub()

	return NewControllerAPI(
		st,
		pool,
		authorizer,
		resources,
		presence,
		hub,
	)
}
710706
func NewMockNetworkAPIClient(ctrl *gomock.Controller) *MockNetworkAPIClient {
	mock := &MockNetworkAPIClient{ctrl: ctrl}
	mock.recorder = &MockNetworkAPIClientMockRecorder{mock}
	return mock
}
1340968
func NewMachineManagerAPI(
	backend Backend,
	storageAccess storageInterface,
	pool Pool,
	auth facade.Authorizer,
	modelTag names.ModelTag,
	callCtx context.ProviderCallContext,
	resources facade.Resources,
) (*MachineManagerAPI, error) {
	if !auth.AuthClient() {
		return nil, common.ErrPerm
	}
	return &MachineManagerAPI{
		st:            backend,
		storageAccess: storageAccess,
		pool:          pool,
		authorizer:    auth,
		check:         common.NewBlockChecker(backend),
		modelTag:      modelTag,
		callContext:   callCtx,
		resources:     resources,
	}, nil
}
6634
func NewImageManagerAPI(st *state.State, resources facade.Resources, authorizer facade.Authorizer) (*ImageManagerAPI, error) {
	// Only clients can access the image manager service.
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}
	return &ImageManagerAPI{
		state:      getState(st),
		resources:  resources,
		authorizer: authorizer,
		check:      common.NewBlockChecker(st),
	}, nil
}
116494
func NewAPIClient(serverURL, caFile, keyFile, certFile, authToken string) *APIClient {
	useClientCerts := true
	c := APIClient{}

	c.apiServerPort = 6443 // default
	port := strings.Split(serverURL, ":")
	if len(port) > 0 {
		if v, err := strconv.ParseUint(port[len(port)-1], 10, 16); err == nil {
			c.apiServerPort = uint16(v)
		} else {
			log.Warnf("parse failed: %s, use default api server port: %d", err, c.apiServerPort)
		}
	}

	c.baseURL = serverURL + "/api/v1/namespaces/"
	c.watchBase = serverURL + "/api/v1/watch/"

	// Read CA cert
	ca, err := ioutil.ReadFile(caFile)
	if err != nil {
		log.Fatal(err)
		return nil
	}

	caPool := x509.NewCertPool()
	caPool.AppendCertsFromPEM(ca)

	// Read client cert
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	// We need either the client certs or a non-empty authToken to proceed
	if err != nil {
		// We cannot use client certs now
		useClientCerts = false
		// Check for a non-empty token
		if len(strings.TrimSpace(authToken)) == 0 {
			log.Fatalf("Error %s loading the client certificates and missing auth token", err)
			return nil
		}
	}
	// Setup HTTPS client
	tlsCfg := &tls.Config{
		RootCAs: caPool,
	}
	// Setup client cert based authentication
	if useClientCerts {
		tlsCfg.Certificates = []tls.Certificate{cert}
		tlsCfg.BuildNameToCertificate()
	}
	transport := &http.Transport{TLSClientConfig: tlsCfg}
	c.client = &http.Client{Transport: transport}
	c.authToken = authToken

	p := &c.podCache
	p.labels = make(map[string]string)
	p.nameSpace = ""
	p.name = ""

	return &c
}