func send(cache []Event) {
	fmt.Println("sending %s", len(cache))
	for index, element := range cache {
		_ = index
		//fmt.Println(element.id, element.event, element.value)
		//fmt.Println(index)
		key, _ := as.NewKey("test", "totals", "total_votes")
		ops := []*as.Operation{
			as.AddOp(as.NewBin("total_votes", 1)), // add the value of the bin to the existing value
			as.GetOp(),                            // get the value of the record after all operations are executed
		}

		_, _ = client.Operate(nil, key, ops...)

		key, _ = as.NewKey("test", "totals", element.value)
		ops = []*as.Operation{
			as.AddOp(as.NewBin(element.value, 1)), // add the value of the bin to the existing value
			as.GetOp(),                            // get the value of the record after all operations are executed
		}

		_, _ = client.Operate(nil, key, ops...)
		//panicOnError(err)
		//fmt.Println(rec)

		//		client.Set(element.id, element.value)
		//		client.Get(element.id)
		//		client.Incr("total_votes")
		//		client.Incr(element.value)
	}
}
示例#2
0
// When the auction has completed, perform the following logic.
func CloseAuction(offerId int, bid *m.Bid) {
	auctionMap.Remove(offerId)

	// Check if the broker has enough inventory
	offerKeyId := fmt.Sprintf("%s:%d", OFFERS, offerId)
	offerKey, _ := as.NewKey(NAMESPACE, OFFERS, offerKeyId)
	offerRec, _ := db.Get(readPolicy, offerKey)
	sellerId := offerRec.Bins["broker_id"].(int)

	// add to buyer's inventory and reduce credit
	buyerKeyId := fmt.Sprintf("%s:%d", BROKERS, bid.BrokerId)
	buyerKey, _ := as.NewKey(NAMESPACE, BROKERS, buyerKeyId)
	db.Operate(writePolicy, buyerKey,
		as.AddOp(as.NewBin(offerRec.Bins["ticker"].(string), offerRec.Bins["quantity"].(int))),
		as.AddOp(as.NewBin("credit", -1*offerRec.Bins["quantity"].(int)*int(bid.Price))),
	)

	// reduce seller's inventory and add to credit
	sellerKeyId := fmt.Sprintf("%s:%d", BROKERS, sellerId)
	sellerKey, _ := as.NewKey(NAMESPACE, BROKERS, sellerKeyId)
	db.Operate(writePolicy, sellerKey,
		as.AddOp(as.NewBin(offerRec.Bins["ticker"].(string), -1*offerRec.Bins["quantity"].(int))),
		as.AddOp(as.NewBin("credit", offerRec.Bins["quantity"].(int)*int(bid.Price))),
	)

	// mark the bid as winner
	bidKeyId := fmt.Sprintf("%s:%d", BIDS, bid.Id)
	bidKey, _ := as.NewKey(NAMESPACE, BIDS, bidKeyId)
	db.Put(writePolicy, bidKey, as.BinMap{"winner": 1})
	db.Put(writePolicy, offerKey, as.BinMap{"finished": 1, "winner": bid.Id})
}
示例#3
0
// Place a Bid on an offer for sale
func (command *Command) Bid(r *http.Request, bid *m.Bid, bidId *int) error {

	var err error

	offerKeyId := fmt.Sprintf("%s:%d", OFFERS, bid.OfferId)
	offerKey, err := as.NewKey(NAMESPACE, OFFERS, offerKeyId)
	if err != nil {
		return err
	}

	offerRec, err := db.Get(readPolicy, offerKey)
	if err != nil {
		return err
	}

	bidChan := auctionMap.Get(bid.OfferId)
	if err != nil || offerRec == nil || bidChan == nil {
		return errors.New("Auction has finished.")
	}

	// bid.Id = int(atomic.AddInt64(&bidIdSeq, 1))
	bid.Id, err = nextSeq("bid")
	if err != nil {
		return nil
	}

	bidKeyId := fmt.Sprintf("%s:%d", BIDS, bid.Id)
	bidKey, err := as.NewKey(NAMESPACE, BIDS, bidKeyId)
	if err != nil {
		return err
	}

	bidBins := as.BinMap{
		"bid_id":     bid.Id,
		"auction_id": bid.OfferId,
		"broker_id":  bid.BrokerId,
		"price":      bid.Price,
	}

	if err := db.Put(writePolicy, bidKey, bidBins); err != nil {
		return err
	}

	*bidId = bid.Id

	// bids < asking price will not be considered in the auction
	// however, we also prevent the bidder from submitting a new
	// bid (ie 1 bid per bidder rule)
	if offerRec.Bins["price"].(int) < bid.Price {
		bidChan <- bid

		broadcast <- &m.Notification{
			Version: "2.0",
			Method:  "Bid",
			Params:  *bid,
		}
	}

	return nil
}
func voteHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	w.Header().Set("Content-Type", "text/plain")

	e := Event{id: r.FormValue("u"), event: "vote", value: r.FormValue("v")}

	//fmt.Println(i)
	i = i + 1
	e.id = strconv.Itoa(i)
	key, err := as.NewKey("test", "votes", e.id)
	bins := as.BinMap{
		"v": e.value,
	}
	err = client.Put(writePolicy, key, bins)
	panicOnError(err)
	_ = err
	if err == nil {
		ch <- e
		//	fmt.Println(i)

		w.Write([]byte(fmt.Sprintf("Vote")))
	} else {
		w.Write([]byte(fmt.Sprintf("Duplicate")))
	}
}
示例#5
0
func statsBoss() {
	statsMap := map[string][]uint64{}
	for {
		select {
		case s := <-stats:
			if lst, exists := statsMap[s.ticker]; !exists {
				statsMap[s.ticker] = []uint64{s.price}
			} else {
				statsMap[s.ticker] = append(lst, s.price)
			}

		case <-time.After(1 * time.Second):
			for ticker, stats := range statsMap {
				if len(stats) == 0 {
					continue
				}

				sum := 0
				for _, p := range stats {
					sum += int(p)
				}

				key, _ := as.NewKey(NAMESPACE, STOCKS, ticker)
				go db.Put(nil, key, as.BinMap{"price": sum / len(stats)})
			}
			// reset the stats
			statsMap = map[string][]uint64{}
		}
	}
}
示例#6
0
// Get retrieves a value by key.
func (db DB) Get(key string) (interface{}, error) {
	k, err := as.NewKey(db.namespace, db.set, key)
	if err != nil {
		return 0, err
	}
	return db.client.Get(db.p, k)
}
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	// defer client.Close()
	client, err = as.NewClient("172.31.53.227", 3000)
	fmt.Println(client)
	panicOnError(err)

	writePolicy = as.NewWritePolicy(0, 0)
	ch = make(chan Event, 1)
	key, err := as.NewKey("test", "totals", "test")
	panicOnError(err)
	// define some bins with data
	bins := as.BinMap{
		"value": 100,
	}
	err = client.Put(nil, key, bins)
	panicOnError(err)

	time.AfterFunc(1*time.Second, func() {
		for i := 1; i < 24; i++ {
			fmt.Println("starting worker %d", i)
			go worker(ch)
		}
	})

	http.HandleFunc("/vote", voteHandler)
	http.HandleFunc("/loaderio-35df9c4fffde902e3b0e3e0115816d82.html", validationHandler)
	http.ListenAndServe(":80", nil)
}
示例#8
0
/**
 * Read records in one batch.
 */
func batchReads(
	client *as.Client,
	keyPrefix string,
	binName string,
	size int,
) {
	// Batch gets into one call.
	keys := make([]*as.Key, size)
	for i := 0; i < size; i++ {
		keys[i], _ = as.NewKey(*shared.Namespace, *shared.Set, keyPrefix+strconv.Itoa(i+1))
	}

	records, err := client.BatchGet(nil, keys, binName)
	shared.PanicOnError(err)

	for i := 0; i < len(records); i++ {
		key := keys[i]
		record := records[i]
		level := asl.ERR
		var value interface{}

		if record != nil {
			level = asl.INFO
			value = record.Bins[binName]
		}
		asl.Logger.LogAtLevel(level, "Record: ns=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), binName, value)
	}

	if len(records) != size {
		log.Fatalf("Record size mismatch. Expected %d. Received %d.", size, len(records))
	}
}
示例#9
0
func runExample(client *as.Client) {
	// Write initial record.
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "opkey")
	bin1 := as.NewBin("optintbin", 7)
	bin2 := as.NewBin("optstringbin", "string value")
	log.Printf("Put: namespace=%s set=%s key=%s bin1=%s value1=%s bin2=%s value2=%s",
		key.Namespace(), key.SetName(), key.Value(), bin1.Name, bin1.Value, bin2.Name, bin2.Value)
	client.PutBins(shared.WritePolicy, key, bin1, bin2)

	// Add integer, write new string and read record.
	bin3 := as.NewBin(bin1.Name, 4)
	bin4 := as.NewBin(bin2.Name, "new string")
	log.Println("Add: ", bin3.Value)
	log.Println("Write: ", bin4.Value)
	log.Println("Read:")

	record, err := client.Operate(shared.WritePolicy, key, as.AddOp(bin3), as.PutOp(bin4), as.GetOp())
	shared.PanicOnError(err)

	if record == nil {
		log.Fatalf(
			"Failed to get: namespace=%s set=%s key=%s",
			key.Namespace(), key.SetName(), key.Value())
	}

	binExpected := as.NewBin(bin3.Name, 11)
	shared.ValidateBin(key, binExpected, record)
	shared.ValidateBin(key, bin4, record)
}
func runExample(client *as.Client) {
	// Set LuaPath
	luaPath, _ := os.Getwd()
	luaPath += "/udf/"
	as.SetLuaPath(luaPath)

	filename := "sum_single_bin"
	regTask, err := client.RegisterUDFFromFile(nil, luaPath+filename+".lua", filename+".lua", as.LUA)
	shared.PanicOnError(err)

	// wait until UDF is created
	shared.PanicOnError(<-regTask.OnComplete())

	sum := 0
	for i := 1; i <= keyCount; i++ {
		sum += i
		key, err := as.NewKey(*shared.Namespace, *shared.Set, i)
		shared.PanicOnError(err)

		bin1 := as.NewBin("bin1", i)
		client.PutBins(nil, key, bin1)
	}

	t := time.Now()
	stm := as.NewStatement(*shared.Namespace, *shared.Set)
	res, err := client.QueryAggregate(nil, stm, filename, filename, "bin1")
	shared.PanicOnError(err)

	for rec := range res.Results() {
		log.Printf("Result %f should equal %d\n", rec.Record.Bins["SUCCESS"], sum)
	}
	log.Println("Map/Reduce took", time.Now().Sub(t))
}
示例#11
0
/**
 * Read record header data in one batch.
 */
func batchReadHeaders(
	client *as.Client,
	keyPrefix string,
	size int,
) {
	// Batch gets into one call.
	keys := make([]*as.Key, size)
	for i := 0; i < size; i++ {
		keys[i], _ = as.NewKey(*shared.Namespace, *shared.Set, keyPrefix+strconv.Itoa(i+1))
	}

	records, err := client.BatchGetHeader(nil, keys)
	shared.PanicOnError(err)

	for i := 0; i < len(records); i++ {
		key := keys[i]
		record := records[i]
		level := asl.ERR
		generation := 0
		expiration := 0

		if record != nil && (record.Generation > 0 || record.Expiration > 0) {
			level = asl.INFO
			generation = record.Generation
			expiration = record.Expiration
		}
		asl.Logger.LogAtLevel(level, "Record: ns=%s set=%s key=%s generation=%d expiration=%d",
			key.Namespace(), key.SetName(), key.Value(), generation, expiration)
	}

	if len(records) != size {
		log.Fatalf("Record size mismatch. Expected %d. Received %d.", size, len(records))
	}
}
示例#12
0
func envKey(env string) (key *aerospike.Key, err error) {
	err = envNameOk(env)
	if err != nil {
		return nil, err
	}
	return aerospike.NewKey(leverOSNamespace, envSet, env)
}
示例#13
0
// Increment a bin, being used as a sequence generator.
func nextSeq(seq string) (int, error) {

	keyId := fmt.Sprintf("%s:%s", SEQUENCES, seq)
	key, err := as.NewKey(NAMESPACE, SEQUENCES, keyId)
	if err != nil {
		return 0, err
	}

	rec, err := db.Operate(
		writePolicy,
		key,
		as.AddOp(as.NewBin("seq", 1)),
		as.GetOpForBin("seq"),
	)

	if err != nil {
		return 0, err
	}

	if seq, exists := rec.Bins["seq"]; !exists || int(seq.(int)) <= 0 {
		return 0, fmt.Errorf("sequence not found: %s", seq)
	}

	return rec.Bins["seq"].(int), nil
}
示例#14
0
// Add a new Broker
func (command *Command) AddBroker(r *http.Request, broker *m.Broker, done *bool) error {

	*done = false

	keyId := fmt.Sprintf("%s:%d", BROKERS, broker.Id)
	key, _ := as.NewKey(NAMESPACE, BROKERS, keyId)

	db.Delete(nil, key)

	bins := as.BinMap{
		"broker_id":   broker.Id,
		"broker_name": broker.Name,
		"credit":      broker.Credit,
	}

	policy := &as.WritePolicy{
		BasePolicy:         *as.NewPolicy(),
		RecordExistsAction: as.CREATE_ONLY,
		GenerationPolicy:   as.NONE,
		Generation:         0,
		Expiration:         0,
		SendKey:            false,
	}

	if err := db.Put(policy, key, bins); err != nil {
		return err
	}

	*done = true
	return nil
}
示例#15
0
// Set stores a value by key.
// TODO(nslaughter): change name. Put is a better name because a Set is a thing.
func (db DB) Set(key string, value string) (interface{}, error) {
	k, err := as.NewKey(db.namespace, db.set, key)
	if err != nil {
		return 0, err
	}
	bin := as.NewBin("", value)
	db.client.PutBins(db.wp, k, bin)
	return 1, nil
}
示例#16
0
func seed_db() {
	println("Sedding db...")

	var key *as.Key

	println("Sedding stocks...")

	// put stocks
	key, _ = as.NewKey(NAMESPACE, STOCKS, "GOOG")
	db.Put(nil, key, as.BinMap{
		"ticker":   "GOOG",
		"quantity": int64(1e9),
		"price":    int(5200),
	})

	key, _ = as.NewKey(NAMESPACE, STOCKS, "APPL")
	db.Put(nil, key, as.BinMap{
		"ticker":   "APPL",
		"quantity": int64(1e9),
		"price":    8200,
	})

	key, _ = as.NewKey(NAMESPACE, STOCKS, "FB")
	db.Put(nil, key, as.BinMap{
		"ticker":   "FB",
		"quantity": int64(1e9),
		"price":    5200,
	})

	key, _ = as.NewKey(NAMESPACE, STOCKS, "MSFT")
	db.Put(nil, key, as.BinMap{
		"ticker":   "MSFT",
		"quantity": int64(1e9),
		"price":    2100,
	})

	key, _ = as.NewKey(NAMESPACE, STOCKS, "GE")
	db.Put(nil, key, as.BinMap{
		"ticker":   "GE",
		"quantity": int64(1e9),
		"price":    1100,
	})

}
示例#17
0
/**
 * Write/Read Array/Map combination directly instead of relying on java serializer.
 */
func testListMapCombined(client *as.Client) {
	log.Printf("Read/Write Array/Map")
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "listmapkey")
	client.Delete(shared.WritePolicy, key)

	blob := []byte{3, 52, 125}
	inner := []interface{}{
		"string2",
		5,
	}

	innerMap := map[interface{}]interface{}{
		"a":    1,
		2:      "b",
		3:      blob,
		"list": inner,
	}

	list := []interface{}{
		"string1",
		8,
		inner,
		innerMap,
	}

	bin := as.NewBin("listmapbin", list)
	client.PutBins(shared.WritePolicy, key, bin)

	record, err := client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)
	received := record.Bins[bin.Name].([]interface{})

	validateSize(4, len(received))
	validate("string1", received[0])
	// Server convert numbers to long, so must expect long.
	validate(8, received[1])

	receivedInner := received[2].([]interface{})
	validateSize(2, len(receivedInner))
	validate("string2", receivedInner[0])
	validate(5, receivedInner[1])

	receivedMap := received[3].(map[interface{}]interface{})
	validateSize(4, len(receivedMap))
	validate(1, receivedMap["a"])
	validate("b", receivedMap[2])
	validateBytes(blob, receivedMap[3].([]byte))

	receivedInner2 := receivedMap["list"].([]interface{})
	validateSize(2, len(receivedInner2))
	validate("string2", receivedInner2[0])
	validate(5, receivedInner2[1])

	log.Printf("Read/Write Array/Map successful")
}
示例#18
0
func runExample(client *as.Client) {
	key, err := as.NewKey(*shared.Namespace, *shared.Set, "addkey")
	shared.PanicOnError(err)

	binName := "addbin"

	// Delete record if it already exists.
	client.Delete(shared.WritePolicy, key)

	// Perform some adds and check results.
	bin := as.NewBin(binName, 10)
	log.Println("Initial add will create record.  Initial value is ", bin.Value, ".")
	client.AddBins(shared.WritePolicy, key, bin)

	bin = as.NewBin(binName, 5)
	log.Println("Add ", bin.Value, " to existing record.")
	client.AddBins(shared.WritePolicy, key, bin)

	record, err := client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)

	if record == nil {
		log.Fatalf(
			"Failed to get: namespace=%s set=%s key=%s",
			key.Namespace(), key.SetName(), key.Value())
	}

	// The value received from the server is an unsigned byte stream.
	// Convert to an integer before comparing with expected.
	received := record.Bins[bin.Name]
	expected := 15

	if received == expected {
		log.Printf("Add successful: ns=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, received)
	} else {
		log.Fatalf("Add mismatch: Expected %d. Received %d.", expected, received)
	}

	// Demonstrate add and get combined.
	bin = as.NewBin(binName, 30)
	log.Println("Add ", bin.Value, " to existing record.")
	record, err = client.Operate(shared.WritePolicy, key, as.AddOp(bin), as.GetOp())
	shared.PanicOnError(err)

	expected = 45
	received = record.Bins[bin.Name]

	if received == expected {
		log.Printf("Add successful: ns=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, received)
	} else {
		log.Fatalf("Add mismatch: Expected %d. Received %d.", expected, received)
	}
}
示例#19
0
文件: dmctrl.go 项目: clude/trygo
func loadASRecord(ns string, set string, pkey string) *as.Record {
	var err error
	key, err := as.NewKey(ns, set, pkey)
	panicOnError(err)

	policy := as.NewPolicy()
	rec, err := client.Get(policy, key)
	panicOnError(err)

	return rec
}
示例#20
0
func serviceKey(env string, service string) (key *aerospike.Key, err error) {
	err = envNameOk(env)
	if err != nil {
		return nil, err
	}
	err = serviceNameOk(service)
	if err != nil {
		return nil, err
	}

	keyName := env + "/" + service
	return aerospike.NewKey(leverOSNamespace, serviceSet, keyName)
}
示例#21
0
func main() {
	// flags
	host := flag.String("h", "127.0.0.1", "host")
	port := flag.Int("p", 3000, "port")
	del := flag.Bool("del", false, "delete?")
	flag.Parse()

	// connect to Aerospike
	if h, found := os.LookupEnv("AEROSPIKE_PORT_3000_TCP_ADDR"); found {
		*host = h
	}
	cl, err := asc.NewClient(*host, *port)
	panicOnErr(err)

	key, err := asc.NewKey("test", "aerospike", "key")
	panicOnErr(err)

	// define some bins with data
	bins := asc.BinMap{
		"bin1": 42,
		"bin2": "elephant",
		"bin3": []interface{}{"Go", 2009},
	}

	// write the bins
	wp := asc.NewWritePolicy(0, 0)
	wp.SendKey = true // also send the key itself
	err = cl.Put(wp, key, bins)
	panicOnErr(err)

	rec, err := cl.Get(nil, key)
	panicOnErr(err)

	_, _ = pp.Printf("key: %v\nbins: %v\n", *rec.Key, rec.Bins)

	// scan all data
	rs, err := cl.ScanAll(nil, "test", "aerospike")
	panicOnErr(err)
	defer rs.Close()

	for r := range rs.Results() {
		_, _ = pp.Println(*r.Record.Key, r.Record.Bins)
	}

	if *del {
		existed, err := cl.Delete(nil, key)
		panicOnErr(err)
		fmt.Printf("Record existed before delete? %v\n", existed)
	}
}
示例#22
0
func runExample(client *as.Client) {
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "touchkey")
	bin := as.NewBin("touchbin", "touchvalue")

	log.Printf("Create record with 2 second expiration.")
	writePolicy := as.NewWritePolicy(0, 2)
	client.PutBins(writePolicy, key, bin)

	log.Printf("Touch same record with 5 second expiration.")
	writePolicy.Expiration = 5
	record, err := client.Operate(writePolicy, key, as.TouchOp(), as.GetHeaderOp())

	if record == nil {
		log.Fatalf(
			"Failed to get: namespace=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, nil)
	}

	if record.Expiration == 0 {
		log.Fatalf(
			"Failed to get record expiration: namespace=%s set=%s key=%s",
			key.Namespace(), key.SetName(), key.Value())
	}

	log.Printf("Sleep 3 seconds.")
	time.Sleep(3 * time.Second)

	record, err = client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)

	if record == nil {
		log.Fatalf(
			"Failed to get: namespace=%s set=%s key=%s",
			key.Namespace(), key.SetName(), key.Value())
	}

	log.Printf("Success. Record still exists.")
	log.Printf("Sleep 4 seconds.")
	time.Sleep(4 * time.Second)

	record, err = client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)

	if record == nil {
		log.Printf("Success. Record expired as expected.")
	} else {
		log.Fatalf("Found record when it should have expired.")
	}
}
示例#23
0
func writeIfGenerationNotChanged(client *as.Client) {
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "udfkey2")
	bin := as.NewBin("udfbin2", "string value")

	// Seed record.
	client.PutBins(shared.WritePolicy, key, bin)

	// Get record generation.
	gen, err := client.Execute(shared.WritePolicy, key, "record_example", "getGeneration")
	shared.PanicOnError(err)

	// Write record if generation has not changed.
	client.Execute(shared.WritePolicy, key, "record_example", "writeIfGenerationNotChanged", as.NewValue(bin.Name), bin.Value, as.NewValue(gen))
	log.Printf("Record written.")
}
示例#24
0
/**
 * Write and twice read a non-expiring tuple using the new "NoExpire" value (-1).
 * This example is most effective when the Default Namespace Time To Live (TTL)
 * is set to a small value, such as 5 seconds.  When we sleep beyond that
 * time, we show that the NoExpire TTL flag actually works.
 */
func noExpireExample(client *as.Client) {
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "expirekey")
	bin := as.NewBin("expirebin", "noexpirevalue")

	log.Printf("Put: namespace=%s set=%s key=%s bin=%s value=%s expiration=NoExpire",
		key.Namespace(), key.SetName(), key.Value(), bin.Name, bin.Value)

	// Specify that record NEVER expires.
	// The "Never Expire" value is -1, or 0xFFFFFFFF.
	writePolicy := as.NewWritePolicy(0, 2)
	writePolicy.Expiration = math.MaxUint32
	client.PutBins(writePolicy, key, bin)

	// Read the record, showing it is there.
	log.Printf("Get: namespace=%s set=%s key=%s",
		key.Namespace(), key.SetName(), key.Value())

	record, err := client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)
	if record == nil {
		log.Fatalf(
			"Failed to get record: namespace=%s set=%s key=%s",
			key.Namespace(), key.SetName(), key.Value())
	}

	received := record.Bins[bin.Name]
	expected := bin.Value.String()
	if received == expected {
		log.Printf("Get record successful: namespace=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, received)
	} else {
		log.Fatalf("Expire record mismatch: Expected %s. Received %s.",
			expected, received)
	}

	// Read this Record after the Default Expiration, showing it is still there.
	// We should have set the Namespace TTL at 5 sec.
	log.Printf("Sleeping for 10 seconds ...")
	time.Sleep(10 * time.Second)
	record, err = client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)

	if record == nil {
		log.Fatalf("Record expired and should NOT have.")
	} else {
		log.Printf("Found Record (correctly) after default TTL.")
	}
}
示例#25
0
/**
 * Write records individually.
 */
func writeRecords(
	client *as.Client,
	keyPrefix string,
	binName string,
	valuePrefix string,
	size int,
) {
	for i := 1; i <= size; i++ {
		key, _ := as.NewKey(*shared.Namespace, *shared.Set, keyPrefix+strconv.Itoa(i))
		bin := as.NewBin(binName, valuePrefix+strconv.Itoa(i))

		log.Printf("Put: ns=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, bin.Value)

		client.PutBins(shared.WritePolicy, key, bin)
	}
}
示例#26
0
func writeUsingUdf(client *as.Client) {
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "udfkey1")
	bin := as.NewBin("udfbin1", "string value")

	client.Execute(shared.WritePolicy, key, "record_example", "writeBin", as.NewValue(bin.Name), bin.Value)

	record, err := client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)
	expected := bin.Value.String()
	received := record.Bins[bin.Name].(string)

	if received == expected {
		log.Printf("Data matched: namespace=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, received)
	} else {
		log.Printf("Data mismatch: Expected %s. Received %s.", expected, received)
	}
}
func create(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	name := req.FormValue("username")
	p := req.FormValue("password")
	if len(name) < 3 || len(p) < 3 {
		http.Redirect(res, req, "/create?msg=Requires longer attributes", http.StatusSeeOther)
		return
	}
	id, err := uuid.NewV4()
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Printf("error generating uuid: %s\n", err.Error())
		return
	}
	hashPass, err := bcrypt.GenerateFromPassword([]byte(p), bcrypt.DefaultCost)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Printf("error hashing password: %s\n", err.Error())
		return
	}
	u := user{
		Username: name,
		Password: string(hashPass),
		ID:       id.String(),
	}

	key, err := as.NewKey("bar", "users", id.String())
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Printf("error creating key: %s\n", err.Error())
		return
	}
	err = client.PutObject(nil, key, &u)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Printf("error saving object: %s\n", err.Error())
		return
	}

	http.SetCookie(res, &http.Cookie{
		Name:  "login",
		Value: id.String(),
	})
	http.Redirect(res, req, "/", http.StatusSeeOther)
}
示例#28
0
/**
 * Write and twice read an expiration record.
 */
func expireExample(client *as.Client) {
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "expirekey ")
	bin := as.NewBin("expirebin", "expirevalue")

	log.Printf("Put: namespace=%s set=%s key=%s bin=%s value=%s expiration=2",
		key.Namespace(), key.SetName(), key.Value(), bin.Name, bin.Value)

	// Specify that record expires 2 seconds after it's written.
	writePolicy := as.NewWritePolicy(0, 2)
	client.PutBins(writePolicy, key, bin)

	// Read the record before it expires, showing it is there.
	log.Printf("Get: namespace=%s set=%s key=%s",
		key.Namespace(), key.SetName(), key.Value())

	record, err := client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)
	if record == nil {
		log.Fatalf(
			"Failed to get record: namespace=%s set=%s key=%s",
			key.Namespace(), key.SetName(), key.Value())
	}

	received := record.Bins[bin.Name]
	expected := bin.Value.String()
	if received == expected {
		log.Printf("Get record successful: namespace=%s set=%s key=%s bin=%s value=%s",
			key.Namespace(), key.SetName(), key.Value(), bin.Name, received)
	} else {
		log.Fatalf("Expire record mismatch: Expected %s. Received %s.",
			expected, received)
	}

	// Read the record after it expires, showing it's gone.
	log.Printf("Sleeping for 3 seconds ...")
	time.Sleep(3 * time.Second)
	record, err = client.Get(shared.Policy, key, bin.Name)
	shared.PanicOnError(err)
	if record == nil {
		log.Printf("Expiry of record successful. Record not found.")
	} else {
		log.Fatalf("Found record when it should have expired.")
	}
}
示例#29
0
// Read record header data.
func runGetHeaderExample(client *as.Client) {
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "putgetkey")

	log.Printf("Get record header: namespace=%s set=%s key=%s", key.Namespace(), key.SetName(), key.Value())
	record, err := client.GetHeader(shared.Policy, key)
	shared.PanicOnError(err)

	if record == nil {
		panic(errors.New(fmt.Sprintf(
			"Failed to get: namespace=%s set=%s key=%s", key.Namespace(), key.SetName(), key.Value())))
	}

	// Generation should be greater than zero.  Make sure it's populated.
	if record.Generation == 0 {
		panic(errors.New(fmt.Sprintf(
			"Invalid record header: generation=%d expiration=%d", record.Generation, record.Expiration)))
	}
	log.Printf("Received: generation=%d expiration=%d (%s)\n", record.Generation, record.Expiration, time.Duration(record.Expiration)*time.Second)
}
示例#30
0
func writeWithValidation(client *as.Client) {
	key, _ := as.NewKey(*shared.Namespace, *shared.Set, "udfkey4")
	binName := "udfbin4"

	// Lua function writeWithValidation accepts number between 1 and 10.
	// Write record with valid value.
	log.Printf("Write with valid value.")
	client.Execute(shared.WritePolicy, key, "record_example", "writeWithValidation", as.NewValue(binName), as.NewValue(4))

	// Write record with invalid value.
	log.Printf("Write with invalid value.")

	_, err := client.Execute(shared.WritePolicy, key, "record_example", "writeWithValidation", as.NewValue(binName), as.NewValue(11))
	if err == nil {
		log.Printf("UDF should not have succeeded!")
	} else {
		log.Printf("Success. UDF resulted in exception as expected.")
	}
}