Beispiel #1
0
func TestKeyBitcountAddAndRemove(t *testing.T) {
	const loopsz = 1000
	bset := Make()
	for i := 0; i < loopsz; i++ {
		bset.Add(i)
		checkbitcount(bset, "add(sequence)", t)
	}
	for i := 0; i < loopsz; i++ {
		bset.Add(rand.Int63())
		checkbitcount(bset, "add(random(spread))", t)
	}
	for i := 0; i < loopsz; i++ {
		bset.Add(rand.Int63n(loopsz * 2))
		checkbitcount(bset, "add(random(focussed))", t)
	}
	for i := 0; i < loopsz; i++ {
		bset.Remove(rand.Int63())
		checkbitcount(bset, "remove(random(spread))", t)
	}
	for i := 0; i < loopsz; i++ {
		bset.Remove(rand.Int63n(loopsz * 2))
		checkbitcount(bset, "remove(random(focussed))", t)
	}
	for i := 0; i < loopsz; i++ {
		bset.Remove(i)
		checkbitcount(bset, "remove(sequence)", t)
	}
}
func (p *FileResource) CreatePath(req Request, cxt Context) (string, Request, Context, int, os.Error) {
	frc := cxt.(FileResourceContext)
	if frc.IsDir() {
		newPath := filepath.Join(frc.FullPath(), string(rand.Int63()))
		frc2 := NewFileResourceContextWithPath(newPath)
		for frc2.Exists() {
			newPath = filepath.Join(frc.FullPath(), string(rand.Int63()))
			frc2 = NewFileResourceContextWithPath(newPath)
		}
		frc = frc2
	} else if frc.Exists() {
		p := frc.FullPath()
		dir, tail := path.Split(p)
		ext := path.Ext(tail)
		basename := tail
		uniquify := time.UTC().Format(".20060102.150405")
		if len(ext) > 0 {
			basename = tail[:len(tail)-len(ext)] + uniquify
			frc.SetFullPath(path.Join(dir, basename+ext))
			for counter := 1; frc.Exists(); counter++ {
				frc.SetFullPath(path.Join(dir, basename+"."+strconv.Itoa(counter)+ext))
			}
		} else {
			basename = basename + uniquify
			frc.SetFullPath(path.Join(dir, basename))
			for counter := 1; frc.Exists(); counter++ {
				frc.SetFullPath(path.Join(dir, basename+"."+strconv.Itoa(counter)))
			}
		}
	}
	log.Print("[FileResource]: Will use path ", frc.FullPath())
	return frc.FullPath(), req, frc, 0, nil
}
Beispiel #3
0
func TestKeyMappingInt64(t *testing.T) {
	for i := 0; i < 10000; i++ {
		num := rand.Int63()
		if i%5 != 0 {
			num = -num
		}
		key, mask := sbitlocation(num)
		if bitcount(mask) != 1 {
			t.Errorf("Expected exactly one bit in mask; found %v", bitcount(mask))
		}
		dcnum := imemberval(key, getbits(mask)[0])
		switch tp := dcnum.(type) {
		case int64:
			if num >= 0 {
				t.Errorf("Expected type \"uint64\": got %v", reflect.Typeof(tp))
			}
			if num != tp {
				t.Errorf("Expected type %v: got %v (%v,%v)", num, tp, key, mask)
			}
		case uint64:
			if num < 0 {
				t.Errorf("Expected type \"int64\": got %v", reflect.Typeof(tp))
			}
			if uint64(num) != tp {
				t.Errorf("Expected type %v: got %v", num, tp)
			}
		default:
			t.Errorf("Expected type \"(u)int64\": got %v", reflect.Typeof(tp))
		}
	}
}
Beispiel #4
0
func (c *AuthClient) MakeRequest(url string, additional_params map[string]string, token_secret string, protected bool) (r *http.Response, finalURL string, err os.Error) {

	log.Stderrf("make_request:url:%s:", url);
	for k,v := range additional_params {
		log.Stderrf("make_request:%s:%s:", k, v);
	}

	params := make(map[string]string);
	params["oauth_consumer_key"] = c.consumer_key;
	params["oauth_signature_method"] = "HMAC-SHA1";
	params["oauth_timestamp"] =  strconv.Itoa64(time.Seconds());
	params["oauth_nonce"] = strconv.Itoa64(rand.Int63());
	params["oauth_version"] = "1.0";

	//if token != "" {
	//	params["oauth_token"] = token;
	//}
	//else {
	//	params["oauth_callback"] = c.callback_url;
	//}

	// typically: oauth_token, oauth_callback, and/or oauth_verifier
	for k,v := range additional_params {
		params[k] = v;
	}

	for k,v := range params {
		log.Stderrf("param:%s:%s:", k, v);
	}

	m := BuildMessage(url, params);

	key := c.consumer_secret + "&" + token_secret;
	log.Stderrf("key:%s", key);

	digest_str := Digest(key, m);
	params["oauth_signature"] = digest_str;
	log.Stderrf("digest_str:%s", digest_str);

	sparams := urllib.Urlencode(params);
	log.Stderrf("sparams:%s", sparams);

	rurl := strings.Join([]string{url,sparams}, "?");

	log.Stderrf("make_request:rurl:%s", rurl);

	// TODO: no easy way to add header for Authorization:OAuth when protected...?
	return http.Get(rurl);
}
Beispiel #5
0
func BenchmarkRollsum(b *testing.B) {
	bytesSize := int64(1024 * 1024 * 5)
	rs := New()
	bits := 0
	for i := 0; i < b.N; i++ {
		for j := int64(0); j < bytesSize; j++ {
			rs.Roll(byte(rand.Int63() & 0xff))
			if rs.OnSplit() {
				bits = rs.Bits()
			}
		}
	}
	b.SetBytes(bytesSize)
	_ = bits
}
Beispiel #6
0
func (a *Authorizer) K(method, uri string) string {
	rr := a.HA1() + ":" + a.nonce
	if a.qop == "auth" {
		// so we can have predictable test results
		if !a.debug {
			cni := rand.Int63()
			cnib := make([]byte, 8)
			binary.LittleEndian.PutUint64(cnib, uint64(cni))
			a.cnonce = hex.EncodeToString(cnib)
			a.cn += 1
		}
		rr += fmt.Sprintf(":%08d:%s:%s", a.cn, a.cnonce, a.qop)
	}
	rr += ":" + a.HA2(method, uri)
	return rr
}
Beispiel #7
0
func main() {
	rand.Seed(time.Nanoseconds())
	web.Config.CookieSecret = "7C19QRmwf3mHZ9CPAaPQ0hsWeufKd"
	web.Get("/said", func() string { return form })
	web.Post("/say", func(ctx *web.Context) string {
		uid := strconv.Itoa64(rand.Int63())
		ctx.SetSecureCookie("user", uid, 3600)
		users[uid] = ctx.Request.Params["said"]
		return `<a href="/final">Click Here</a>`
	})
	web.Get("/final", func(ctx *web.Context) string {
		uid, _ := ctx.GetSecureCookie("user")
		return "You said " + users[uid]
	})
	web.Run("0.0.0.0:9999")
}
Beispiel #8
0
func putSession(ctx *web.Context, key string, value interface{}) {
	sessionid, _ := ctx.GetSecureCookie("sessionid")
	if sessionid == "" {
		sessionid = strconv.Itoa64(rand.Int63())
		//ctx.SetSecureCookie("sessionid", sessionid, 3600)
		cookie := fmt.Sprintf("%s=%s;path=/;", key, sessionid)
		ctx.SetHeader("Set-Cookie", cookie, false)
		log.Printf("create session:session id=%v", sessionid)
	}
	if sessionMap == nil {
		sessionMap = map[string]map[string]interface{}{sessionid: nil}
	}
	if sessionMap[sessionid] == nil {
		sessionMap[sessionid] = map[string]interface{}{key: value}
	} else {
		sessionMap[sessionid][key] = value
	}
}
Beispiel #9
0
func TestEye64(t *testing.T) {
	fmt.Printf("--> Print some would be addresses for looks:\n")
	for i := 0; i < 5; i++ {
		fmt.Printf("http://xyz/%s/\n", U64ToEye(uint64(rand.Int63())))
	}
	fmt.Printf("\n")

	fmt.Printf("--> Print 0, 1, 3, ...\n")
	for i := 0; i < 2*base+1; i++ {
		fmt.Printf("%d = %s\n", i, U64ToEye(uint64(i)))
	}
	fmt.Printf("\n")

	x := int64(-1234)
	u1 := uint64(x)
	u2 := uint64(1234567890)
	u3 := uint64(12345678901234)
	u4 := uint64(1<<64 - 1)
	fmt.Printf("%d = %s\n", u1, U64ToEye(u1))
	fmt.Printf("%d = %s\n", u2, U64ToEye(u2))
	fmt.Printf("%d = %s\n", u3, U64ToEye(u3))
	fmt.Printf("%d = %s\n", u4, U64ToEye(u4))
	f1 := U64ToEye(u1)
	f2 := U64ToEye(u2)
	if v, err := EyeToU64(f1); v != u1 {
		t.Errorf("U->E->U mismatch: expect %d vs. seen %d, err: %s", u1, v, err)
	}
	if v, err := EyeToU64(f2); v != u2 {
		t.Errorf("U->E->U mismatch: expect %d vs. seen %d, err: %s", u2, v, err)
	}

	/*
		e1 := "ab678"
		e2 := "ghkp8k"
		w1, _ := EyeToU64(e1)
		w2, _ := EyeToU64(e2)
		if U64ToEye(w1) != e1 {
			t.Errorf("E->U->E mismatch: expect %s vs. seen %s", e1, U64ToEye(w1))
		}
		if U64ToEye(w2) != e2 {
			t.Errorf("E->U->E mismatch: expect %s vs. seen %s", e2, U64ToEye(w2))
		}
	*/
}
Beispiel #10
0
func SigninPost(ctx *web.Context, val string) string {
	username := ctx.Params["Username"]
	password := ctx.Params["Password"]
	user := NewUser()
	if db, err := util.GetDB(); err == nil {
		if _, err = db.Retrieve("User_"+username, &user); err == nil {
			if string(util.PasswordHash(password, user.Password.Version).Hash) == string(user.Password.Hash) {
				num := rand.Int63()
				key := username + "_" + strconv.Itoa64(num)
				util.SetUserKey(key, username)
				ctx.SetSecureCookie("UserKey", key, 6000000)
				return util.MessagePage("You are now signed in.", ctx)
			}
			return util.MessagePage("Invalid username and password combination.", ctx)
		}
		return util.MessagePage("Error: Username may not exist.", ctx)
	}
	return util.MessagePage("Could not access the database.", ctx)
}
Beispiel #11
0
func (self *Grapher) CreatePermaBlob(mimeType string) (node AbstractNode, err os.Error) {
	// Create the JSON to compute the hash
	permaJson := map[string]interface{}{"signer": self.userID, "random": fmt.Sprintf("%v", rand.Int63()), "mimeType": mimeType}
	permaBlob, err := json.Marshal(permaJson)
	if err != nil {
		panic(err.String())
	}
	permaBlob = append([]byte(`{"type":"permanode",`), permaBlob[1:]...)
	log.Printf("Storing perma %v\n", string(permaBlob))
	permaBlobRef := newBlobRef(permaBlob)
	// Process it
	var schema superSchema
	schema.Type = "permanode"
	schema.Signer = self.userID
	schema.Random = fmt.Sprintf("%v", rand.Int63())
	schema.MimeType = mimeType
	_, node, err = self.handleSchemaBlob(&schema, permaBlobRef)
	return
}
Beispiel #12
0
Datei: apage.go Projekt: ypb/bwl
// Attaches a handler to a page, and returns a link to it.
func (self *AnonymousPageServer) Handle(h http.Handler) string {
	return self.a.Schedule(func() interface{} {
		// clear cache
		for self.items.Len() >= self.limit {
			e := self.items.Back()
			self.paths[e.Value.(int64)] = nil, false
			self.items.Remove(e)
		}
		// generate a key
		var key int64
		done := false
		for !done {
			key = rand.Int63()
			if _, ok := self.paths[key]; !ok {
				done = true
			}
		}
		// add new item
		self.items.PushFront(key)
		self.paths[key] = h
		// and return the path
		return self.prefix + strconv.Itoa64(key)
	}).(string)
}
Beispiel #13
0
package main

import (
	"github.com/mattn/go-gtk/gdkpixbuf"
	"github.com/mattn/go-gtk/gtk"
	"os"
	"path"
	"rand"
	"state"
)

//Setting up the universe shamelessly lifted from Kevin's textui example.
var u = state.NewSampleUniverse()
var s = u.Instantiate()
var r = rand.New(rand.NewSource(rand.Int63()))
var log = s.Now()
var choices = s.ChosenTransitions()

func updateChoice(k int, buttons []*gtk.GtkButton, textview *gtk.GtkTextView) {
	var end gtk.GtkTextIter
	buffer := textview.GetBuffer()
	// 	buffer.GetStartIter(&start)
	buffer.GetEndIter(&end)
	// 	buffer.Delete(&start, &end)

	choices = s.ChosenTransitions()

	if !(k-1 < len(choices)) {
		return
	}
Beispiel #14
0
// GetRequestAuthorizationURL Returns the URL for the visitor to Authorize the Access
func (oc *OAuthConsumer) GetRequestAuthorizationURL() (string, *RequestToken, os.Error) {
	// Gather the params
	p := Params{}

	// Add required OAuth params
	p.Add(&Pair{Key: "oauth_version", Value: "1.0"})
	p.Add(&Pair{Key: "oauth_timestamp", Value: strconv.Itoa64(time.Seconds())})
	p.Add(&Pair{Key: "oauth_consumer_key", Value: oc.ConsumerKey})
	p.Add(&Pair{Key: "oauth_callback", Value: oc.CallBackURL})
	p.Add(&Pair{Key: "oauth_nonce", Value: strconv.Itoa64(rand.Int63())})
	p.Add(&Pair{Key: "oauth_signature_method", Value: "HMAC-SHA1"})

	// Sort the collection
	sort.Sort(p)

	// Generate string of sorted params
	sigBaseCol := make([]string, len(p)+len(oc.AdditionalParams))
	for i := range p {
		sigBaseCol[i] = Encode(p[i].Key) + "=" + Encode(p[i].Value)
	}

	buf := &bytes.Buffer{}

	i := len(p)
	for _, kv := range oc.AdditionalParams {
		buf.Write([]byte(kv.Key + "=" + Encode(kv.Value) + ""))
		sigBaseCol[i] = kv.Key + "=" + Encode(kv.Value)
		i++
	}

	sigBaseStr := "GET&" +
		Encode(oc.RequestTokenURL) + "&" +
		Encode(strings.Join(sigBaseCol, "&"))

	// Generate Composite Signing key
	key := Encode(oc.ConsumerSecret) + "&" + "" // token secrect is blank on the Request Token

	// Generate Signature
	d := oc.digest(key, sigBaseStr)

	// Build Auth Header
	authHeader := "OAuth "
	for i := range p {
		authHeader += p[i].Key + "=\"" + Encode(p[i].Value) + "\", "
	}

	// Add the signature
	authHeader += "oauth_signature=\"" + Encode(d) + "\""

	headers := map[string]string{
		"Content-Type":  "text/plain",
		"Authorization": authHeader,
	}

	lAddParams := len(oc.AdditionalParams)
	if lAddParams > 0 {
		oc.RequestTokenURL += "?" + string(buf.Bytes())
	}

	r, err := get(oc.RequestTokenURL, headers)

	if err != nil {
		return "", nil, err
	}

	if r.StatusCode != 200 {
		// OAuth service returned an error
		return "", nil, os.NewError("OAuth Service returned an error : " + r.Status)
	}

	b, _ := ioutil.ReadAll(r.Body)
	s := string(b)

	rt := &RequestToken{}

	if strings.Index(s, "&") == -1 {
		// Body is empty
		return "", nil, os.NewError("Empty response from server")
	}

	vals := strings.Split(s, "&", 10)

	for i := range vals {
		if strings.Index(vals[i], "=") > -1 {
			kv := strings.Split(vals[i], "=", 2)
			if len(kv) > 0 { // Adds the key even if there's no value.
				switch kv[0] {
				case "oauth_token":
					if len(kv) > 1 {
						rt.Token = kv[1]
					}
					break
				case "oauth_token_secret":
					if len(kv) > 1 {
						rt.Secret = kv[1]
					}
					break
				}
			}
		}
	}

	oc.appendRequestToken(rt)

	return oc.AuthorizationURL + "?oauth_token=" + rt.Token, rt, nil

}
Beispiel #15
0
func (oc *OAuthConsumer) oAuthRequest(url string, fparams Params, at *AccessToken, method string) (r *http.Response, err os.Error) {

	// Gather the params
	p := Params{}

	hp := Params{}

	// Add required OAuth params
	p.Add(&Pair{Key: "oauth_token", Value: at.Token})
	p.Add(&Pair{Key: "oauth_signature_method", Value: "HMAC-SHA1"})
	p.Add(&Pair{Key: "oauth_consumer_key", Value: oc.ConsumerKey})
	p.Add(&Pair{Key: "oauth_timestamp", Value: strconv.Itoa64(time.Seconds())})
	p.Add(&Pair{Key: "oauth_nonce", Value: strconv.Itoa64(rand.Int63())})
	p.Add(&Pair{Key: "oauth_version", Value: "1.0"})

	// Add the params to the Header collection
	for i := range p {
		hp.Add(&Pair{Key: p[i].Key, Value: p[i].Value})
	}

	fparamsStr := ""
	// Add any additional params passed
	for i := range fparams {
		k, v := fparams[i].Key, fparams[i].Value
		p.Add(&Pair{Key: k, Value: v})
		fparamsStr += k + "=" + Encode(v) + "&"
	}

	// Sort the collection
	sort.Sort(p)

	// Generate string of sorted params
	sigBaseCol := make([]string, len(p))
	for i := range p {
		sigBaseCol[i] = Encode(p[i].Key) + "=" + Encode(p[i].Value)
	}

	sigBaseStr := method + "&" +
		Encode(url) + "&" +
		Encode(strings.Join(sigBaseCol, "&"))

	sigBaseStr = strings.Replace(sigBaseStr, Encode(Encode(at.Token)), Encode(at.Token), 1)

	// Generate Composite Signing key
	key := Encode(oc.ConsumerSecret) + "&" + at.Secret

	// Generate Signature
	d := oc.digest(key, sigBaseStr)

	// Build Auth Header
	authHeader := "OAuth "
	for i := range hp {
		if strings.Index(hp[i].Key, "oauth") == 0 {
			//Add it to the authHeader
			authHeader += hp[i].Key + "=\"" + Encode(hp[i].Value) + "\", "
		}
	}

	// Add the signature
	authHeader += "oauth_signature=\"" + Encode(d) + "\""

	authHeader = strings.Replace(authHeader, Encode(at.Token), at.Token, 1)

	// Add Header & Buffer for params
	buf := bytes.NewBufferString(fparamsStr)
	headers := map[string]string{
		"Authorization": authHeader,
	}

	if method == "GET" {
		// return Get response
		return get(url+"?"+fparamsStr, headers)
	}

	// return POSTs response
	return post(url, headers, buf)

}
func newVertex() *Vertex {
	v := new(Vertex)
	v.id = rand.Int63()
	v.edgeMap = make(map[string]*Edge)
	return v
}
Beispiel #17
0
// For oauth_nonce (if that wasn't obvious).
func nonce() string {
	return strconv.Itoa64(rand.Int63())
}
Beispiel #18
0
func (self *Indexer) CreatePermaBlob() (blobref string, err os.Error) {
	permaJson := map[string]interface{}{"signer": self.userID, "random": fmt.Sprintf("%v", rand.Int63()), "t": "2006-01-02T15:04:05+07:00"}
	// TODO: Get time correctly
	permaBlob, err := json.Marshal(permaJson)
	if err != nil {
		panic(err.String())
	}
	permaBlob = append([]byte(`{"type":"permanode",`), permaBlob[1:]...)
	log.Printf("Storing perma %v\n", string(permaBlob))
	permaBlobRef := NewBlobRef(permaBlob)
	self.store.StoreBlob(permaBlob, permaBlobRef)
	return permaBlobRef, nil
}
func (nv BintValue) Create() string {
	val := rand.Int63()
	val = val * int64(sign())
	return fmt.Sprint(val)
}
Beispiel #20
0
func peerId() string {
	sid := "-tt" + strconv.Itoa(os.Getpid()) + "_" + strconv.Itoa64(rand.Int63())
	return sid[0:20]
}
Beispiel #21
0
// GetAccessToken gets the access token for the response from the Authorization URL
func (oc *OAuthConsumer) GetAccessToken(token string, verifier string) *AccessToken {

	var rt *RequestToken

	// Match the RequestToken by Token
	for i := range oc.requestTokens {
		if oc.requestTokens[i].Token == token ||
			oc.requestTokens[i].Token == Encode(token) {
			rt = oc.requestTokens[i]
		}
	}

	rt.Verifier = verifier

	// Gather the params
	p := Params{}

	// Add required OAuth params
	p.Add(&Pair{Key: "oauth_consumer_key", Value: oc.ConsumerKey})
	p.Add(&Pair{Key: "oauth_token", Value: rt.Token})
	p.Add(&Pair{Key: "oauth_verifier", Value: rt.Verifier})
	p.Add(&Pair{Key: "oauth_signature_method", Value: "HMAC-SHA1"})
	p.Add(&Pair{Key: "oauth_timestamp", Value: strconv.Itoa64(time.Seconds())})
	p.Add(&Pair{Key: "oauth_nonce", Value: strconv.Itoa64(rand.Int63())})
	p.Add(&Pair{Key: "oauth_version", Value: "1.0"})

	// Sort the collection
	sort.Sort(p)

	// Generate string of sorted params
	sigBaseCol := make([]string, len(p))
	for i := range p {
		sigBaseCol[i] = Encode(p[i].Key) + "=" + Encode(p[i].Value)
	}

	sigBaseStr := "POST&" +
		Encode(oc.AccessTokenURL) + "&" +
		Encode(strings.Join(sigBaseCol, "&"))

	sigBaseStr = strings.Replace(sigBaseStr, Encode(Encode(rt.Token)), Encode(rt.Token), 1)

	// Generate Composite Signing key
	key := Encode(oc.ConsumerSecret) + "&" + rt.Secret

	// Generate Signature
	d := oc.digest(key, sigBaseStr)

	// Build Auth Header
	authHeader := "OAuth "
	for i := range p {
		authHeader += p[i].Key + "=\"" + Encode(p[i].Value) + "\", "
	}

	// Add the signature
	authHeader += "oauth_signature=\"" + Encode(d) + "\""

	authHeader = strings.Replace(authHeader, Encode(rt.Token), rt.Token, 1)

	// Add Header & Buffer for params
	buf := &bytes.Buffer{}
	headers := map[string]string{
		"Content-Type":  "application/x-www-form-urlencoded",
		"Authorization": authHeader,
	}

	// Action the POST to get the AccessToken
	r, err := post(oc.AccessTokenURL, headers, buf)

	if err != nil {
		fmt.Println(err.String())
		return nil
	}

	// Read response Body & Create AccessToken
	b, _ := ioutil.ReadAll(r.Body)
	s := string(b)
	at := &AccessToken{Service: oc.Service}

	if strings.Index(s, "&") > -1 {
		vals := strings.Split(s, "&", 10)

		for i := range vals {
			if strings.Index(vals[i], "=") > -1 {
				kv := strings.Split(vals[i], "=", 2)
				if len(kv) > 0 { // Adds the key even if there's no value.
					switch kv[0] {
					case "oauth_token":
						if len(kv) > 1 {
							at.Token = kv[1]
						}
						break
					case "oauth_token_secret":
						if len(kv) > 1 {
							at.Secret = kv[1]
						}
						break
					}
				}
			}
		}
	}

	// Return the AccessToken
	return at

}
Beispiel #22
0
func queryRoleLogin1(cli *mysql.Client) {
	queryName := "[RoleLogin.query1]"
	loopCount := 1000
	type row struct {
		// PK: (date, server, roleid)
		date   string
		server int8
		roleid int64
		money  int32
	}
	fmt.Println(queryName, "started...")
	startTime := time.Nanoseconds()
	for i := 0; i < loopCount; i++ {
		newRow := &row{}
		newRow.date = fmt.Sprintf("2011-%02d-%02d %02d:%02d:%02d",
			rand.Intn(12)+1, // month
			rand.Intn(30)+1, // day
			rand.Intn(24),   // hour
			rand.Intn(60),   // minute
			rand.Intn(60))   // second
		newRow.server = int8(rand.Intn(127))
		newRow.roleid = rand.Int63()
		newRow.money = rand.Int31()
		if VERBOSE_MODE {
			fmt.Printf("%s INSERT IGNORE INTO role_login VALUES(%s, %d, %d, %d)\n",
				queryName, newRow.date, newRow.server, newRow.roleid, newRow.money)
		} else {
			if i == 0 {
				fmt.Printf("%s INSERT IGNORE INTO role_login "+
					"VALUES(%s, %d, %d, %d)\n",
					queryName, newRow.date, newRow.server,
					newRow.roleid, newRow.money)
				fmt.Printf("%s ...(%d lines)\n",
					queryName, loopCount-1)
			}
		}
		if !DRYRUN_MODE {
			cli.Start()
			stmt, err := cli.Prepare("INSERT IGNORE INTO role_login " +
				"VALUES(?,?,?,?)")
			if err != nil {
				fmt.Fprintln(os.Stderr, queryName+err.String())
				os.Exit(1)
			}
			err = stmt.BindParams(newRow.date, newRow.server, newRow.roleid,
				newRow.money)
			if err != nil {
				fmt.Fprintln(os.Stderr, queryName+err.String())
				os.Exit(1)
			}
			err = stmt.Execute()
			if err != nil {
				fmt.Fprintln(os.Stderr, queryName+err.String())
				os.Exit(1)
			}
			cli.Rollback()
		}
		endTime := time.Nanoseconds()
		if !DRYRUN_MODE {
			fmt.Printf("%s ended. Averange query time: %d nanosecs.\n", queryName,
				(endTime-startTime)/((int64)(loopCount)))
		} else {
			fmt.Printf("%s ended.\n", queryName)
		}
	}
}
Beispiel #23
0
func main() {
	flag.Parse()
	if *pprof_port > 0 {
		go prof(*pprof_port)
		log.Println("Pprof listening at port:", *pprof_port)
	}
	runtime.GOMAXPROCS(*procs)
	peerId := (CLIENT_ID + "-" + strconv.Itoa(os.Getpid()) + strconv.Itoa64(rand.Int63()))[0:20]
	log.Println("Peer ID:", peerId)
	// Load torrent file
	torr, err := NewTorrent(*torrent)
	if err != nil {
		log.Println("Error parsing torrent metainfo:", err)
		return
	}
	// Create File Store
	fs, size, err := files.NewFiles(&torr.Info, *folder)
	if err != nil || size <= 0 {
		log.Println("Error parsing files:", err)
		return
	}
	log.Println("Files -> Total size:", size)
	left, bitfield, err := fs.CheckPieces()
	if err != nil {
		log.Println("Error checking pieces:", err)
		return
	}
	// BW Limiter
	limiter, err := limiter.NewLimiter(*up_limit, *down_limit)
	if err != nil {
		return
	}
	// Perform test of the tracker request
	// Initilize Stats
	s := stats.NewStats(left, size, bitfield, torr.Info.Piece_length)
	//go s.Run()
	// Initialize peerMgr
	lastPieceLength := size % torr.Info.Piece_length
	peerMgr, err := peers.NewPeerMgr(int64(bitfield.Len()), peerId, torr.Infohash, bitfield, s, fs, limiter, lastPieceLength)
	if err != nil {
		log.Println("Error creating peer manager:", err)
		return
	}
	if _, *listen_port, err = listener.NewListener(*ip, *listen_port, peerMgr); err != nil {
		log.Println("Error creating listener:", err)
		return
	}
	//go peerMgr.Run()
	// Initialize ChokeMgr
	choke.NewChokeMgr(s, peerMgr)
	// Initialize pieceMgr
	pieceMgr, err := peers.NewPieceMgr(peerMgr, s, fs, bitfield, torr.Info.Piece_length, lastPieceLength, bitfield.Len(), size)
	if err != nil {
		log.Println("Error creating piece manager:", err)
		return
	}
	peerMgr.SetPieceMgr(pieceMgr)
	tracker.NewTrackerMgr(torr.Announce_list, torr.Infohash, *listen_port, peerMgr, left, bitfield, torr.Info.Piece_length, peerId, s)
	for {
		log.Println("Active Peers:", peerMgr.ActivePeers(), "Incoming Peers:", peerMgr.IncomingPeers(), "Unused Peers:", peerMgr.UnusedPeers())
		log.Println("Done:", (bitfield.Count()*100)/bitfield.Len(), "%")
		//log.Println("Bitfield:", bitfield.Bytes())
		time.Sleep(30 * NS_PER_S)
	}
}