本文整理汇总了Golang中github.com/juju/juju/environs.Environ.Config方法的典型用法代码示例。如果您正苦于以下问题:Golang Environ.Config方法的具体用法?Golang Environ.Config怎么用?Golang Environ.Config使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/juju/juju/environs.Environ
的用法示例。
在下文中一共展示了Environ.Config方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: validateUploadAllowed
// validateUploadAllowed returns an error if an attempt to upload tools should
// not be allowed.
func validateUploadAllowed(env environs.Environ, toolsArch, toolsSeries *string, validator constraints.Validator) error {
// Now check that the architecture and series for which we are setting up an
// environment matches that from which we are bootstrapping.
hostArch := arch.HostArch()
// We can't build tools for a different architecture if one is specified.
if toolsArch != nil && *toolsArch != hostArch {
return fmt.Errorf("cannot use agent built for %q using a machine running on %q", *toolsArch, hostArch)
}
hostOS := jujuos.HostOS()
if toolsSeries != nil {
toolsSeriesOS, err := series.GetOSFromSeries(*toolsSeries)
if err != nil {
return errors.Trace(err)
}
if !toolsSeriesOS.EquivalentTo(hostOS) {
return errors.Errorf("cannot use agent built for %q using a machine running %q", *toolsSeries, hostOS)
}
}
// If no architecture is specified, ensure the target provider supports instances matching our architecture.
if _, err := validator.Validate(constraints.Value{Arch: &hostArch}); err != nil {
return errors.Errorf(
"model %q of type %s does not support instances running on %q",
env.Config().Name(), env.Config().Type(), hostArch,
)
}
return nil
}
示例2: Bootstrap
// Bootstrap bootstraps the given environment. The supplied constraints are
// used to provision the instance, and are also set within the bootstrapped
// environment.
func Bootstrap(ctx environs.BootstrapContext, environ environs.Environ, args environs.BootstrapParams) error {
cfg := environ.Config()
network.InitializeFromConfig(cfg)
if secret := cfg.AdminSecret(); secret == "" {
return fmt.Errorf("environment configuration has no admin-secret")
}
if authKeys := ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys()); len(authKeys) == 0 {
// Apparently this can never happen, so it's not tested. But, one day,
// Config will act differently (it's pretty crazy that, AFAICT, the
// authorized-keys are optional config settings... but it's impossible
// to actually *create* a config without them)... and when it does,
// we'll be here to catch this problem early.
return fmt.Errorf("environment configuration has no authorized-keys")
}
if _, hasCACert := cfg.CACert(); !hasCACert {
return fmt.Errorf("environment configuration has no ca-cert")
}
if _, hasCAKey := cfg.CAPrivateKey(); !hasCAKey {
return fmt.Errorf("environment configuration has no ca-private-key")
}
// Write out the bootstrap-init file, and confirm storage is writeable.
if err := environs.VerifyStorage(environ.Storage()); err != nil {
return err
}
logger.Debugf("environment %q supports service/machine networks: %v", environ.Name(), environ.SupportNetworks())
logger.Infof("bootstrapping environment %q", environ.Name())
return environ.Bootstrap(ctx, args)
}
示例3: assertEnvironDestroyed
func assertEnvironDestroyed(c *gc.C, env environs.Environ, store configstore.Storage) {
_, err := store.ReadInfo(env.Config().Name())
c.Assert(err, jc.Satisfies, errors.IsNotFound)
_, err = env.Instances([]instance.Id{"invalid"})
c.Assert(err, gc.ErrorMatches, "environment has been destroyed")
}
示例4: makeFakeUpstartScripts
func (s *localJujuTestSuite) makeFakeUpstartScripts(c *gc.C, env environs.Environ,
) (mongoService *upstart.Service, machineAgent *upstart.Service) {
upstartDir := c.MkDir()
s.PatchValue(&upstart.InitDir, upstartDir)
s.MakeTool(c, "start", `echo "some-service start/running, process 123"`)
namespace := env.Config().AllAttrs()["namespace"].(string)
mongoConf := common.Conf{
Desc: "fake mongo",
Cmd: "echo FAKE",
}
mongoService = upstart.NewService(mongo.ServiceName(namespace), mongoConf)
err := mongoService.Install()
c.Assert(err, gc.IsNil)
c.Assert(mongoService.Installed(), jc.IsTrue)
agentConf := common.Conf{
Desc: "fake agent",
Cmd: "echo FAKE",
}
machineAgent = upstart.NewService(fmt.Sprintf("juju-agent-%s", namespace), agentConf)
err = machineAgent.Install()
c.Assert(err, gc.IsNil)
c.Assert(machineAgent.Installed(), jc.IsTrue)
return mongoService, machineAgent
}
示例5: destroyStorage
func destroyStorage(env environs.Environ) error {
logger.Infof("destroying storage")
environConfig := env.Config()
storageProviderTypes, ok := registry.EnvironStorageProviders(environConfig.Type())
if !ok {
return nil
}
for _, storageProviderType := range storageProviderTypes {
storageProvider, err := registry.StorageProvider(storageProviderType)
if err != nil {
return errors.Trace(err)
}
if !storageProvider.Dynamic() {
continue
}
if storageProvider.Scope() != storage.ScopeEnviron {
continue
}
if err := destroyVolumes(environConfig, storageProviderType, storageProvider); err != nil {
return errors.Trace(err)
}
// TODO(axw) destroy env-level filesystems when we have them.
}
return nil
}
示例6: newState
// newState returns a new State that uses the given environment.
// The environment must have already been bootstrapped.
func newState(environ environs.Environ, mongoInfo *mongo.MongoInfo) (*state.State, error) {
config := environ.Config()
password := config.AdminSecret()
if password == "" {
return nil, fmt.Errorf("cannot connect without admin-secret")
}
modelTag := names.NewModelTag(config.UUID())
mongoInfo.Password = password
opts := mongo.DefaultDialOpts()
st, err := state.Open(modelTag, mongoInfo, opts, environs.NewStatePolicy())
if errors.IsUnauthorized(errors.Cause(err)) {
// We try for a while because we might succeed in
// connecting to mongo before the state has been
// initialized and the initial password set.
for a := redialStrategy.Start(); a.Next(); {
st, err = state.Open(modelTag, mongoInfo, opts, environs.NewStatePolicy())
if !errors.IsUnauthorized(errors.Cause(err)) {
break
}
}
if err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
if err := updateSecrets(environ, st); err != nil {
st.Close()
return nil, fmt.Errorf("unable to push secrets: %v", err)
}
return st, nil
}
示例7: SetImageMetadata
func SetImageMetadata(env environs.Environ, series, arches []string, out *[]*imagemetadata.ImageMetadata) error {
hasRegion, ok := env.(simplestreams.HasRegion)
if !ok {
return nil
}
sources, err := environs.ImageMetadataSources(env)
if err != nil {
return errors.Trace(err)
}
region, err := hasRegion.Region()
if err != nil {
return errors.Trace(err)
}
imageConstraint := imagemetadata.NewImageConstraint(simplestreams.LookupParams{
CloudSpec: region,
Series: series,
Arches: arches,
Stream: env.Config().ImageStream(),
})
imageMetadata, _, err := imagemetadata.Fetch(sources, imageConstraint)
if err != nil {
return errors.Trace(err)
}
*out = imageMetadata
return nil
}
示例8: setBootstrapEndpointAddress
// setBootstrapEndpointAddress writes the API endpoint address of the
// bootstrap server into the connection information. This should only be run
// once directly after Bootstrap. It assumes that there is just one instance
// in the environment - the bootstrap instance.
func (c *bootstrapCommand) setBootstrapEndpointAddress(environ environs.Environ) error {
instances, err := allInstances(environ)
if err != nil {
return errors.Trace(err)
}
length := len(instances)
if length == 0 {
return errors.Errorf("found no instances, expected at least one")
}
if length > 1 {
logger.Warningf("expected one instance, got %d", length)
}
bootstrapInstance := instances[0]
// Don't use c.ConnectionEndpoint as it attempts to contact the state
// server if no addresses are found in connection info.
netAddrs, err := bootstrapInstance.Addresses()
if err != nil {
return errors.Annotate(err, "failed to get bootstrap instance addresses")
}
cfg := environ.Config()
apiPort := cfg.APIPort()
apiHostPorts := network.AddressesWithPort(netAddrs, apiPort)
return juju.UpdateControllerAddresses(c.ClientStore(), c.controllerName, nil, apiHostPorts...)
}
示例9: makeFakeInitScripts
func (s *localJujuTestSuite) makeFakeInitScripts(c *gc.C, env environs.Environ) (installable, installable) {
s.MakeTool(c, "start", `echo "some-service start/running, process 123"`)
namespace := env.Config().AllAttrs()["namespace"].(string)
// Mongo first...
mongoName := mongo.ServiceName(namespace)
mongoConf := common.Conf{
Desc: "fake mongo",
ExecStart: "echo FAKE",
}
mongoService := local.NewService(mongoName, mongoConf, s.svcData)
s.svcData.SetStatus(mongoName, "installed")
installed, err := mongoService.Installed()
c.Assert(err, jc.ErrorIsNil)
c.Check(installed, jc.IsTrue)
// ...then the machine agent
agentName := fmt.Sprintf("juju-agent-%s", namespace)
agentConf := common.Conf{
Desc: "fake agent",
ExecStart: "echo FAKE",
}
agentService := local.NewService(agentName, agentConf, s.svcData)
s.svcData.SetStatus(agentName, "installed")
installed, err = agentService.Installed()
c.Assert(err, jc.ErrorIsNil)
c.Check(installed, jc.IsTrue)
return mongoService, agentService
}
示例10: StateInfo
// StateInfo is a reusable implementation of Environ.StateInfo, available to
// providers that also use the other functionality from this file.
func StateInfo(env environs.Environ) (*state.Info, *api.Info, error) {
st, err := bootstrap.LoadState(env.Storage())
if err != nil {
return nil, nil, err
}
config := env.Config()
if _, hasCert := config.CACert(); !hasCert {
return nil, nil, fmt.Errorf("no CA certificate in environment configuration")
}
// Wait for the addresses of at least one of the instances to become available.
logger.Debugf("waiting for addresses of state server instances %v", st.StateInstances)
var addresses []string
for a := LongAttempt.Start(); len(addresses) == 0 && a.Next(); {
insts, err := env.Instances(st.StateInstances)
if err != nil && err != environs.ErrPartialInstances {
logger.Debugf("error getting state instances: %v", err.Error())
return nil, nil, err
}
addresses = getAddresses(insts)
}
if len(addresses) == 0 {
return nil, nil, fmt.Errorf("timed out waiting for addresses from %v", st.StateInstances)
}
stateInfo, apiInfo := getStateInfo(config, addresses)
return stateInfo, apiInfo, nil
}
示例11: validateUploadAllowed
// validateUploadAllowed returns an error if an attempt to upload tools should
// not be allowed.
func validateUploadAllowed(env environs.Environ, toolsArch *string) error {
// Now check that the architecture for which we are setting up an
// environment matches that from which we are bootstrapping.
hostArch := arch.HostArch()
// We can't build tools for a different architecture if one is specified.
if toolsArch != nil && *toolsArch != hostArch {
return fmt.Errorf("cannot build tools for %q using a machine running on %q", *toolsArch, hostArch)
}
// If no architecture is specified, ensure the target provider supports instances matching our architecture.
supportedArchitectures, err := env.SupportedArchitectures()
if err != nil {
return fmt.Errorf(
"no packaged tools available and cannot determine environment's supported architectures: %v", err)
}
archSupported := false
for _, arch := range supportedArchitectures {
if hostArch == arch {
archSupported = true
break
}
}
if !archSupported {
envType := env.Config().Type()
return errors.Errorf("environment %q of type %s does not support instances running on %q", env.Config().Name(), envType, hostArch)
}
return nil
}
示例12: GetMetadataSources
// GetMetadataSources returns the sources to use when looking for
// simplestreams tools metadata for the given stream.
func GetMetadataSources(env environs.Environ) ([]simplestreams.DataSource, error) {
config := env.Config()
// Add configured and environment-specific datasources.
var sources []simplestreams.DataSource
if userURL, ok := config.AgentMetadataURL(); ok {
verify := utils.VerifySSLHostnames
if !config.SSLHostnameVerification() {
verify = utils.NoVerifySSLHostnames
}
sources = append(sources, simplestreams.NewURLSignedDataSource(conf.AgentMetadataURLKey, userURL, juju.JujuPublicKey, verify, simplestreams.SPECIFIC_CLOUD_DATA, false))
}
envDataSources, err := environmentDataSources(env)
if err != nil {
return nil, err
}
sources = append(sources, envDataSources...)
// Add the default, public datasource.
defaultURL, err := ToolsURL(DefaultBaseURL)
if err != nil {
return nil, err
}
if defaultURL != "" {
sources = append(sources,
simplestreams.NewURLSignedDataSource("default simplestreams", defaultURL, juju.JujuPublicKey, utils.VerifySSLHostnames, simplestreams.DEFAULT_CLOUD_DATA, true))
}
return sources, nil
}
示例13: StartInstanceWithParams
// StartInstanceWithParams is a test helper function that starts an instance
// with the given parameters, and a plausible but invalid configuration, and
// returns the result of Environ.StartInstance. The provided params's
// MachineConfig and Tools field values will be ignored.
func StartInstanceWithParams(
env environs.Environ, machineId string,
params environs.StartInstanceParams,
networks []string,
) (
instance.Instance, *instance.HardwareCharacteristics, []network.Info, error,
) {
series := config.PreferredSeries(env.Config())
agentVersion, ok := env.Config().AgentVersion()
if !ok {
return nil, nil, nil, fmt.Errorf("missing agent version in environment config")
}
possibleTools, err := tools.FindInstanceTools(
env, agentVersion, series, params.Constraints.Arch,
)
if err != nil {
return nil, nil, nil, err
}
machineNonce := "fake_nonce"
stateInfo := FakeStateInfo(machineId)
apiInfo := FakeAPIInfo(machineId)
machineConfig := environs.NewMachineConfig(
machineId, machineNonce,
networks,
stateInfo, apiInfo)
params.Tools = possibleTools
params.MachineConfig = machineConfig
return env.StartInstance(params)
}
示例14: StartInstanceWithParams
// StartInstanceWithParams is a test helper function that starts an instance
// with the given parameters, and a plausible but invalid configuration, and
// returns the result of Environ.StartInstance. The provided params's
// InstanceConfig and Tools field values will be ignored.
func StartInstanceWithParams(
env environs.Environ, machineId string,
params environs.StartInstanceParams,
networks []string,
) (
*environs.StartInstanceResult, error,
) {
preferredSeries := config.PreferredSeries(env.Config())
agentVersion, ok := env.Config().AgentVersion()
if !ok {
return nil, errors.New("missing agent version in model config")
}
filter := coretools.Filter{
Number: agentVersion,
Series: preferredSeries,
}
if params.Constraints.Arch != nil {
filter.Arch = *params.Constraints.Arch
}
stream := tools.PreferredStream(&agentVersion, env.Config().Development(), env.Config().AgentStream())
possibleTools, err := tools.FindTools(env, -1, -1, stream, filter)
if err != nil {
return nil, errors.Trace(err)
}
if params.ImageMetadata == nil {
if err := SetImageMetadata(
env,
possibleTools.AllSeries(),
possibleTools.Arches(),
¶ms.ImageMetadata,
); err != nil {
return nil, errors.Trace(err)
}
}
machineNonce := "fake_nonce"
stateInfo := FakeStateInfo(machineId)
apiInfo := FakeAPIInfo(machineId)
instanceConfig, err := instancecfg.NewInstanceConfig(
machineId,
machineNonce,
imagemetadata.ReleasedStream,
preferredSeries,
"",
true,
networks,
stateInfo,
apiInfo,
)
if err != nil {
return nil, errors.Trace(err)
}
eUUID, _ := env.Config().UUID()
instanceConfig.Tags[tags.JujuModel] = eUUID
params.Tools = possibleTools
params.InstanceConfig = instanceConfig
return env.StartInstance(params)
}
示例15: assertEnvironNotDestroyed
func assertEnvironNotDestroyed(c *gc.C, env environs.Environ, store configstore.Storage) {
info, err := store.ReadInfo(env.Config().Name())
c.Assert(err, gc.IsNil)
c.Assert(info.Initialized(), jc.IsTrue)
_, err = environs.NewFromName(env.Config().Name(), store)
c.Assert(err, gc.IsNil)
}