当前位置: 首页>>代码示例>>Golang>>正文


Golang environs.New函数代码示例

本文整理汇总了Golang中github.com/juju/juju/environs.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: EnvironConfig

// EnvironConfig returns the current environment's configuration.
func (e *EnvironWatcher) EnvironConfig() (params.EnvironConfigResult, error) {
	result := params.EnvironConfigResult{}

	config, err := e.st.EnvironConfig()
	if err != nil {
		return result, err
	}
	allAttrs := config.AllAttrs()

	if !e.authorizer.AuthEnvironManager() {
		// Mask out any secrets in the environment configuration
		// with values of the same type, so it'll pass validation.
		//
		// TODO(dimitern) 201309-26 bug #1231384
		// Delete the code below and mark the bug as fixed,
		// once it's live tested on MAAS and 1.16 compatibility
		// is dropped.
		env, err := environs.New(config)
		if err != nil {
			return result, err
		}
		secretAttrs, err := env.Provider().SecretAttrs(config)
		for k := range secretAttrs {
			allAttrs[k] = "not available"
		}
	}
	result.Config = allAttrs
	return result, nil
}
开发者ID:kapilt,项目名称:juju,代码行数:30,代码来源:environwatcher.go

示例2: TestMachineConfig

func (s *machineConfigSuite) TestMachineConfig(c *gc.C) {
	addrs := []network.Address{network.NewAddress("1.2.3.4", network.ScopeUnknown)}
	hc := instance.MustParseHardware("mem=4G arch=amd64")
	apiParams := params.AddMachineParams{
		Jobs:       []params.MachineJob{params.JobHostUnits},
		InstanceId: instance.Id("1234"),
		Nonce:      "foo",
		HardwareCharacteristics: hc,
		Addrs: addrs,
	}
	machines, err := s.APIState.Client().AddMachines([]params.AddMachineParams{apiParams})
	c.Assert(err, gc.IsNil)
	c.Assert(len(machines), gc.Equals, 1)

	machineId := machines[0].Machine
	machineConfig, err := client.MachineConfig(s.State, machineId, apiParams.Nonce, "")
	c.Assert(err, gc.IsNil)

	envConfig, err := s.State.EnvironConfig()
	c.Assert(err, gc.IsNil)
	env, err := environs.New(envConfig)
	c.Assert(err, gc.IsNil)
	stateInfo, apiInfo, err := env.StateInfo()
	c.Assert(err, gc.IsNil)
	c.Check(machineConfig.StateInfo.Addrs, gc.DeepEquals, stateInfo.Addrs)
	c.Check(machineConfig.APIInfo.Addrs, gc.DeepEquals, apiInfo.Addrs)
	c.Assert(machineConfig.Tools.URL, gc.Not(gc.Equals), "")
}
开发者ID:rogpeppe,项目名称:juju,代码行数:28,代码来源:machineconfig_test.go

示例3: prepareContainerAccessEnvironment

// prepareContainerAccessEnvironment retrieves the environment, host machine, and access
// for working with containers.
func (p *ProvisionerAPI) prepareContainerAccessEnvironment() (environs.NetworkingEnviron, *state.Machine, common.AuthFunc, error) {
	cfg, err := p.st.EnvironConfig()
	if err != nil {
		return nil, nil, nil, errors.Annotate(err, "failed to get environment config")
	}
	environ, err := environs.New(cfg)
	if err != nil {
		return nil, nil, nil, errors.Annotate(err, "failed to construct an environment from config")
	}
	netEnviron, supported := environs.SupportsNetworking(environ)
	if !supported {
		// " not supported" will be appended to the message below.
		return nil, nil, nil, errors.NotSupportedf("environment %q networking", cfg.Name())
	}

	canAccess, err := p.getAuthFunc()
	if err != nil {
		return nil, nil, nil, errors.Annotate(err, "cannot authenticate request")
	}
	hostAuthTag := p.authorizer.GetAuthTag()
	if hostAuthTag == nil {
		return nil, nil, nil, errors.Errorf("authenticated entity tag is nil")
	}
	hostTag, err := names.ParseMachineTag(hostAuthTag.String())
	if err != nil {
		return nil, nil, nil, errors.Trace(err)
	}
	host, err := p.getMachine(canAccess, hostTag)
	if err != nil {
		return nil, nil, nil, errors.Trace(err)
	}
	return netEnviron, host, canAccess, nil
}
开发者ID:kakamessi99,项目名称:juju,代码行数:35,代码来源:provisioner.go

示例4: processGet

// processGet handles a tools GET request.
func (h *toolsDownloadHandler) processGet(r *http.Request) (*tools.Tools, utils.SSLHostnameVerification, error) {
	version, err := version.ParseBinary(r.URL.Query().Get(":version"))
	if err != nil {
		return nil, false, err
	}
	cfg, err := h.state.EnvironConfig()
	if err != nil {
		return nil, false, err
	}
	env, err := environs.New(cfg)
	if err != nil {
		return nil, false, err
	}
	filter := tools.Filter{
		Number: version.Number,
		Series: version.Series,
		Arch:   version.Arch,
	}
	tools, err := envtools.FindTools(env, version.Major, version.Minor, filter, false)
	if err != nil {
		return nil, false, errors.Annotate(err, "failed to find tools")
	}
	verify := utils.SSLHostnameVerification(cfg.SSLHostnameVerification())
	return tools[0], verify, nil
}
开发者ID:kapilt,项目名称:juju,代码行数:26,代码来源:tools.go

示例5: TestNewModelConfig

func (s *configSuite) TestNewModelConfig(c *gc.C) {

	type checker struct {
		checker gc.Checker
		value   interface{}
	}

	var newConfigTests = []struct {
		info   string
		insert testing.Attrs
		remove []string
		expect testing.Attrs
		err    string
	}{{
		info:   "username is required",
		remove: []string{"username"},
		err:    "username: must not be empty",
	}, {
		info:   "username cannot be empty",
		insert: testing.Attrs{"username": ""},
		err:    "username: must not be empty",
	}, {
		info:   "password is required",
		remove: []string{"password"},
		err:    "password: must not be empty",
	}, {
		info:   "password cannot be empty",
		insert: testing.Attrs{"password": ""},
		err:    "password: must not be empty",
	}, {
		info:   "region is inserted if missing",
		remove: []string{"region"},
		expect: testing.Attrs{"region": "zrh"},
	}, {
		info:   "region must not be empty",
		insert: testing.Attrs{"region": ""},
		err:    "region: must not be empty",
	}}

	for i, test := range newConfigTests {
		c.Logf("test %d: %s", i, test.info)
		attrs := validAttrs().Merge(test.insert).Delete(test.remove...)
		testConfig := newConfig(c, attrs)
		environ, err := environs.New(testConfig)
		if test.err == "" {
			c.Check(err, gc.IsNil)
			attrs := environ.Config().AllAttrs()
			for field, value := range test.expect {
				if chk, ok := value.(checker); ok {
					c.Check(attrs[field], chk.checker, chk.value)
				} else {
					c.Check(attrs[field], gc.Equals, value)
				}
			}
		} else {
			c.Check(environ, gc.IsNil)
			c.Check(err, gc.ErrorMatches, test.err)
		}
	}
}
开发者ID:xushiwei,项目名称:juju,代码行数:60,代码来源:config_test.go

示例6: assertStartInstanceDefaultSecurityGroup

func (s *LiveTests) assertStartInstanceDefaultSecurityGroup(c *gc.C, useDefault bool) {
	attrs := s.TestConfig.Merge(coretesting.Attrs{
		"name":                 "sample-" + randomName(),
		"control-bucket":       "juju-test-" + randomName(),
		"use-default-secgroup": useDefault,
	})
	cfg, err := config.New(config.NoDefaults, attrs)
	c.Assert(err, gc.IsNil)
	// Set up a test environment.
	env, err := environs.New(cfg)
	c.Assert(err, gc.IsNil)
	c.Assert(env, gc.NotNil)
	defer env.Destroy()
	// Bootstrap and start an instance.
	err = bootstrap.Bootstrap(coretesting.Context(c), env, environs.BootstrapParams{})
	c.Assert(err, gc.IsNil)
	inst, _ := jujutesting.AssertStartInstance(c, env, "100")
	// Check whether the instance has the default security group assigned.
	novaClient := openstack.GetNovaClient(env)
	groups, err := novaClient.GetServerSecurityGroups(string(inst.Id()))
	c.Assert(err, gc.IsNil)
	defaultGroupFound := false
	for _, group := range groups {
		if group.Name == "default" {
			defaultGroupFound = true
			break
		}
	}
	c.Assert(defaultGroupFound, gc.Equals, useDefault)
}
开发者ID:jiasir,项目名称:juju,代码行数:30,代码来源:live_test.go

示例7: stateStepsFor125

// stateStepsFor125 returns upgrade steps for Juju 1.25 that manipulate state directly.
func stateStepsFor125() []Step {
	return []Step{
		&upgradeStep{
			description: "set hosted environment count to number of hosted environments",
			targets:     []Target{DatabaseMaster},
			run: func(context Context) error {
				return state.SetHostedEnvironCount(context.State())
			},
		},
		&upgradeStep{
			description: "tag machine instances",
			targets:     []Target{DatabaseMaster},
			run: func(context Context) error {
				st := context.State()
				machines, err := st.AllMachines()
				if err != nil {
					return errors.Trace(err)
				}
				cfg, err := st.EnvironConfig()
				if err != nil {
					return errors.Trace(err)
				}
				env, err := environs.New(cfg)
				if err != nil {
					return errors.Trace(err)
				}
				return addInstanceTags(env, machines)
			},
		},
	}
}
开发者ID:frankban,项目名称:juju-tmp,代码行数:32,代码来源:steps125.go

示例8: TestAddressesWithoutPublicIP

func (s *localServerSuite) TestAddressesWithoutPublicIP(c *gc.C) {
	bootstrapFinished := false
	s.PatchValue(&common.FinishBootstrap, func(ctx environs.BootstrapContext, client ssh.Client, inst instance.Instance, machineConfig *cloudinit.MachineConfig) error {
		addr, err := inst.Addresses()
		c.Assert(err, gc.IsNil)
		c.Assert(addr, jc.SameContents, []network.Address{
			{Value: "127.0.0.1", Type: "ipv4", NetworkName: "private", Scope: "local-machine"},
			{Value: "::face::000f", Type: "hostname", NetworkName: "private", Scope: ""},
			{Value: "127.10.0.1", Type: "ipv4", NetworkName: "public", Scope: "public"},
			{Value: "::dead:beef:f00d", Type: "ipv6", NetworkName: "public", Scope: "public"},
		})
		bootstrapFinished = true
		return nil
	})

	cfg, err := config.New(config.NoDefaults, s.TestConfig.Merge(coretesting.Attrs{
		"use-floating-ip": false,
	}))
	c.Assert(err, gc.IsNil)
	env, err := environs.New(cfg)
	c.Assert(err, gc.IsNil)
	err = bootstrap.Bootstrap(coretesting.Context(c), env, bootstrap.BootstrapParams{})
	c.Assert(err, gc.IsNil)
	c.Assert(bootstrapFinished, jc.IsTrue)
}
开发者ID:kapilt,项目名称:juju,代码行数:25,代码来源:local_test.go

示例9: MachineConfig

// MachineConfig returns information from the environment config that is
// needed for machine cloud-init (for non-state servers only).
// It is exposed for testing purposes.
// TODO(rog) fix environs/manual tests so they do not need to
// call this, or move this elsewhere.
func MachineConfig(st *state.State, machineId, nonce, dataDir string) (*cloudinit.MachineConfig, error) {
	environConfig, err := st.EnvironConfig()
	if err != nil {
		return nil, err
	}

	// Get the machine so we can get its series and arch.
	// If the Arch is not set in hardware-characteristics,
	// an error is returned.
	machine, err := st.Machine(machineId)
	if err != nil {
		return nil, err
	}
	hc, err := machine.HardwareCharacteristics()
	if err != nil {
		return nil, err
	}
	if hc.Arch == nil {
		return nil, fmt.Errorf("arch is not set for %q", machine.Tag())
	}

	// Find the appropriate tools information.
	env, err := environs.New(environConfig)
	if err != nil {
		return nil, err
	}
	tools, err := findInstanceTools(env, machine.Series(), *hc.Arch)
	if err != nil {
		return nil, err
	}

	// Find the API endpoints.
	apiInfo, err := environs.APIInfo(env)
	if err != nil {
		return nil, err
	}

	auth := authentication.NewAuthenticator(st.MongoConnectionInfo(), apiInfo)
	mongoInfo, apiInfo, err := auth.SetupAuthentication(machine)
	if err != nil {
		return nil, err
	}

	// Find requested networks.
	networks, err := machine.RequestedNetworks()
	if err != nil {
		return nil, err
	}

	mcfg := environs.NewMachineConfig(machineId, nonce, networks, mongoInfo, apiInfo)
	if dataDir != "" {
		mcfg.DataDir = dataDir
	}
	mcfg.Tools = tools
	err = environs.FinishMachineConfig(mcfg, environConfig, constraints.Value{})
	if err != nil {
		return nil, err
	}
	return mcfg, nil
}
开发者ID:jiasir,项目名称:juju,代码行数:65,代码来源:machineconfig.go

示例10: apiConfigConnect

// apiConfigConnect looks for configuration info on the given environment,
// and tries to use an Environ constructed from that to connect to
// its endpoint. It only starts the attempt after the given delay,
// to allow the faster apiInfoConnect to hopefully succeed first.
// It returns nil if there was no configuration information found.
func apiConfigConnect(
	cfg *config.Config,
	accountDetails *jujuclient.AccountDetails,
	modelUUID string,
	apiOpen api.OpenFunc,
	stop <-chan struct{},
	delay time.Duration,
	dialOpts api.DialOpts,
) (api.Connection, error) {
	select {
	case <-time.After(delay):
		// TODO(fwereade): 2016-03-17 lp:1558657
	case <-stop:
		return nil, errAborted
	}
	environ, err := environs.New(cfg)
	if err != nil {
		return nil, errors.Annotate(err, "constructing environ")
	}
	apiInfo, err := environs.APIInfo(environ)
	if err != nil {
		return nil, errors.Annotate(err, "getting API info")
	}
	st, err := commonConnect(apiOpen, apiInfo, accountDetails, modelUUID, dialOpts)
	if err != nil {
		return nil, errors.Annotate(err, "connecting with bootstrap config")
	}
	return apiStateCachedInfo{st, apiInfo}, nil
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:34,代码来源:api.go

示例11: NewTracker

// NewTracker loads an environment from the observer and returns a new Tracker,
// or an error if anything goes wrong. If a tracker is returned, its Environ()
// method is immediately usable.
//
// The caller is responsible for Kill()ing the returned Tracker and Wait()ing
// for any errors it might return.
func NewTracker(config Config) (*Tracker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}
	environConfig, err := config.Observer.EnvironConfig()
	if err != nil {
		return nil, errors.Annotate(err, "cannot read environ config")
	}
	environ, err := environs.New(environConfig)
	if err != nil {
		return nil, errors.Annotate(err, "cannot create environ")
	}

	t := &Tracker{
		config:  config,
		environ: environ,
	}
	err = catacomb.Invoke(catacomb.Plan{
		Site: &t.catacomb,
		Work: t.loop,
	})
	if err != nil {
		return nil, errors.Trace(err)
	}
	return t, nil
}
开发者ID:felicianotech,项目名称:juju,代码行数:32,代码来源:environ.go

示例12: addCharm

func addCharm(st *state.State, curl *charm.URL, ch charm.Charm) (*state.Charm, error) {
	var f *os.File
	name := charm.Quote(curl.String())
	switch ch := ch.(type) {
	case *charm.CharmDir:
		var err error
		if f, err = ioutil.TempFile("", name); err != nil {
			return nil, err
		}
		defer os.Remove(f.Name())
		defer f.Close()
		err = ch.ArchiveTo(f)
		if err != nil {
			return nil, fmt.Errorf("cannot bundle charm: %v", err)
		}
		if _, err := f.Seek(0, 0); err != nil {
			return nil, err
		}
	case *charm.CharmArchive:
		var err error
		if f, err = os.Open(ch.Path); err != nil {
			return nil, fmt.Errorf("cannot read charm bundle: %v", err)
		}
		defer f.Close()
	default:
		return nil, fmt.Errorf("unknown charm type %T", ch)
	}
	digest, size, err := utils.ReadSHA256(f)
	if err != nil {
		return nil, err
	}
	if _, err := f.Seek(0, 0); err != nil {
		return nil, err
	}
	cfg, err := st.EnvironConfig()
	if err != nil {
		return nil, err
	}
	env, err := environs.New(cfg)
	if err != nil {
		return nil, err
	}
	stor := env.Storage()
	if err := stor.Put(name, f, size); err != nil {
		return nil, fmt.Errorf("cannot put charm: %v", err)
	}
	ustr, err := stor.URL(name)
	if err != nil {
		return nil, fmt.Errorf("cannot get storage URL for charm: %v", err)
	}
	u, err := url.Parse(ustr)
	if err != nil {
		return nil, fmt.Errorf("cannot parse storage URL: %v", err)
	}
	sch, err := st.AddCharm(ch, curl, u, digest)
	if err != nil {
		return nil, fmt.Errorf("cannot add charm: %v", err)
	}
	return sch, nil
}
开发者ID:kapilt,项目名称:juju,代码行数:60,代码来源:conn.go

示例13: getControllerEnvironFromAPI

func (c *destroyCommandBase) getControllerEnvironFromAPI(
	api destroyControllerAPI,
	controllerName string,
) (environs.Environ, error) {
	if api == nil {
		return nil, errors.New(
			"unable to get bootstrap information from client store or API",
		)
	}
	attrs, err := api.ModelConfig()
	if err != nil {
		return nil, errors.Annotate(err, "getting model config from API")
	}
	cfg, err := config.New(config.NoDefaults, attrs)
	if err != nil {
		return nil, errors.Trace(err)
	}
	cloudSpec, err := api.CloudSpec(names.NewModelTag(cfg.UUID()))
	if err != nil {
		return nil, errors.Annotate(err, "getting cloud spec from API")
	}
	return environs.New(environs.OpenParams{
		Cloud:  cloudSpec,
		Config: cfg,
	})
}
开发者ID:bac,项目名称:juju,代码行数:26,代码来源:destroy.go

示例14: TestBase

func (s *environSuite) TestBase(c *gc.C) {
	baseConfig := newConfig(c, validAttrs().Merge(testing.Attrs{"name": "testname"}))
	env, err := environs.New(environs.OpenParams{
		Cloud:  fakeCloudSpec(),
		Config: baseConfig,
	})
	c.Assert(err, gc.IsNil)

	cfg := env.Config()
	c.Assert(cfg, gc.NotNil)
	c.Check(cfg.Name(), gc.Equals, "testname")

	c.Check(env.PrecheckInstance("", constraints.Value{}, ""), gc.IsNil)

	hasRegion, ok := env.(simplestreams.HasRegion)
	c.Check(ok, gc.Equals, true)
	c.Assert(hasRegion, gc.NotNil)

	cloudSpec, err := hasRegion.Region()
	c.Assert(err, gc.IsNil)
	c.Check(cloudSpec.Region, gc.Not(gc.Equals), "")
	c.Check(cloudSpec.Endpoint, gc.Not(gc.Equals), "")

	c.Check(env.OpenPorts(nil), gc.IsNil)
	c.Check(env.ClosePorts(nil), gc.IsNil)
	ports, err := env.Ports()
	c.Assert(err, gc.IsNil)
	c.Check(ports, gc.IsNil)
}
开发者ID:bac,项目名称:juju,代码行数:29,代码来源:environ_test.go

示例15: NewEnvironObserver

// NewEnvironObserver waits for the environment to have a valid
// environment configuration and returns a new environment observer.
// While waiting for the first environment configuration, it will
// return with tomb.ErrDying if it receives a value on dying.
func NewEnvironObserver(st EnvironConfigObserver) (*EnvironObserver, error) {
	config, err := st.EnvironConfig()
	if err != nil {
		return nil, err
	}
	environ, err := environs.New(config)
	if err != nil {
		return nil, errors.Annotate(err, "cannot create an environment")
	}
	environWatcher, err := st.WatchForEnvironConfigChanges()
	if err != nil {
		return nil, errors.Annotate(err, "cannot watch environment config")
	}
	obs := &EnvironObserver{
		st:             st,
		environ:        environ,
		environWatcher: environWatcher,
	}
	go func() {
		defer obs.tomb.Done()
		defer watcher.Stop(environWatcher, &obs.tomb)
		obs.tomb.Kill(obs.loop())
	}()
	return obs, nil
}
开发者ID:imoapps,项目名称:juju,代码行数:29,代码来源:environ.go


注:本文中的github.com/juju/juju/environs.New函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。