Beispiel #1
1
func (s *Server) setupIDs() error {
	clusterIDPath := filepath.Join(s.dataDir, clusterIDFilename)
	clusterID, err := s.readID(clusterIDPath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if clusterID == "" {
		clusterID = uuid.NewV4().String()
		s.writeID(clusterIDPath, clusterID)
	}
	s.ClusterID = clusterID

	serverIDPath := filepath.Join(s.dataDir, serverIDFilename)
	serverID, err := s.readID(serverIDPath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if serverID == "" {
		serverID = uuid.NewV4().String()
		s.writeID(serverIDPath, serverID)
	}
	s.ServerID = serverID

	return nil
}
func Example() {
	saver := new(savers.FileSystemSaver)
	saver.Report = true
	saver.Duration = time.Second * 3

	// Run before any v1 or v2 UUIDs to ensure the saver takes
	uuid.RegisterSaver(saver)

	u1 := uuid.NewV1()
	fmt.Printf("version %d variant %x: %s\n", u1.Version(), u1.Variant(), u1)

	uP, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	u3 := uuid.NewV3(uP, uuid.Name("test"))

	u4 := uuid.NewV4()
	fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)

	u5 := uuid.NewV5(uuid.NamespaceURL, uuid.Name("test"))

	if uuid.Equal(u1, u3) {
		fmt.Printf("Will never happen")
	}

	fmt.Print(uuid.Sprintf(uuid.CurlyHyphen, u5))

	uuid.SwitchFormat(uuid.BracketHyphen)
}
func (s *EnvelopeRepositorySuite) Test_AllEnvelopes() {
	e1 := gledger.Envelope{
		UUID:    uuid.NewV4().String(),
		Name:    "Test Envelope 1",
		Type:    "income",
		Balance: 10,
	}
	e2 := gledger.Envelope{
		UUID: uuid.NewV4().String(),
		Name: "Test Envelope 2",
		Type: "expense",
	}
	s.mustExec(`INSERT INTO envelopes VALUES (
		$1, $2, '2016-08-30T00:00:00Z', now(), $3
	)`, e1.UUID, e1.Name, e1.Type)
	s.mustExec(`INSERT INTO envelopes VALUES (
		$1, $2, '2016-08-30T00:00:01Z', now(), $3
	)`, e2.UUID, e2.Name, e2.Type)
	s.mustExec(`INSERT INTO transactions VALUES ($1, $2, now(), 'payee', 10, 'f', 'f', now(), now(), $3)`, uuid.NewV4(), "cadd0722-6fd1-47ff-b390-b53307cc8c01", e1.UUID)

	es, err := AllEnvelopes(s.tx.Query)()
	if s.NoError(err) {
		s.Equal([]gledger.Envelope{e1, e2}, es)
	}
}
Beispiel #4
0
func InsertPost(title []byte, slug string, markdown []byte, html []byte, featured bool, isPage bool, published bool, image []byte, created_at time.Time, created_by int64) (int64, error) {

	status := "draft"
	if published {
		status = "published"
	}
	writeDB, err := readDB.Begin()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	var result sql.Result
	if published {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, created_at, created_by)
	} else {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, nil, nil)
	}
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	postId, err := result.LastInsertId()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	return postId, writeDB.Commit()
}
Beispiel #5
0
// TestProcessCancelCommandMessage tests that processCancelCommandMessage calls all the expected APIs
// on receiving a cancel message.
func TestProcessCancelCommandMessage(t *testing.T) {
	testCase := TestCaseCancelCommand{
		MsgToCancelID: uuid.NewV4().String(),
		MsgID:         uuid.NewV4().String(),
		InstanceID:    "i-400e1090",
	}

	testProcessCancelCommandMessage(t, testCase)
}
Beispiel #6
0
// For now, it doesn't actually test much to be honest
func TestTrak(t *testing.T) {
	log.Printf("### TRAK.TRANSACTION")

	tr := &Transaction{
		ID:        uuid.NewV4().String(),
		Timestamp: time.Now(),
		Author:    uuid.NewV4().String(),
		Action:    "buy food and eat",
		Payload: []Payload{
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "transactions",
				Action: "insert",
				Values: map[string]interface{}{
					"timestamp": time.Now(),
					"item":      uuid.NewV4().String(),
					"buyer":     uuid.NewV4().String(),
				},
			},
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "accounts",
				Action: "update",
				Values: map[string]interface{}{
					"money": 23712,
				},
			},
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "accounts",
				Action: "update",
				Values: map[string]interface{}{
					"money": 82139,
				},
			},
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "players",
				Action: "update",
				Values: map[string]interface{}{
					"hunger":    0,
					"last_meal": time.Now(),
				},
			},
			Payload{
				ID:     uuid.NewV4().String(),
				Table:  "items",
				Action: "delete",
			},
		},
	}

	trJ, _ := tr.JSON()
	log.Printf("Transaction JSON: %s", trJ)

	trS, _, _ := tr.SQL()
	log.Printf("Transaction SQL: %s", trS)
}
Beispiel #7
0
func generateKey() (string, string, error) {
	key := uuid.NewV4().String()
	secretKey := uuid.NewV4().String()
	_, err := Conn.Do("SADD", "api-keys", key)
	if err != nil {
		return "", "", err
	}
	_, err = Conn.Do("HSET", "key:"+key, "secret", secretKey)
	if err != nil {
		return "", "", err
	}
	_, err = Conn.Do("SADD", "key:"+key+":permissions", GetPermission, UploadPermission)
	return key, secretKey, err
}
Beispiel #8
0
func Initialize() error {
	// If journey.db does not exist, look for a Ghost database to convert
	if !helpers.FileExists(filenames.DatabaseFilename) {
		// Convert Ghost database if available (time format needs to change to be compatible with journey)
		migration.Ghost()
	}
	// Open or create database file
	var err error
	readDB, err = sql.Open("sqlite3", filenames.DatabaseFilename)
	if err != nil {
		return err
	}
	readDB.SetMaxIdleConns(256) // TODO: is this enough?
	err = readDB.Ping()
	if err != nil {
		return err
	}
	currentTime := time.Now()
	_, err = readDB.Exec(stmtInitialization, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime)
	// TODO: Is Commit()/Rollback() needed for DB.Exec()?
	if err != nil {
		return err
	}
	err = checkBlogSettings()
	if err != nil {
		return err
	}
	return nil
}
Beispiel #9
0
func saveImage(image string) (string, error) {
	if image == "" {
		return "", nil
	}

	var number = uuid.NewV4()
	var newImage = "download/" + uuid.Formatter(number, uuid.CurlyHyphen)
	out, error := os.Create(newImage)
	if error != nil {
		return "", error
	}
	defer out.Close()

	response, error := http.Get(image)
	if error != nil {
		return "", error
	}
	defer response.Body.Close()

	pix, error := ioutil.ReadAll(response.Body)
	if error != nil {
		return "", error
	}

	_, error = io.Copy(out, bytes.NewReader(pix))
	if error != nil {
		return "", error
	}

	return newImage, nil
}
Beispiel #10
0
// NewStatistics creates an expvar-based map. Within there "name" is the Measurement name, "tags" are the tags,
// and values are placed at the key "values".
// The "values" map is returned so that statistics can be set.
func NewStatistics(name string, tags map[string]string) (string, *kexpvar.Map) {
	key := uuid.NewV4().String()

	m := &kexpvar.Map{}
	m.Init()

	// Set the name
	nameVar := &kexpvar.String{}
	nameVar.Set(name)
	m.Set("name", nameVar)

	// Set the tags
	tagsVar := &kexpvar.Map{}
	tagsVar.Init()
	for k, v := range tags {
		value := &kexpvar.String{}
		value.Set(v)
		tagsVar.Set(k, value)
	}
	m.Set("tags", tagsVar)

	// Create and set the values entry used for actual stats.
	statMap := &kexpvar.Map{}
	statMap.Init()
	m.Set("values", statMap)

	// Set new statsMap on the top level map.
	stats.Set(key, m)

	return key, statMap
}
Beispiel #11
0
func ParseMessage(recipients []string, sender string, data []byte) (msg Msg, err error) {

	msg.Sender, err = ParseAddress(sender)
	if err != nil {
		return msg, err
	}
	for _, rcpt := range recipients {
		rcptAddr, err := ParseAddress(rcpt)
		if err != nil {
			return msg, err
		}
		msg.Rcpt = append(msg.Rcpt, rcptAddr)
	}
	message, err := mail.ReadMessage(bytes.NewReader(data))
	if err != nil {
		return msg, err
	}
	msg.Message = *message

	msg.MessageId = msg.Message.Header.Get("message-id")
	if msg.MessageId == "" {
		id := uuid.NewV4()
		uuid.SwitchFormat(uuid.Clean)
		msg.MessageId = id.String()
	}

	msg.RcptDomains = make(map[string]int)
	for _, d := range msg.Rcpt {
		msg.RcptDomains[d.Domain] = msg.RcptDomains[d.Domain] + 1
	}
	return msg, nil
}
Beispiel #12
0
func BenchmarkNewV4(b *testing.B) {
	for i := 0; i < b.N; i++ {
		uuid.NewV4()
	}
	b.StopTimer()
	b.ReportAllocs()
}
Beispiel #13
0
func (as accountService) Create(a Account) (Account, error) {
	if a.UUID == "" {
		a.UUID = uuid.NewV4().String()
	}

	return a, as.saveAccount(a)
}
Beispiel #14
0
func (ts transactionService) Create(t Transaction) (Transaction, error) {
	if t.UUID == "" {
		t.UUID = uuid.NewV4().String()
	}

	return t, ts.saveTransaction(t)
}
// Handles upload requests.
func handleUpload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	// parse HTML template
	t, err := template.New("presign").Parse(htmlDocument)
	if err != nil {
		c.Errorf("Error parsing template: %s", err.Error())
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	// a unique key to upload
	id := uuid.NewV4().String()

	// AWS S3 credentials
	creds := &s3.Credentials{
		Region:          regionName,
		Bucket:          bucketName,
		AccessKeyID:     accessKeyID,
		SecretAccessKey: secretAccessKey,
	}

	// create pre-signed POST details
	opts := &s3.PolicyOptions{5, 1024000}
	post, err := s3.NewPresignedPOST(id, creds, opts)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	// render HTML form
	t.Execute(w, post)
}
Beispiel #16
0
func doServerBeat(kapi client.KeysAPI) {
	var key = runningbase + *serverbeatname

	myuuid := uuid.NewV4()
	uuidstring := myuuid.String()

	fmt.Println("Badum")
	_, err := kapi.Set(context.TODO(), key, uuidstring, &client.SetOptions{PrevExist: client.PrevNoExist, TTL: time.Second * 60})
	if err != nil {
		log.Fatal(err)
	}

	running := true
	counter := *serverbeatcount

	for running {
		time.Sleep(time.Second * time.Duration(*serverbeattime))
		fmt.Println("Badum")
		_, err := kapi.Set(context.TODO(), key, uuidstring, &client.SetOptions{PrevExist: client.PrevExist, TTL: time.Second * 60, PrevValue: uuidstring})
		if err != nil {
			log.Fatal(err)
		}
		if *serverbeatcount != 0 {
			counter = counter - 1
			if counter == 0 {
				running = false
			}
		}
	}

	_, err = kapi.Delete(context.TODO(), key, &client.DeleteOptions{PrevValue: uuidstring})
	if err != nil {
		log.Fatal(err)
	}
}
Beispiel #17
0
// NewStatistics creates an expvar-based map. Within there "name" is the Measurement name, "tags" are the tags,
// and values are placed at the key "values".
// The "values" map is returned so that statistics can be set.
func NewStatistics(name string, tags map[string]string) *expvar.Map {
	expvarMu.Lock()
	defer expvarMu.Unlock()

	key := uuid.NewV4().String()

	m := &expvar.Map{}
	m.Init()
	expvar.Publish(key, m)

	// Set the name
	nameVar := &expvar.String{}
	nameVar.Set(name)
	m.Set("name", nameVar)

	// Set the tags
	tagsVar := &expvar.Map{}
	tagsVar.Init()
	for k, v := range tags {
		value := &expvar.String{}
		value.Set(v)
		tagsVar.Set(k, value)
	}
	m.Set("tags", tagsVar)

	// Create and set the values entry used for actual stats.
	statMap := &expvar.Map{}
	statMap.Init()
	m.Set("values", statMap)

	return statMap
}
Beispiel #18
0
func NewNode(controllerUrl string, dockerUrl string, tlsConfig *tls.Config, cpus float64, memory float64, heartbeatInterval int, ip string, showOnlyGridContainers bool, enableDebug bool) (*Node, error) {
	if enableDebug {
		log.SetLevel(log.DebugLevel)
	}

	u := uuid.NewV4()
	id := uuid.Formatter(u, uuid.CleanHyphen)

	client, err := dockerclient.NewDockerClient(dockerUrl, tlsConfig)
	if err != nil {
		return nil, err
	}

	node := &Node{
		Id:                     id,
		client:                 client,
		controllerUrl:          controllerUrl,
		heartbeatInterval:      heartbeatInterval,
		showOnlyGridContainers: showOnlyGridContainers,
		ip:     ip,
		Cpus:   cpus,
		Memory: memory,
	}
	return node, nil
}
Beispiel #19
0
func NewEntry() *Entry {
	id := uuid.NewV4()

	return &Entry{
		uuid: strings.ToUpper(uuid.Formatter(id, uuid.Clean)), // e.g. FF755C6D7D9B4A5FBC4E41C07D622C65
	}
}
Beispiel #20
0
/*
NewTask creates a new task with the assigned parents. The new task is in an
incomplete state, with no subtasks of it's own. Passing in nil or an empty
array as the argument for parent means it has no parent(s) and so it
is a root task.
*/
func NewTask(name string, parents []*Task) *Task {
	if parents == nil {
		parents = make([]*Task, 0)
	}

	now := time.Now().Unix()

	newTask := &Task{
		ID:           uuid.NewV4().String(),
		Name:         name,
		Complete:     false,
		CreatedDate:  now,
		ModifiedDate: now,
		DueDate:      0,
		Categories:   make([]string, 0),
		Parents:      parents,
		Subtasks:     make([]*Task, 0),
	}

	for _, parent := range parents {
		parent.AddSubtask(newTask)
	}

	return newTask
}
Beispiel #21
0
func speak(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	r.ParseForm()
	sentence := r.PostFormValue("sentence")
	if strings.TrimSpace(sentence) == "" {
		log.Println("no sentence provided, request aborted")
		http.Redirect(w, r, "/failed", http.StatusSeeOther)
		return
	}

	attclient.SetAuthTokens()
	apiRequest := attclient.NewAPIRequest(attspeech.TTSResource)
	apiRequest.ContentType = "text/plain"
	apiRequest.Accept = "audio/x-wav"
	apiRequest.VoiceName = "mike"
	apiRequest.Text = sentence

	data, err := attclient.TextToSpeech(apiRequest)
	if err != nil {
		log.Println(err)
		http.Redirect(w, r, "/failed", http.StatusSeeOther)
		return
	}

	filename := wavfilesdir + uuid.NewV4().String() + ".wav"
	err = ioutil.WriteFile(filename, data, 0644)
	if err != nil {
		log.Println(err)
		http.Redirect(w, r, "/failed", http.StatusSeeOther)
		return
	}
	defer os.Remove(filename)

	play(filename)
	http.Redirect(w, r, "/", http.StatusSeeOther)
}
Beispiel #22
0
func (es envelopeService) Create(e Envelope) (Envelope, error) {
	if e.UUID == "" {
		e.UUID = uuid.NewV4().String()
	}

	return e, es.save(e)
}
Beispiel #23
0
//NewSync initialize new etcd sync
func NewSync(etcdServers []string) *Sync {
	sync := &Sync{locks: cmap.New()}
	sync.etcdClient = etcd.NewClient(etcdServers)
	hostname, _ := os.Hostname()
	sync.processID = hostname + uuid.NewV4().String()
	return sync
}
Beispiel #24
0
// Open opens or creates a storage with specific format for a local engine Driver.
func (d Driver) Open(schema string) (kv.Storage, error) {
	mc.mu.Lock()
	defer mc.mu.Unlock()

	if store, ok := mc.cache[schema]; ok {
		// TODO: check the cache store has the same engine with this Driver.
		log.Info("cache store", schema)
		return store, nil
	}

	db, err := d.Driver.Open(schema)
	if err != nil {
		return nil, errors.Trace(err)
	}

	log.Info("New store", schema)
	s := &dbStore{
		txns:       make(map[uint64]*dbTxn),
		keysLocked: make(map[string]uint64),
		uuid:       uuid.NewV4().String(),
		path:       schema,
		db:         db,
		compactor:  newLocalCompactor(localCompactDefaultPolicy, db),
	}
	mc.cache[schema] = s
	s.compactor.Start()
	return s, nil
}
Beispiel #25
0
func (w *rpcWorker) getTSFromRemote(conn *bufio.ReadWriter, n int) (pdpb.Timestamp, error) {
	var timestampHigh = pdpb.Timestamp{}
	req := &pdpb.Request{
		Header: &pdpb.RequestHeader{
			Uuid:      uuid.NewV4().Bytes(),
			ClusterId: w.clusterID,
		},
		CmdType: pdpb.CommandType_Tso,
		Tso: &pdpb.TsoRequest{
			Count: uint32(n),
		},
	}
	resp, err := w.callRPC(conn, req)
	if err != nil {
		return timestampHigh, errors.Trace(err)
	}
	if resp.GetTso() == nil {
		return timestampHigh, errors.New("[pd] tso filed in rpc response not set")
	}
	timestampHigh = resp.GetTso().GetTimestamp()
	if resp.GetTso().GetCount() != uint32(n) {
		return timestampHigh, errors.New("[pd] tso length in rpc response is incorrect")
	}
	return timestampHigh, nil
}
Beispiel #26
0
func newToken() *Token {
	u := uuid.NewV4().String()
	now := time.Now()
	token := &Token{
		AccessToken: u,
		ExpireAt:    now.Add(TokenExpiration),
	}
	return token
}
Beispiel #27
0
// getMessagesOutput wraps an MDS message into a GetMessagesOutput struct.
func getMessagesOutput(m *ssmmds.Message) ssmmds.GetMessagesOutput {
	uuid.SwitchFormat(uuid.CleanHyphen)
	requestID := uuid.NewV4().String()
	return ssmmds.GetMessagesOutput{
		Destination:       m.Destination,
		Messages:          []*ssmmds.Message{m},
		MessagesRequestId: aws.String(requestID),
	}
}
Beispiel #28
0
func (s *AccountRepositorySuite) Test_AllAccounts_WithTransactions() {
	u := uuid.NewV4().String()
	eu := uuid.NewV4().String()
	s.mustExec(`INSERT INTO accounts VALUES ($1, 'name', 'type', 't', now(), now())`, u)
	s.mustExec(`INSERT INTO envelopes VALUES ($1, 'envelope name', now(), now(), 'expense')`, eu)
	s.mustExec(`INSERT INTO transactions VALUES ($1, $2, now(), 'payee', 10, 'f', 'f', now(), now(), $3)`, uuid.NewV4(), u, eu)
	s.mustExec(`INSERT INTO transactions VALUES ($1, $2, now(), 'payee', -5, 'f', 'f', now(), now(), $3)`, uuid.NewV4(), u, eu)

	as, err := AllAccounts(s.tx.Query)()
	s.NoError(err)
	s.Equal([]gledger.Account{gledger.Account{
		UUID:    u,
		Name:    "name",
		Type:    "type",
		Active:  true,
		Balance: 5,
	}}, as)
}
Beispiel #29
0
func TestFileSystemSaver_Save(t *testing.T) {

	saver := SetupFileSystemStateSaver(path.Join("github.com.twinj.uuid.generator-"+uuid.NewV4().String()+".gob"), true)

	// Read is always called first
	saver.Read()

	store := &uuid.Store{Timestamp: 1, Sequence: 2, Node: []byte{0xff, 0xaa, 0x33, 0x44, 0x55, 0x66}}
	saver.Save(store)

	saver = SetupFileSystemStateSaver(path.Join("/generator-"+uuid.NewV4().String()+".gob"), false)

	// Read is always called first
	saver.Read()

	store = &uuid.Store{Timestamp: 1, Sequence: 2, Node: []byte{0xff, 0xaa, 0x33, 0x44, 0x55, 0x66}}
	saver.Save(store)
}
Beispiel #30
0
func buildConceptSuggestionsHeader(publishEventHeaders map[string]string) map[string]string {
	return map[string]string{
		"Message-Id":        uuid.NewV4().String(),
		"Message-Type":      "concept-suggestions",
		"Content-Type":      publishEventHeaders["Content-Type"],
		"X-Request-Id":      publishEventHeaders["X-Request-Id"],
		"Origin-System-Id":  publishEventHeaders["Origin-System-Id"],
		"Message-Timestamp": time.Now().Format(messageTimestampDateFormat),
	}
}