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


Golang utils.NewUUID函数代码示例

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


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

示例1: TestPendingOkay

func (s *UploadSuite) TestPendingOkay(c *gc.C) {
	res, apiResult := newResourceResult(c, "a-service", "spam")
	uuid, err := utils.NewUUID()
	c.Assert(err, jc.ErrorIsNil)
	expected := uuid.String()
	s.response.Resource = apiResult.Resources[0]
	data := "<data>"
	fp, err := charmresource.GenerateFingerprint(strings.NewReader(data))
	c.Assert(err, jc.ErrorIsNil)
	req, err := http.NewRequest("PUT", "/services/a-service/resources/spam", nil)
	c.Assert(err, jc.ErrorIsNil)
	req.Header.Set("Content-Type", "application/octet-stream")
	req.Header.Set("Content-SHA384", fp.String())
	req.Header.Set("Content-Length", fmt.Sprint(len(data)))
	req.ContentLength = int64(len(data))
	req.URL.RawQuery = "pendingid=" + expected
	reader := &stubFile{stub: s.stub}
	reader.returnRead = strings.NewReader(data)
	s.facade.pendingIDs = []string{expected}
	cl := client.NewClient(s.facade, s, s.facade)

	uploadID, err := cl.AddPendingResource("a-service", res[0].Resource, reader)
	c.Assert(err, jc.ErrorIsNil)

	s.stub.CheckCallNames(c,
		"FacadeCall",
		"Read",
		"Read",
		"Seek",
		"Do",
	)
	s.stub.CheckCall(c, 4, "Do", req, reader, s.response)
	c.Check(uploadID, gc.Equals, expected)
}
开发者ID:OSBI,项目名称:juju,代码行数:34,代码来源:client_upload_test.go

示例2: mustUUID

// mustUUID returns a stringified uuid or panics
func mustUUID() string {
	uuid, err := utils.NewUUID()
	if err != nil {
		panic(err)
	}
	return uuid.String()
}
开发者ID:kapilt,项目名称:juju,代码行数:8,代码来源:environ.go

示例3: constructInstanceConfig

func (task *provisionerTask) constructInstanceConfig(
	machine *apiprovisioner.Machine,
	auth authentication.AuthenticationProvider,
	pInfo *params.ProvisioningInfo,
) (*instancecfg.InstanceConfig, error) {

	stateInfo, apiInfo, err := auth.SetupAuthentication(machine)
	if err != nil {
		return nil, errors.Annotate(err, "failed to setup authentication")
	}

	// Generated a nonce for the new instance, with the format: "machine-#:UUID".
	// The first part is a badge, specifying the tag of the machine the provisioner
	// is running on, while the second part is a random UUID.
	uuid, err := utils.NewUUID()
	if err != nil {
		return nil, errors.Annotate(err, "failed to generate a nonce for machine "+machine.Id())
	}

	nonce := fmt.Sprintf("%s:%s", task.machineTag, uuid)
	return instancecfg.NewInstanceConfig(
		machine.Id(),
		nonce,
		task.imageStream,
		pInfo.Series,
		task.secureServerConnection,
		nil,
		stateInfo,
		apiInfo,
	)
}
开发者ID:kakamessi99,项目名称:juju,代码行数:31,代码来源:provisioner_task.go

示例4: TestNewModelSameUserSameNameFails

func (s *ModelSuite) TestNewModelSameUserSameNameFails(c *gc.C) {
	cfg, _ := s.createTestModelConfig(c)
	owner := s.Factory.MakeUser(c, nil).UserTag()

	// Create the first model.
	_, st1, err := s.State.NewModel(state.ModelArgs{
		CloudName:   "dummy",
		CloudRegion: "dummy-region",
		Config:      cfg,
		Owner:       owner,
		StorageProviderRegistry: storage.StaticProviderRegistry{},
	})
	c.Assert(err, jc.ErrorIsNil)
	defer st1.Close()

	// Attempt to create another model with a different UUID but the
	// same owner and name as the first.
	newUUID, err := utils.NewUUID()
	c.Assert(err, jc.ErrorIsNil)
	cfg2 := testing.CustomModelConfig(c, testing.Attrs{
		"name": cfg.Name(),
		"uuid": newUUID.String(),
	})
	_, _, err = s.State.NewModel(state.ModelArgs{
		CloudName:   "dummy",
		CloudRegion: "dummy-region",
		Config:      cfg2,
		Owner:       owner,
		StorageProviderRegistry: storage.StaticProviderRegistry{},
	})
	errMsg := fmt.Sprintf("model %q for %s already exists", cfg2.Name(), owner.Canonical())
	c.Assert(err, gc.ErrorMatches, errMsg)
	c.Assert(errors.IsAlreadyExists(err), jc.IsTrue)

	// Remove the first model.
	env1, err := st1.Model()
	c.Assert(err, jc.ErrorIsNil)
	err = env1.Destroy()
	c.Assert(err, jc.ErrorIsNil)
	// Destroy only sets the model to dying and RemoveAllModelDocs can
	// only be called on a dead model. Normally, the environ's lifecycle
	// would be set to dead after machines and services have been cleaned up.
	err = state.SetModelLifeDead(st1, env1.ModelTag().Id())
	c.Assert(err, jc.ErrorIsNil)
	err = st1.RemoveAllModelDocs()
	c.Assert(err, jc.ErrorIsNil)

	// We should now be able to create the other model.
	env2, st2, err := s.State.NewModel(state.ModelArgs{
		CloudName:   "dummy",
		CloudRegion: "dummy-region",
		Config:      cfg2,
		Owner:       owner,
		StorageProviderRegistry: storage.StaticProviderRegistry{},
	})
	c.Assert(err, jc.ErrorIsNil)
	defer st2.Close()
	c.Assert(env2, gc.NotNil)
	c.Assert(st2, gc.NotNil)
}
开发者ID:kat-co,项目名称:juju,代码行数:60,代码来源:model_test.go

示例5: NewLock

// NewLock returns a new lock with the given name within the given lock
// directory, without acquiring it. The lock name must match the regular
// expression defined by NameRegexp.
func NewLock(lockDir, name string, cfg LockConfig) (*Lock, error) {
	if !validName.MatchString(name) {
		return nil, fmt.Errorf("Invalid lock name %q.  Names must match %q", name, NameRegexp)
	}
	uuid, err := utils.NewUUID()
	if err != nil {
		return nil, err
	}
	lock := &Lock{
		name:                 name,
		parent:               lockDir,
		clock:                cfg.Clock,
		nonce:                uuid.String(),
		PID:                  os.Getpid(),
		stopWritingAliveFile: make(chan struct{}, 1),
		waitDelay:            cfg.WaitDelay,
		lividityTimeout:      cfg.LividityTimeout,
		readRetryTimeout:     cfg.ReadRetryTimeout,
		sanityCheck:          make(chan struct{}),
	}
	// Ensure the parent exists.
	if err := os.MkdirAll(lock.parent, 0755); err != nil {
		return nil, err
	}
	// Ensure that an old alive file doesn't exist. RemoveAll doesn't raise
	// an error if the target doesn't exist, so we don't expect any errors.
	if err := os.RemoveAll(lock.aliveFile(lock.PID)); err != nil {
		return nil, err
	}

	return lock, nil
}
开发者ID:kat-co,项目名称:utils,代码行数:35,代码来源:fslock.go

示例6: newPendingID

// newPendingID generates a new unique identifier for a resource.
func newPendingID() (string, error) {
	uuid, err := utils.NewUUID()
	if err != nil {
		return "", errors.Annotate(err, "could not create new resource ID")
	}
	return uuid.String(), nil
}
开发者ID:bac,项目名称:juju,代码行数:8,代码来源:resource.go

示例7: testHandler

func testHandler(c *gc.C, batches chan<- wireformat.MetricBatch, statusMap StatusMap, gracePeriod time.Duration) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c.Assert(r.Method, gc.Equals, "POST")
		dec := json.NewDecoder(r.Body)
		enc := json.NewEncoder(w)
		var incoming []wireformat.MetricBatch
		err := dec.Decode(&incoming)
		c.Assert(err, jc.ErrorIsNil)

		var resp = make(wireformat.EnvironmentResponses)
		for _, batch := range incoming {
			c.Logf("received metrics batch: %+v", batch)

			resp.Ack(batch.ModelUUID, batch.UUID)

			if statusMap != nil {
				unitName, status, info := statusMap(batch.UnitName)
				resp.SetStatus(batch.ModelUUID, unitName, status, info)
			}

			select {
			case batches <- batch:
			default:
			}
		}
		uuid, err := utils.NewUUID()
		c.Assert(err, jc.ErrorIsNil)
		err = enc.Encode(wireformat.Response{
			UUID:           uuid.String(),
			EnvResponses:   resp,
			NewGracePeriod: gracePeriod,
		})
		c.Assert(err, jc.ErrorIsNil)
	}
}
开发者ID:kat-co,项目名称:juju,代码行数:35,代码来源:sender_test.go

示例8: TestNewEnvironmentSameUserSameNameFails

func (s *EnvironSuite) TestNewEnvironmentSameUserSameNameFails(c *gc.C) {
	cfg, _ := s.createTestEnvConfig(c)
	owner := s.factory.MakeUser(c, nil).UserTag()

	// Create the first environment.
	_, st1, err := s.State.NewEnvironment(cfg, owner)
	c.Assert(err, jc.ErrorIsNil)
	defer st1.Close()

	// Attempt to create another environment with a different UUID but the
	// same owner and name as the first.
	newUUID, err := utils.NewUUID()
	c.Assert(err, jc.ErrorIsNil)
	cfg2 := testing.CustomEnvironConfig(c, testing.Attrs{
		"name": cfg.Name(),
		"uuid": newUUID.String(),
	})
	_, _, err = s.State.NewEnvironment(cfg2, owner)
	errMsg := fmt.Sprintf("environment %q for %s already exists", cfg2.Name(), owner.Username())
	c.Assert(err, gc.ErrorMatches, errMsg)
	c.Assert(errors.IsAlreadyExists(err), jc.IsTrue)

	// Remove the first environment.
	err = st1.RemoveAllEnvironDocs()
	c.Assert(err, jc.ErrorIsNil)

	// We should now be able to create the other environment.
	env2, st2, err := s.State.NewEnvironment(cfg2, owner)
	c.Assert(err, jc.ErrorIsNil)
	defer st2.Close()
	c.Assert(env2, gc.NotNil)
	c.Assert(st2, gc.NotNil)
}
开发者ID:Pankov404,项目名称:juju,代码行数:33,代码来源:environ_test.go

示例9: TestRunHookRelationFlushingError

func (s *FlushContextSuite) TestRunHookRelationFlushingError(c *gc.C) {
	uuid, err := utils.NewUUID()
	c.Assert(err, jc.ErrorIsNil)
	ctx := s.getHookContext(c, uuid.String(), -1, "", noProxies)

	// Mess with multiple relation settings.
	relCtx0, ok := ctx.Relation(0)
	c.Assert(ok, jc.IsTrue)
	node0, err := relCtx0.Settings()
	c.Assert(err, jc.ErrorIsNil)
	node0.Set("foo", "1")
	relCtx1, ok := ctx.Relation(1)
	c.Assert(ok, jc.IsTrue)
	node1, err := relCtx1.Settings()
	c.Assert(err, jc.ErrorIsNil)
	node1.Set("bar", "2")

	// Flush the context with a failure.
	err = ctx.FlushContext("some badge", errors.New("blam pow"))
	c.Assert(err, gc.ErrorMatches, "blam pow")

	// Check that the changes have not been written to state.
	settings0, err := s.relunits[0].ReadSettings("u/0")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(settings0, gc.DeepEquals, map[string]interface{}{"relation-name": "db0"})
	settings1, err := s.relunits[1].ReadSettings("u/0")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(settings1, gc.DeepEquals, map[string]interface{}{"relation-name": "db1"})
}
开发者ID:Pankov404,项目名称:juju,代码行数:29,代码来源:flush_test.go

示例10: charmArchiveStoragePath

// charmArchiveStoragePath returns a string that is suitable as a
// storage path, using a random UUID to avoid colliding with concurrent
// uploads.
func charmArchiveStoragePath(curl *charm.URL) (string, error) {
	uuid, err := utils.NewUUID()
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("charms/%s-%s", curl.String(), uuid), nil
}
开发者ID:Pankov404,项目名称:juju,代码行数:10,代码来源:charmstore.go

示例11: TestNewModelConfigForksControllerValue

func (s *ModelConfigSourceSuite) TestNewModelConfigForksControllerValue(c *gc.C) {
	uuid, err := utils.NewUUID()
	c.Assert(err, jc.ErrorIsNil)
	cfg := testing.CustomModelConfig(c, testing.Attrs{
		"name": "another",
		"uuid": uuid.String(),
	})
	owner := names.NewUserTag("[email protected]")
	_, st, err := s.State.NewModel(state.ModelArgs{
		Config: cfg, Owner: owner, CloudName: "dummy", CloudRegion: "nether-region",
		StorageProviderRegistry: storage.StaticProviderRegistry{},
	})
	c.Assert(err, jc.ErrorIsNil)
	defer st.Close()

	modelCfg, err := st.ModelConfig()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(modelCfg.AllAttrs()["apt-mirror"], gc.Equals, "http://mirror")

	// Change the local controller settings and ensure the model setting stays the same.
	localCloudSettings, err := s.State.ReadSettings(state.GlobalSettingsC, state.ControllerInheritedSettingsGlobalKey)
	c.Assert(err, jc.ErrorIsNil)
	localCloudSettings.Set("apt-mirror", "http://anothermirror")
	_, err = localCloudSettings.Write()
	c.Assert(err, jc.ErrorIsNil)

	modelCfg, err = st.ModelConfig()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(modelCfg.AllAttrs()["apt-mirror"], gc.Equals, "http://mirror")
}
开发者ID:bac,项目名称:juju,代码行数:30,代码来源:modelconfig_test.go

示例12: PrepareForBootstrap

func (p manualProvider) PrepareForBootstrap(ctx environs.BootstrapContext, cfg *config.Config) (environs.Environ, error) {
	if _, ok := cfg.UnknownAttrs()["storage-auth-key"]; !ok {
		uuid, err := utils.NewUUID()
		if err != nil {
			return nil, err
		}
		cfg, err = cfg.Apply(map[string]interface{}{
			"storage-auth-key": uuid.String(),
		})
		if err != nil {
			return nil, err
		}
	}
	if use, ok := cfg.UnknownAttrs()["use-sshstorage"].(bool); ok && !use {
		return nil, fmt.Errorf("use-sshstorage must not be specified")
	}
	envConfig, err := p.validate(cfg, nil)
	if err != nil {
		return nil, err
	}
	cfg, err = cfg.Apply(envConfig.attrs)
	if err != nil {
		return nil, err
	}
	envConfig = newEnvironConfig(cfg, envConfig.attrs)
	if err := ensureBootstrapUbuntuUser(ctx, envConfig); err != nil {
		return nil, err
	}
	return p.open(envConfig)
}
开发者ID:Pankov404,项目名称:juju,代码行数:30,代码来源:provider.go

示例13: newID

func newID() (string, error) {
	uuid, err := utils.NewUUID()
	if err != nil {
		return "", errors.Annotate(err, "could not create new payload ID")
	}
	return uuid.String(), nil
}
开发者ID:imoapps,项目名称:juju,代码行数:7,代码来源:unit.go

示例14: TestRunHook

func (s *RunHookSuite) TestRunHook(c *gc.C) {
	uuid, err := utils.NewUUID()
	c.Assert(err, jc.ErrorIsNil)
	for i, t := range runHookTests {
		c.Logf("\ntest %d: %s; perm %v", i, t.summary, t.spec.perm)
		ctx := s.getHookContext(c, uuid.String(), t.relid, t.remote, noProxies)
		paths := NewRealPaths(c)
		rnr := runner.NewRunner(ctx, paths)
		var hookExists bool
		if t.spec.perm != 0 {
			spec := t.spec
			spec.dir = "hooks"
			spec.name = hookName
			c.Logf("makeCharm %#v", spec)
			makeCharm(c, spec, paths.charm)
			hookExists = true
		}
		t0 := time.Now()
		err := rnr.RunHook("something-happened")
		if t.err == "" && hookExists {
			c.Assert(err, jc.ErrorIsNil)
		} else if !hookExists {
			c.Assert(runner.IsMissingHookError(err), jc.IsTrue)
		} else {
			c.Assert(err, gc.ErrorMatches, t.err)
		}
		if t.spec.background != "" && time.Now().Sub(t0) > 5*time.Second {
			c.Errorf("background process holding up hook execution")
		}
	}
}
开发者ID:mhilton,项目名称:juju,代码行数:31,代码来源:runner_test.go

示例15: MakeModel

// MakeModel creates an model with specified params,
// filling in sane defaults for missing values. If params is nil,
// defaults are used for all values.
//
// By default the new model shares the same owner as the calling
// Factory's model.
func (factory *Factory) MakeModel(c *gc.C, params *ModelParams) *state.State {
	if params == nil {
		params = new(ModelParams)
	}
	if params.Name == "" {
		params.Name = uniqueString("testenv")
	}
	if params.Owner == nil {
		origEnv, err := factory.st.Model()
		c.Assert(err, jc.ErrorIsNil)
		params.Owner = origEnv.Owner()
	}
	// It only makes sense to make an model with the same provider
	// as the initial model, or things will break elsewhere.
	currentCfg, err := factory.st.ModelConfig()
	c.Assert(err, jc.ErrorIsNil)

	uuid, err := utils.NewUUID()
	c.Assert(err, jc.ErrorIsNil)
	cfg := testing.CustomModelConfig(c, testing.Attrs{
		"name":       params.Name,
		"uuid":       uuid.String(),
		"type":       currentCfg.Type(),
		"state-port": currentCfg.StatePort(),
		"api-port":   currentCfg.APIPort(),
	}.Merge(params.ConfigAttrs))
	_, st, err := factory.st.NewModel(state.ModelArgs{
		Config: cfg,
		Owner:  params.Owner.(names.UserTag),
	})
	c.Assert(err, jc.ErrorIsNil)
	return st
}
开发者ID:makyo,项目名称:juju,代码行数:39,代码来源:factory.go


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