Пример #1
0
// Create floating-ip with 2 vmi references, delete it and verify that
// the back_refs are updated as expected.
func TestDeleteRefs(t *testing.T) {
	db := NewInMemDatabase()

	vmi1 := new(types.VirtualMachineInterface)
	vmi1.SetUuid(uuid.New())
	vmi1.SetName("port1")
	assert.NoError(t, db.Put(vmi1, nil, GetReferenceList(vmi1)))

	vmi2 := new(types.VirtualMachineInterface)
	vmi2.SetUuid(uuid.New())
	vmi2.SetName("port2")
	assert.NoError(t, db.Put(vmi2, nil, GetReferenceList(vmi2)))

	fip := new(types.FloatingIp)
	fip.SetUuid(uuid.New())
	fip.SetName("fip")
	fip.AddVirtualMachineInterface(vmi1)
	fip.AddVirtualMachineInterface(vmi2)
	assert.NoError(t, db.Put(fip, nil, GetReferenceList(fip)))

	assert.Error(t, db.Delete(vmi1))

	result, err := db.GetBackReferences(parseUID(vmi2.GetUuid()), "floating_ip")
	assert.NoError(t, err)
	assert.Len(t, result, 1)

	assert.NoError(t, db.Delete(fip))

	result, err = db.GetBackReferences(parseUID(vmi2.GetUuid()), "floating_ip")
	assert.NoError(t, err)
	assert.Len(t, result, 0)

	assert.NoError(t, db.Delete(vmi1))
	assert.NoError(t, db.Delete(vmi2))
}
func TestState_LoadCluster(t *testing.T) {
	t.Parallel()

	testPrefix := "TestState_LoadClusterState"
	testutil.ResetEtcd(t, testPrefix)
	logger := testutil.NewTestLogger(testPrefix, t)

	state, err := NewStateEtcdWithPrefix(testutil.LocalEtcdConfig, testPrefix, logger)
	if err != nil {
		t.Fatalf("Could not create state", err)
	}

	instanceID := structs.ClusterID(uuid.New())
	planID := uuid.New()
	clusterState := structs.ClusterState{
		InstanceID:       instanceID,
		OrganizationGUID: "OrganizationGUID",
		PlanID:           planID,
		ServiceID:        "ServiceID",
		SpaceGUID:        "SpaceGUID",
	}
	err = state.SaveCluster(clusterState)
	if err != nil {
		t.Fatalf("SaveCluster failed %s", err)
	}

	loadedState, err := state.LoadCluster(instanceID)
	if !reflect.DeepEqual(clusterState, loadedState) {
		t.Fatalf("Failed to load ClusterState")
	}
}
Пример #3
0
func TestUpdateOne(t *testing.T) {
	db := NewInMemDatabase()

	instance := new(types.VirtualMachine)
	instance.SetUuid(uuid.New())
	instance.SetName("instance")
	assert.NoError(t, db.Put(instance, nil, UIDList{}))

	vmi1 := new(types.VirtualMachineInterface)
	vmi1.SetUuid(uuid.New())
	vmi1.SetName("port1")
	assert.NoError(t, db.Put(vmi1, nil, GetReferenceList(vmi1)))

	vmi1.AddVirtualMachine(instance)
	assert.NoError(t, db.Update(vmi1, GetReferenceList(vmi1)))

	result, err := db.GetBackReferences(parseUID(instance.GetUuid()), "virtual_machine_interface")
	assert.NoError(t, err)
	assert.Contains(t, result, parseUID(vmi1.GetUuid()))

	vmi1.ClearVirtualMachine()
	assert.NoError(t, db.Update(vmi1, GetReferenceList(vmi1)))
	result, err = db.GetBackReferences(parseUID(instance.GetUuid()), "virtual_machine_interface")
	assert.NoError(t, err)
	assert.Len(t, result, 0)
}
Пример #4
0
func TestStoreFailsOnInvalidUserData(t *testing.T) {
	client := &osin.DefaultClient{Id: "3", Secret: "secret", RedirectUri: "http://localhost/", UserData: ""}
	authorize := &osin.AuthorizeData{
		Client:      client,
		Code:        uuid.New(),
		ExpiresIn:   int32(60),
		Scope:       "scope",
		RedirectUri: "http://localhost/",
		State:       "state",
		CreatedAt:   time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
		UserData:    struct{ foo string }{"bar"},
	}
	access := &osin.AccessData{
		Client:        client,
		AuthorizeData: authorize,
		AccessData:    nil,
		AccessToken:   uuid.New(),
		RefreshToken:  uuid.New(),
		ExpiresIn:     int32(60),
		Scope:         "scope",
		RedirectUri:   "https://localhost/",
		CreatedAt:     time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
		UserData:      struct{ foo string }{"bar"},
	}
	assert.NotNil(t, store.SaveAuthorize(authorize))
	assert.NotNil(t, store.SaveAccess(access))
}
Пример #5
0
func TestToolDoesNotExist(t *testing.T) {
	// Build the Queue with the SimpleTool timer
	q := Queue{authToken: "ResourceTest"}

	// Add the tool
	st := new(SimpleTimerTooler)
	st.SetUUID(uuid.New())
	q.tools = append(q.tools, st)

	// Create the RPC server and bind the Queue
	listen := startRPCOnce("tcp", addr, &q)
	defer listen.Close()

	// Connect to the RPC server
	client, err := rpc.Dial("tcp", addr)
	if err != nil {
		t.Fatal("Error dailing RPC server.", err)
	}
	defer client.Close()

	// Setup the Job information to start the service
	params := map[string]string{"timer": "1"}
	j := common.NewJob(uuid.New(), "Testing Job", "GoTestSuite", params)

	// Create RPC call for starting a job
	startJob := common.RPCCall{Auth: "ResourceTest", Job: j}

	// Make call and expect an error of bad job
	err = client.Call("Queue.AddTask", startJob, &j)
	if err == nil || err.Error() != ERROR_NO_TOOL {
		t.Fatal("No tool error was not returned.", err)
	}
}
Пример #6
0
func TestAcquireExistsWait(t *testing.T) {
	t.Parallel()

	key := "lock-TestAcquireExistsWait"
	id1 := uuid.New()
	id2 := uuid.New()
	ttl := uint64(2)
	c := newClient(t)
	defer cleanup(c, key)

	_, err := Acquire(c, key, id1, ttl, false)
	if err != nil {
		t.Fatal(err)
	}

	tstart := time.Now().Unix()
	_, err = Acquire(c, key, id2, ttl, true)
	if err != nil {
		t.Fatal(err)
	}
	tstop := time.Now().Unix()
	if uint64(tstop-tstart) < ttl-1 {
		t.Fatalf("expected atleast %ds(ttl-1)  wait time, got: %d\n", ttl-1, tstop-tstart)
	}

	resp, err := c.Get(key, false, false)
	if err != nil {
		t.Fatal(err)
	}
	if resp.Node.Value != id2 {
		t.Fatalf("incorrect data in lock, wanted: %s, got: %s\n", id2, resp.Node.Value)
	}
}
Пример #7
0
func TestUpdateUsername(t *testing.T) {
	id := uuid.New()
	_, _ = store.Create(account.CreateAccountRequest{
		ID:       id,
		Username: uuid.New(),
		Password: "******",
	})

	_, err := store.UpdateUsername(id, account.UpdateUsernameRequest{
		Username: uuid.New(),
		Password: "******",
	})
	assert.NotNil(t, err)

	r, err := store.UpdateUsername(id, account.UpdateUsernameRequest{
		Username: "******",
		Password: "******",
	})
	assert.Nil(t, err)
	assert.Equal(t, "3@foo", r.GetUsername())

	// Did it persist?
	r, err = store.Get(id)
	assert.Nil(t, err)
	assert.Equal(t, "3@foo", r.GetUsername())
}
Пример #8
0
func TestRefreshOperations(t *testing.T) {
	client := &osin.DefaultClient{Id: "4", Secret: "secret", RedirectUri: "http://localhost/", UserData: ""}
	type test struct {
		access *osin.AccessData
	}

	for k, c := range []*test{
		{
			access: &osin.AccessData{
				Client: client,
				AuthorizeData: &osin.AuthorizeData{
					Client:      client,
					Code:        uuid.New(),
					ExpiresIn:   int32(60),
					Scope:       "scope",
					RedirectUri: "http://localhost/",
					State:       "state",
					CreatedAt:   time.Now().Round(time.Second),
					UserData:    userDataMock,
				},
				AccessData:   nil,
				AccessToken:  uuid.New(),
				RefreshToken: uuid.New(),
				ExpiresIn:    int32(60),
				Scope:        "scope",
				RedirectUri:  "https://localhost/",
				CreatedAt:    time.Now().Round(time.Second),
				UserData:     userDataMock,
			},
		},
	} {
		createClient(t, store, client)
		require.Nil(t, store.SaveAuthorize(c.access.AuthorizeData), "Case %d", k)
		require.Nil(t, store.SaveAccess(c.access), "Case %d", k)

		result, err := store.LoadRefresh(c.access.RefreshToken)
		require.Nil(t, err)
		require.Equal(t, c.access.CreatedAt.Unix(), result.CreatedAt.Unix())
		require.Equal(t, c.access.AuthorizeData.CreatedAt.Unix(), result.AuthorizeData.CreatedAt.Unix())
		c.access.CreatedAt = result.CreatedAt
		c.access.AuthorizeData.CreatedAt = result.AuthorizeData.CreatedAt
		require.Equal(t, c.access, result, "Case %d", k)

		require.Nil(t, store.RemoveRefresh(c.access.RefreshToken))
		_, err = store.LoadRefresh(c.access.RefreshToken)

		require.NotNil(t, err, "Case %d", k)
		require.Nil(t, store.RemoveAccess(c.access.AccessToken), "Case %d", k)
		require.Nil(t, store.SaveAccess(c.access), "Case %d", k)

		_, err = store.LoadRefresh(c.access.RefreshToken)
		require.Nil(t, err, "Case %d", k)

		require.Nil(t, store.RemoveAccess(c.access.AccessToken), "Case %d", k)
		_, err = store.LoadRefresh(c.access.RefreshToken)
		require.NotNil(t, err, "Case %d", k)

	}
	removeClient(t, store, client)
}
Пример #9
0
func TestCreateAndGetCases(t *testing.T) {
	var stateDataSet = map[string]storage.StateData{
		"valid": {
			ID:          uuid.New(),
			ClientID:    uuid.New(),
			RedirectURL: "http://localhost/",
			Scope:       "scope",
			State:       "state",
			Type:        "code",
			Provider:    "facebook",
			ExpiresAt:   time.Now().Add(time.Hour),
		},
		"invalid": {},
	}

	for k, c := range []struct {
		sd         storage.StateData
		passCreate bool
		passGet    bool
	}{
		{stateDataSet["valid"], true, true},
	} {
		assert.Equal(t, c.passCreate, store.SaveStateData(&c.sd) == nil, "Case %d", k)
		if !c.passCreate {
			continue
		}

		result, err := store.GetStateData(c.sd.ID)
		assert.Nil(t, err, "Case %d", k)

		assert.Equal(t, c.sd.IsExpired(), result.IsExpired(), "Case %d", k)
		c.sd.ExpiresAt = result.ExpiresAt
		assert.Equal(t, &c.sd, result, "Case %d", k)
	}
}
func TestState_ClusterExists(t *testing.T) {
	t.Parallel()

	testPrefix := "TestState_ClusterExists"
	testutil.ResetEtcd(t, testPrefix)
	logger := testutil.NewTestLogger(testPrefix, t)

	state, err := NewStateEtcdWithPrefix(testutil.LocalEtcdConfig, testPrefix, logger)
	if err != nil {
		t.Fatalf("Could not create state", err)
	}

	clusterID := structs.ClusterID(uuid.New())
	planID := uuid.New()
	clusterState := structs.ClusterState{
		InstanceID:       clusterID,
		OrganizationGUID: "OrganizationGUID",
		PlanID:           planID,
		ServiceID:        "ServiceID",
		SpaceGUID:        "SpaceGUID",
	}
	err = state.SaveCluster(clusterState)
	if err != nil {
		t.Fatalf("SaveCluster failed %s", err)
	}

	if !state.ClusterExists(clusterID) {
		t.Fatalf("Cluster %s should exist", clusterID)
	}

	if state.ClusterExists("fakeID") {
		t.Fatalf("Cluster %s should not exist", "fakeID")
	}
}
Пример #11
0
func (s *RequestTestSuite) TestValidate() {
	rh, _ := url.ParseRequestURI("unix:///tmp")

	tests := []struct {
		description  string
		id           string
		task         string
		responseHook *url.URL
		expectedErr  bool
	}{
		{"missing ID", "", "foo", rh, true},
		{"missing Task", uuid.New(), "", rh, true},
		{"missing ResponseHook", uuid.New(), "foo", nil, true},
		{"valid", uuid.New(), "foo", rh, false},
	}

	for _, test := range tests {
		msg := testMsgFunc(test.description)
		req := &acomm.Request{
			ID:           test.id,
			Task:         test.task,
			ResponseHook: test.responseHook,
		}
		if test.expectedErr {
			s.Error(req.Validate(), msg("should not be valid"))
		} else {
			s.NoError(req.Validate(), msg("should be valid"))
		}
	}
}
Пример #12
0
func TestUpdatePassword(t *testing.T) {
	id := uuid.New()
	ac, _ := store.Create(account.CreateAccountRequest{
		ID:       id,
		Username: uuid.New(),
		Password: "******",
	})

	_, err := store.UpdatePassword(id, account.UpdatePasswordRequest{
		CurrentPassword: "******",
		NewPassword:     "******",
	})
	assert.NotNil(t, err)

	updatedAccount, err := store.UpdatePassword(id, account.UpdatePasswordRequest{
		CurrentPassword: "******",
		NewPassword:     "******",
	})
	assert.Nil(t, err)

	resultAccount, err := store.Get(id)
	assert.Nil(t, err)

	assert.Equal(t, updatedAccount.GetPassword(), resultAccount.GetPassword())
	assert.NotEqual(t, ac.GetPassword(), resultAccount.GetPassword())
}
Пример #13
0
func TestTLSGen(t *testing.T) {
	priv := filepath.Join(tmpDir, uuid.New())
	pub := filepath.Join(tmpDir, uuid.New())
	os.Args = []string{"hydra-host", "tls", "generate-dummy-certificate", "-c", priv, "-k", pub, "-u", "localhost", "--sd", "Jan 1 15:04:05 2011", "-d", "8760h0m0s", "--ca", "--rb", "4069", "--ec", "P521"}
	assert.Nil(t, NewApp().Run(os.Args))
	assertAndRemoveFile(t, priv)
	assertAndRemoveFile(t, pub)
}
Пример #14
0
func TestJWTGen(t *testing.T) {
	priv := filepath.Join(tmpDir, uuid.New())
	pub := filepath.Join(tmpDir, uuid.New())
	os.Args = []string{"hydra-host", "jwt", "generate-keypair", "-s", priv, "-p", pub}
	assert.Nil(t, NewApp().Run(os.Args))
	assertAndRemoveFile(t, priv)
	assertAndRemoveFile(t, pub)
}
Пример #15
0
func (h *Handler) TokenHandler(w http.ResponseWriter, r *http.Request) {
	resp := h.server.NewResponse()
	r.ParseForm()
	defer resp.Close()
	if ar := h.server.HandleAccessRequest(resp, r); ar != nil {
		switch ar.Type {
		case osin.AUTHORIZATION_CODE:
			data, ok := ar.UserData.(string)
			if !ok {
				http.Error(w, fmt.Sprintf("Could not assert UserData to string: %v", ar.UserData), http.StatusInternalServerError)
				return
			}

			var claims jwt.ClaimsCarrier
			if err := json.Unmarshal([]byte(data), &claims); err != nil {
				http.Error(w, fmt.Sprintf("Could not unmarshal UserData: %v", ar.UserData), http.StatusInternalServerError)
				return
			}

			ar.UserData = jwt.NewClaimsCarrier(uuid.New(), claims.GetSubject(), h.Issuer, h.Audience, time.Now(), time.Now())
			ar.Authorized = true
		case osin.REFRESH_TOKEN:
			data, ok := ar.UserData.(map[string]interface{})
			if !ok {
				http.Error(w, fmt.Sprintf("Could not assert UserData type: %v", ar.UserData), http.StatusInternalServerError)
				return
			}
			claims := jwt.ClaimsCarrier(data)
			ar.UserData = jwt.NewClaimsCarrier(uuid.New(), claims.GetSubject(), h.Issuer, h.Audience, time.Now(), time.Now())
			ar.Authorized = true
		case osin.PASSWORD:
			// TODO if !ar.Client.isAllowedToAuthenticateUser
			// TODO ... return
			// TODO }

			if user, err := h.authenticate(w, r, ar.Username, ar.Password); err == nil {
				ar.UserData = jwt.NewClaimsCarrier(uuid.New(), user.GetID(), h.Issuer, h.Audience, time.Now(), time.Now())
				ar.Authorized = true
			}
		case osin.CLIENT_CREDENTIALS:
			ar.UserData = jwt.NewClaimsCarrier(uuid.New(), ar.Client.GetId(), h.Issuer, h.Audience, time.Now(), time.Now())
			ar.Authorized = true

			// TODO ASSERTION workflow http://leastprivilege.com/2013/12/23/advanced-oauth2-assertion-flow-why/
			// TODO Since assertions are only a draft for now and there is no need for SAML or similar this is postponed.
			//case osin.ASSERTION:
			//	if ar.AssertionType == "urn:hydra" && ar.Assertion == "osin.data" {
			//		ar.Authorized = true
			//	}
		}

		h.server.FinishAccessRequest(resp, r, ar)
	}
	if resp.IsError {
		resp.StatusCode = http.StatusUnauthorized
	}
	osin.OutputJSON(resp, w, r)
}
Пример #16
0
func SessionGet(app *forest.App, manager SessionManager) func(ctx *bear.Context) {
	return func(ctx *bear.Context) {
		cookieName := forest.SessionID
		createEmptySession := func(sessionID string) {
			path := app.Config.CookiePath
			if path == "" {
				path = "/"
			}
			cookieValue := sessionID
			duration := app.Duration("Cookie")
			// Reset the cookie.
			app.SetCookie(ctx, path, cookieName, cookieValue, duration)
			manager.CreateEmpty(sessionID, ctx)
			ctx.Next()
		}
		cookie, err := ctx.Request.Cookie(cookieName)
		if err != nil || cookie.Value == "" {
			createEmptySession(uuid.New())
			return
		}
		sessionID := cookie.Value
		userID, userJSON, err := manager.Read(sessionID)
		if err != nil || userID == "" || userJSON == "" {
			createEmptySession(uuid.New())
			return
		}
		if err := manager.Create(sessionID, userID, userJSON, ctx); err != nil {
			println(fmt.Sprintf("error creating session: %s", err))
			defer func(sessionID string, userID string) {
				if err := manager.Delete(sessionID, userID); err != nil {
					println(fmt.Sprintf("error deleting session: %s", err))
				}
			}(sessionID, userID)
			createEmptySession(uuid.New())
			return
		}
		// If SessionRefresh is set to false, the session will not refresh;
		// if it's not set or if it's set to true, the session is refreshed.
		refresh, ok := ctx.Get(forest.SessionRefresh).(bool)
		if !ok || refresh {
			path := app.Config.CookiePath
			if path == "" {
				path = "/"
			}
			cookieName := forest.SessionID
			cookieValue := sessionID
			duration := app.Duration("Cookie")
			// Refresh the cookie.
			app.SetCookie(ctx, path, cookieName, cookieValue, duration)
			err := manager.Update(sessionID, userID,
				userJSON, app.Duration("Session"))
			if err != nil {
				println(fmt.Sprintf("error updating session: %s", err))
			}
		}
		ctx.Next()
	}
}
Пример #17
0
func TestAccessOperations(t *testing.T) {
	client := &osin.DefaultClient{Id: "3", Secret: "secret", RedirectUri: "http://localhost/", UserData: ""}
	authorize := &osin.AuthorizeData{
		Client:      client,
		Code:        uuid.New(),
		ExpiresIn:   int32(60),
		Scope:       "scope",
		RedirectUri: "http://localhost/",
		State:       "state",
		// FIXME this should be time.Now(), but an upstream ( https://github.com/lib/pq/issues/329 ) issue prevents this.
		CreatedAt: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
		UserData:  userDataMock,
	}
	nestedAccess := &osin.AccessData{
		Client:        client,
		AuthorizeData: authorize,
		AccessData:    nil,
		AccessToken:   uuid.New(),
		RefreshToken:  uuid.New(),
		ExpiresIn:     int32(60),
		Scope:         "scope",
		RedirectUri:   "https://localhost/",
		// FIXME this should be time.Now(), but an upstream ( https://github.com/lib/pq/issues/329 ) issue prevents this.
		CreatedAt: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
		UserData:  userDataMock,
	}
	access := &osin.AccessData{
		Client:        client,
		AuthorizeData: authorize,
		AccessData:    nestedAccess,
		AccessToken:   uuid.New(),
		RefreshToken:  uuid.New(),
		ExpiresIn:     int32(60),
		Scope:         "scope",
		RedirectUri:   "https://localhost/",
		// FIXME this should be time.Now(), but an upstream ( https://github.com/lib/pq/issues/329 ) issue prevents this.
		CreatedAt: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
		UserData:  userDataMock,
	}

	createClient(t, store, client)
	require.Nil(t, store.SaveAuthorize(authorize))
	require.Nil(t, store.SaveAccess(nestedAccess))
	require.Nil(t, store.SaveAccess(access))

	result, err := store.LoadAccess(access.AccessToken)
	require.Nil(t, err)
	require.True(t, reflect.DeepEqual(access, result))

	require.Nil(t, store.RemoveAccess(access.AccessToken))
	_, err = store.LoadAccess(access.AccessToken)
	require.NotNil(t, err)
	require.Nil(t, store.RemoveAuthorize(authorize.Code))

	removeClient(t, store, client)
}
Пример #18
0
// TestExec tests the exec.go source file
func TestExec(t *testing.T) {
	_, err := Exec(uuid.New(), "touch", uuid.New())
	assert.Error(t, err, "Exec should not be able to run in a not existing directory")

	o, err := Exec("/tmp", "echo", "test")
	assert.Nil(t, err, "Could not exec echo")
	assert.Equal(t, "test\n", string(o), "Could not exec echo")

	_, err = Exec("/tmp", uuid.New())
	assert.Error(t, err, "An invalid command should return an error")
}
Пример #19
0
func TestDelete(t *testing.T) {
	id := uuid.New()
	_, _ = store.Create(account.CreateAccountRequest{
		ID:       id,
		Username: uuid.New(),
		Password: "******",
	})

	_, err := store.Get(id)
	assert.Nil(t, err)
	assert.Nil(t, store.Delete(id))
	_, err = store.Get(id)
	assert.NotNil(t, err)
}
Пример #20
0
func newWorker(rChan <-chan job) *worker {
	return &worker{
		rcv:      rChan,
		id:       uuid.New(),
		kamikaze: make(chan struct{}),
	}
}
Пример #21
0
func (s *ServerSuite) SetupSuite() {
	log.SetLevel(log.FatalLevel)

	socketDir, err := ioutil.TempDir("", "providerTest-")
	s.Require().NoError(err, "failed to create socket dir")

	s.configData = &provider.ConfigData{
		SocketDir:       socketDir,
		ServiceName:     uuid.New(),
		CoordinatorURL:  "http://localhost:8080/",
		DefaultPriority: 43,
		LogLevel:        "fatal",
		DefaultTimeout:  100,
		RequestTimeout:  10,
		Tasks: map[string]*provider.TaskConfigData{
			"foobar": {
				Priority: 56,
				Timeout:  64,
			},
		},
	}

	s.config, _, _, _, err = newConfig(true, false, s.configData)
	s.Require().NoError(err, "failed to create config")
	s.Require().NoError(s.config.LoadConfig(), "failed to load config")
}
Пример #22
0
func (shop *Shop) NewOrder(username string, item string, qty uint64) (string, error) {
	order_time := time.Now()
	timestamp := strconv.FormatUint(uint64(order_time.Unix()), 10)
	if err := shop.noteFreshOrder(username, item, qty); err != nil {
		return "", err
	}
	order := shop.MakeOrder(uuid.New())
	order.User = username
	order.Item = item
	order.Quantity = qty
	order.Timestamp = timestamp
	order.Status = shopApi.OrderStatusProcessing
	order.Time = order_time.String()

	// TODO would be good to try to release the fresh_order lock if the transaction fails
	err := shop.redis.Transaction(func(redis services.Redis) error {
		err := redis.Cmd("sadd", user_orders_key+username, order.id).Err()
		if err != nil {
			return err
		}
		err = redis.Cmd("sadd", open_orders_key, order.id).Err()
		if err != nil {
			return err
		}
		return order.SaveIn(redis)
	})
	if err == nil {
		return order.id, nil
	} else {
		return "", err
	}
}
Пример #23
0
func getHostname() string {
	hostname, err := os.Hostname()
	if err != nil {
		return uuid.New()
	}
	return hostname
}
Пример #24
0
// Snapshot create new subvolume from volume
func (d *driver) Snapshot(volumeID api.VolumeID, readonly bool, locator api.VolumeLocator) (api.VolumeID, error) {
	vols, err := d.Inspect([]api.VolumeID{volumeID})
	if err != nil {
		return api.BadVolumeID, err
	}
	if len(vols) != 1 {
		return api.BadVolumeID, fmt.Errorf("Failed to inspect %v len %v", volumeID, len(vols))
	}
	snapID := uuid.New()
	vols[0].ID = api.VolumeID(snapID)
	vols[0].Parent = volumeID
	vols[0].Locator = locator
	vols[0].Ctime = time.Now()

	err = d.CreateVol(&vols[0])
	if err != nil {
		return api.BadVolumeID, err
	}
	chaos.Now(koStrayCreate)
	err = d.btrfs.Create(snapID, string(volumeID))
	if err != nil {
		return api.BadVolumeID, err
	}
	return vols[0].ID, nil
}
Пример #25
0
func main() {
	g := cloudwatch.NewGroup("test", cloudwatchlogs.New(defaults.DefaultConfig))

	stream := uuid.New()

	w, err := g.Create(stream)
	if err != nil {
		log.Fatal(err)
	}

	r, err := g.Open(stream)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		var i int
		for {
			i++
			<-time.After(time.Second / 30)
			_, err := fmt.Fprintf(w, "Line %d\n", i)
			if err != nil {
				log.Println(err)
			}
		}
	}()

	io.Copy(os.Stdout, r)
}
Пример #26
0
func addUser(p *WsPlayer, w http.ResponseWriter) string {
	id := uuid.New()
	uids[id] = p
	p._uid = id

	return id
}
Пример #27
0
func TestRefresh(t *testing.T) {
	t.Parallel()

	key := "lock-TestRefresh"
	id := uuid.New()
	ttl := uint64(2)
	c := newClient(t)
	defer cleanup(c, key)

	l, err := Acquire(c, key, id, ttl, false)
	if err != nil {
		t.Fatal(err)
	}

	if err := l.Refresh(); err != nil {
		t.Fatal(err)
	}
	time.Sleep(time.Duration(ttl) * time.Second)
	if err := l.Refresh(); err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Duration(ttl+1) * time.Second)
	if err := l.Refresh(); err != ErrKeyNotFound {
		t.Fatalf("wanted: %v, got: %v\n", ErrKeyNotFound, err)
	}

	if err := l.Refresh(); err != ErrLockNotHeld {
		t.Fatalf("wanted: %v, got: %v\n", ErrLockNotHeld, err)
	}
}
Пример #28
0
//NewTask creates a Task
func newTask(s schedule.Schedule, wf *schedulerWorkflow, m *workManager, mm managesMetrics, emitter gomit.Emitter, opts ...core.TaskOption) *task {

	//Task would always be given a default name.
	//However if a user want to change this name, she can pass optional arguments, in form of core.TaskOption
	//The new name then get over written.

	taskID := uuid.New()
	name := fmt.Sprintf("Task-%s", taskID)
	wf.eventEmitter = emitter
	task := &task{
		id:               taskID,
		name:             name,
		schResponseChan:  make(chan schedule.Response),
		schedule:         s,
		state:            core.TaskStopped,
		creationTime:     time.Now(),
		workflow:         wf,
		manager:          m,
		metricsManager:   mm,
		deadlineDuration: DefaultDeadlineDuration,
		stopOnFailure:    DefaultStopOnFailure,
		eventEmitter:     emitter,
	}
	//set options
	for _, opt := range opts {
		opt(task)
	}
	return task
}
Пример #29
0
// NewRequest creates a new Request instance.
func NewRequest(task, responseHook string, args interface{}, sh ResponseHandler, eh ResponseHandler) (*Request, error) {
	hook, err := url.ParseRequestURI(responseHook)
	if err != nil {
		log.WithFields(log.Fields{
			"error":        err,
			"responseHook": responseHook,
		}).Error("invalid response hook url")
		return nil, err
	}

	if task == "" {
		return nil, errors.New("missing task")
	}

	argsJSON, err := json.Marshal(args)
	if err != nil {
		return nil, err
	}

	return &Request{
		ID:             uuid.New(),
		Task:           task,
		ResponseHook:   hook,
		Args:           (*json.RawMessage)(&argsJSON),
		SuccessHandler: sh,
		ErrorHandler:   eh,
	}, nil
}
Пример #30
-1
func tryCrypto() {
	pwd := "pwd"
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	if err != nil {
		P("bcrypt err: ", err)
	}

	P("first, pwd and hansh: \n", pwd, string(hash), len(string(hash)))
	hash2, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	P("second, pwd and hash: \n", pwd, string(hash2), len(string(hash2)))

	P("check pwd..")
	P("check hash1: ")
	err = bcrypt.CompareHashAndPassword(hash, []byte(pwd))
	P(err == nil)
	err = bcrypt.CompareHashAndPassword(hash, []byte("pwds"))
	P(err == nil)
	P("check has2:")
	P("hash1 != hash2: ", string(hash) != string(hash2))
	err = bcrypt.CompareHashAndPassword(hash2, []byte(pwd))
	P(err == nil)
	u := uuid.New()
	P("uuid: ", u, len(u), len(uuid.New()), len(uuid.New()))
	unix := time.Now().Unix()
	unixStr := fmt.Sprintf("%d", unix)
	P("time: ", unix, len(unixStr))

}