Beispiel #1
0
func CTLSAVE_Handler(acMessageCtlReq *AcControlMessageRequest) (acMsgResponse *AcControlMessageResponse, err error) {
	var responseType AcControlMessageResponseAcCTLRRespMsgType
	responseType = AcControlMessageResponse_CTLR_SAVECTX
	reqPassword := acMessageCtlReq.GetPassword()

	acutl.DebugLog.Printf("(CALL) SAVECTX '%s'\n", reqPassword)

	//func (psk PSKMap) Map2FileBlob(outfilestr string, salt []byte, keystr []byte) (bool, error) {
	// TODO: we hardcode the save file
	ok, err := ackp.ACmap.Map2File(ackp.AcSaveFile, []byte(reqPassword))
	if err != nil || ok != false {
		retErr := &acutl.AcError{Value: -1, Msg: "CTLSAVE_Handler().args(outfile, salt, keystr): 0 bytes", Err: nil}
		acMsgResponse = &AcControlMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-1),
		}
		acutl.DebugLog.Printf("(RET[!]) SAVECTX -> (-1) Map2File failed\n")
		return acMsgResponse, retErr
	}
	acMsgResponse = &AcControlMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(true),
		ErrorCode: proto.Int32(0),
	}
	acutl.DebugLog.Printf("(RET) SAVECTX -> (0) ! '%s' saved\n", reqPassword)
	return acMsgResponse, nil
}
Beispiel #2
0
// TODO: Use gauge-go result object rather than ProtoExecutionResult
func executeFunc(fn reflect.Value, args ...interface{}) (res *m.ProtoExecutionResult) {
	rargs := make([]reflect.Value, len(args))
	for i, a := range args {
		rargs[i] = reflect.ValueOf(a)
	}
	res = &m.ProtoExecutionResult{}
	T = &testingT{}
	start := time.Now()
	defer func() {
		if r := recover(); r != nil {
			res.ScreenShot = getScreenshot()
			res.Failed = proto.Bool(true)
			res.ExecutionTime = proto.Int64(time.Since(start).Nanoseconds())
			res.StackTrace = proto.String(strings.SplitN(string(debug.Stack()), "\n", 9)[8])
			res.ErrorMessage = proto.String(fmt.Sprintf("%s", r))
		}
		T = &testingT{}
	}()
	fn.Call(rargs)
	res.Failed = proto.Bool(false)
	if len(T.errors) != 0 {
		res.ScreenShot = getScreenshot()
		res.Failed = proto.Bool(true)
		res.StackTrace = proto.String(T.getStacktraces())
		res.ErrorMessage = proto.String(T.getErrors())
	}
	res.ExecutionTime = proto.Int64(time.Since(start).Nanoseconds())
	return res
}
Beispiel #3
0
func TestClientBucketOperations(t *testing.T) {
	assert := assert.New(t)
	client := NewClient("127.0.0.1:8087", 1)

	// SetBucket and GetBucket
	setReq := &RpbSetBucketReq{
		Bucket: []byte("riago_test"),
		Props: &RpbBucketProps{
			NVal:          proto.Uint32(2),
			AllowMult:     proto.Bool(false),
			LastWriteWins: proto.Bool(true),
		},
	}

	err := client.SetBucket(setReq)
	assert.Nil(err)

	getReq := &RpbGetBucketReq{
		Bucket: []byte("riago_test"),
	}

	getResp, err := client.GetBucket(getReq)
	assert.Nil(err)
	assert.Equal(uint32(2), getResp.GetProps().GetNVal())
	assert.Equal(false, getResp.GetProps().GetAllowMult())
	assert.Equal(true, getResp.GetProps().GetLastWriteWins())
}
Beispiel #4
0
func OnCreateDeck(s *Session, body []byte) ([]byte, error) {
	req := hsproto.PegasusUtil_CreateDeck{}
	err := proto.Unmarshal(body, &req)
	if err != nil {
		return nil, err
	}

	deck := Deck{
		AccountID:    s.Account.ID,
		DeckType:     int(req.GetDeckType()),
		Name:         req.GetName(),
		HeroID:       int32(req.GetHero()),
		HeroPremium:  int32(req.GetHeroPremium()),
		CardBackID:   0,
		LastModified: time.Now().UTC(),
	}
	db.Create(&deck)

	res := hsproto.PegasusUtil_DeckCreated{}

	info := hsproto.PegasusShared_DeckInfo{}
	info.Id = proto.Int64(deck.ID)
	info.Name = req.Name
	info.DeckType = req.DeckType
	info.CardBack = proto.Int32(1)
	info.CardBackOverride = proto.Bool(false)
	info.Hero = req.Hero
	info.HeroPremium = req.HeroPremium
	info.HeroOverride = proto.Bool(false)
	info.Validity = proto.Uint64(1)
	res.Info = &info
	return EncodeUtilResponse(217, &res)
}
Beispiel #5
0
func (dt *DTable) zmq_status_handler(request *dendrite.ChordMsg, w chan *dendrite.ChordMsg) {
	pbMsg := request.TransportMsg.(PBDTableStatus)

	dest := dendrite.VnodeFromProtobuf(pbMsg.GetDest())
	dest_key_str := fmt.Sprintf("%x", dest.Id)
	zmq_transport := dt.transport.(*dendrite.ZMQTransport)

	// make sure destination vnode exists locally
	_, ok := dt.table[dest_key_str]
	setResp := &PBDTableResponse{}
	if !ok {
		setResp.Ok = proto.Bool(false)
		setResp.Error = proto.String("local dtable vnode not found")
	} else {
		setResp.Ok = proto.Bool(true)
	}

	// encode and send the response
	pbdata, err := proto.Marshal(setResp)
	if err != nil {
		errorMsg := zmq_transport.NewErrorMsg("ZMQ::DTable::StatusHandler - failed to marshal response - " + err.Error())
		w <- errorMsg
		return
	}
	w <- &dendrite.ChordMsg{
		Type: PbDtableResponse,
		Data: pbdata,
	}
	return
}
Beispiel #6
0
// TODO: error code is not handled properly
func PKDEL_Handler(acMessagePkReq *AcPublicKeyMessageRequest) (acMsgResponse *AcPublicKeyMessageResponse, err error) {
	var responseType AcPublicKeyMessageResponseAcPKRespMsgType
	responseType = AcPublicKeyMessageResponse_PKR_DEL

	// request: type && nick && server                   -> delete the specific public key
	reqNick := acMessagePkReq.GetNick()
	reqServ := acMessagePkReq.GetServer()
	acutl.DebugLog.Printf("(CALL) PKDEL <- '%s' ! <host> / %s\n", reqNick, reqServ)

	if len(reqNick) > 0 && len(reqServ) > 0 { // IS A SPECIFIC NICK REQUESTED ?!?!
		//_, ok := Pk[reqNick]
		//Pk, ok := ackp.ACmap.GetPKMap(reqServ)
		ok := ackp.ACmap.DelPKMapEntry(reqServ, reqNick)
		if ok == true {
			//delete(Pk, reqNick)
			acMsgResponse = &AcPublicKeyMessageResponse{
				Type:      &responseType,
				Bada:      proto.Bool(true),
				ErrorCode: proto.Int32(0), // no such nickname
			}
			acutl.DebugLog.Printf("(RET) PKDEL -> (0) ! deleted key\n")
			return acMsgResponse, nil
		}
	}

	// XXX TODO: not sure If I should remove all keys or just return error
	retErr := &acutl.AcError{Value: -1, Msg: "PKDEL_Handler().reqServ|reqNick: 0 bytes", Err: nil}
	acMsgResponse = &AcPublicKeyMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(false),
		ErrorCode: proto.Int32(-1), // no such nickname
	}
	acutl.DebugLog.Printf("(RET[!]) PKDEL -> (-1) ! missing argument\n")
	return acMsgResponse, retErr
}
Beispiel #7
0
func (s *Server) handleAppendEntriesRequest(appendRequest *AppendEntriesRequest) *AppendEntriesResponse {
	resp := &AppendEntriesResponse{
		Term:    proto.Int64(s.currentTerm),
		Success: proto.Bool(false)}
	if s.currentTerm > appendRequest.GetTerm() {
		return resp
	}
	if s.currentTerm < appendRequest.GetTerm() {
		s.updateCurrentTerm(appendRequest.GetTerm())
	}
	if s.log.contains(appendRequest.GetPrevLogIndex(), appendRequest.GetPrevLogTerm()) {
		s.log.appendEntries(s, appendRequest.GetPrevLogIndex(), appendRequest.GetEntries())
		resp.Success = proto.Bool(true)

		if s.leader == noleader {
			s.leader = appendRequest.GetLeaderID()
		}

		if appendRequest.GetCommitIndex() > s.log.commitIndex {
			s.log.setCommitIndex(appendRequest.GetCommitIndex(), s.context)
		}

		s.resetElectionTimeout()
	}
	return resp
}
Beispiel #8
0
func TestStringSave(t *testing.T) {

	options := MysqlOptions{
		Addr:         "localhost:3306",
		DB:           "kite",
		Username:     "******",
		Password:     "",
		ShardNum:     4,
		BatchUpSize:  100,
		BatchDelSize: 100,
		FlushPeriod:  10 * time.Millisecond,
		MaxIdleConn:  10,
		MaxOpenConn:  10}

	kiteMysql := NewKiteMysql(options, "localhost")
	truncate(kiteMysql)
	for i := 0; i < 16; i++ {
		//创建消息
		msg := &protocol.StringMessage{}
		msg.Header = &protocol.Header{
			MessageId:    proto.String("26c03f00665862591f696a980b5a6" + fmt.Sprintf("%x", i)),
			Topic:        proto.String("trade"),
			MessageType:  proto.String("pay-succ"),
			ExpiredTime:  proto.Int64(time.Now().Add(10 * time.Minute).Unix()),
			DeliverLimit: proto.Int32(100),
			GroupId:      proto.String("go-kite-test"),
			Commit:       proto.Bool(false),
			Fly:          proto.Bool(false)}

		msg.Body = proto.String("hello world")
		innerT(kiteMysql, msg, msg.GetHeader().GetMessageId(), t)
	}
	kiteMysql.Stop()
}
Beispiel #9
0
func doPerRPCCreds(tc testpb.TestServiceClient) {
	jsonKey := getServiceAccountJSONKey()
	pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
	req := &testpb.SimpleRequest{
		ResponseType:   testpb.PayloadType_COMPRESSABLE.Enum(),
		ResponseSize:   proto.Int32(int32(largeRespSize)),
		Payload:        pl,
		FillUsername:   proto.Bool(true),
		FillOauthScope: proto.Bool(true),
	}
	token := getToken()
	kv := map[string]string{"authorization": token.TokenType + " " + token.AccessToken}
	ctx := metadata.NewContext(context.Background(), metadata.MD{"authorization": []string{kv["authorization"]}})
	reply, err := tc.UnaryCall(ctx, req)
	if err != nil {
		grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
	}
	user := reply.GetUsername()
	scope := reply.GetOauthScope()
	if !strings.Contains(string(jsonKey), user) {
		grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
	}
	if !strings.Contains(*oauthScope, scope) {
		grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
	}
	grpclog.Println("PerRPCCreds done")
}
Beispiel #10
0
func OnCreateDeck(s *Session, body []byte) *Packet {
	req := util.CreateDeck{}
	err := proto.Unmarshal(body, &req)
	if err != nil {
		panic(err)
	}

	deck := Deck{
		AccountID:    s.Account.ID,
		DeckType:     int(req.GetDeckType()),
		Name:         req.GetName(),
		HeroID:       int32(req.GetHero()),
		HeroPremium:  int32(req.GetHeroPremium()),
		CardBackID:   0,
		LastModified: time.Now().UTC(),
	}
	db.Create(&deck)

	res := util.DeckCreated{}

	info := shared.DeckInfo{}
	info.Id = proto.Int64(deck.ID)
	info.Name = req.Name
	info.DeckType = req.DeckType
	info.CardBack = proto.Int32(1)
	info.CardBackOverride = proto.Bool(false)
	info.Hero = req.Hero
	info.HeroPremium = req.HeroPremium
	info.HeroOverride = proto.Bool(false)
	info.Validity = proto.Uint64(1)
	res.Info = &info
	return EncodePacket(util.DeckCreated_ID, &res)
}
Beispiel #11
0
func (executor *specExecutor) executeStep(protoStep *gauge_messages.ProtoStep) bool {
	stepRequest := executor.createStepRequest(protoStep)
	executor.logger.Debug("Executing Step: %s", formatter.FormatStep(parser.CreateStepFromStepRequest(stepRequest)))
	protoStepExecResult := &gauge_messages.ProtoStepExecutionResult{}
	executor.currentExecutionInfo.CurrentStep = &gauge_messages.StepInfo{Step: stepRequest, IsFailed: proto.Bool(false)}

	beforeHookStatus := executor.executeBeforeStepHook()
	if beforeHookStatus.GetFailed() {
		protoStepExecResult.PreHookFailure = result.GetProtoHookFailure(beforeHookStatus)
		protoStepExecResult.ExecutionResult = &gauge_messages.ProtoExecutionResult{Failed: proto.Bool(true)}
		setStepFailure(executor.currentExecutionInfo, executor.logger)
		printStatus(beforeHookStatus, executor.logger)
	} else {
		executeStepMessage := &gauge_messages.Message{MessageType: gauge_messages.Message_ExecuteStep.Enum(), ExecuteStepRequest: stepRequest}
		stepExecutionStatus := executeAndGetStatus(executor.runner, executeStepMessage)
		if stepExecutionStatus.GetFailed() {
			setStepFailure(executor.currentExecutionInfo, executor.logger)
			printStatus(stepExecutionStatus, executor.logger)
		}
		protoStepExecResult.ExecutionResult = stepExecutionStatus
	}
	afterStepHookStatus := executor.executeAfterStepHook()
	addExecutionTimes(protoStepExecResult, beforeHookStatus, afterStepHookStatus)
	if afterStepHookStatus.GetFailed() {
		setStepFailure(executor.currentExecutionInfo, executor.logger)
		printStatus(afterStepHookStatus, executor.logger)
		protoStepExecResult.PostHookFailure = result.GetProtoHookFailure(afterStepHookStatus)
		protoStepExecResult.ExecutionResult.Failed = proto.Bool(true)
	}
	protoStepExecResult.Skipped = protoStep.StepExecutionResult.Skipped
	protoStepExecResult.SkippedReason = protoStep.StepExecutionResult.SkippedReason
	protoStep.StepExecutionResult = protoStepExecResult
	return protoStep.GetStepExecutionResult().GetExecutionResult().GetFailed()
}
Beispiel #12
0
func CTLLOAD_Handler(acMessageCtlReq *AcControlMessageRequest) (acMsgResponse *AcControlMessageResponse, err error) {
	var responseType AcControlMessageResponseAcCTLRRespMsgType
	responseType = AcControlMessageResponse_CTLR_LOADCTX
	reqPassword := acMessageCtlReq.GetPassword()

	acutl.DebugLog.Printf("(CALL) LOADCTX '%s'\n", []byte(reqPassword))

	ok, err := ackp.ACmap.File2Map(ackp.AcSaveFile, []byte(reqPassword))
	if err != nil || ok != false {
		retErr := &acutl.AcError{Value: -1, Msg: "CTLLOAD_Handler().args(outfile, salt, keystr): 0 bytes", Err: nil}
		acMsgResponse = &AcControlMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-1),
		}
		acutl.DebugLog.Printf("(RET[!]) LOADCTX -> (-1)\n")
		return acMsgResponse, retErr
	}
	acMsgResponse = &AcControlMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(true),
		ErrorCode: proto.Int32(0),
	}
	acutl.DebugLog.Printf("(RET) LOADCTX -> (0) ! '%s' opened\n", reqPassword)
	return acMsgResponse, nil
}
Beispiel #13
0
func CTLPING_Handler(acMessageCtlReq *AcControlMessageRequest) (acMsgResponse *AcControlMessageResponse, err error) {
	var responseType AcControlMessageResponseAcCTLRRespMsgType
	responseType = AcControlMessageResponse_CTLR_PONG
	timeStamp := acMessageCtlReq.GetTimestamp()

	acutl.DebugLog.Printf("(CALL) CTLPING timestamp: %d\n", timeStamp)

	if timeStamp <= 0 {
		retErr := &acutl.AcError{Value: -1, Msg: "CTLPING invalid timestamp", Err: nil}
		acMsgResponse = &AcControlMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-1),
		}
		acutl.DebugLog.Printf("(RET[!]) CTLPING -> (-1) ! %s\n", retErr.Error())
		return acMsgResponse, retErr
	}

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

	acMsgResponse = &AcControlMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(true),
		ErrorCode: proto.Int32(0), // should be good enough for now... but better have a separate field with correct type..
		Timestamp: &replyTime,
	}
	acutl.DebugLog.Printf("(RET) CTLPING -> (0) ! PONG REPLIED. %d\n", replyTime)
	return acMsgResponse, nil
}
Beispiel #14
0
func newPresenceResponse(isAvailable bool, presence pb.PresenceResponse_SHOW, valid bool) *pb.PresenceResponse {
	return &pb.PresenceResponse{
		IsAvailable: proto.Bool(isAvailable),
		Presence:    presence.Enum(),
		Valid:       proto.Bool(valid),
	}
}
Beispiel #15
0
func marshalFact(m *ProtoFact, f *origins.Fact) ([]byte, error) {
	m.Reset()

	m.EntityDomain = proto.String(f.Entity.Domain)
	m.Entity = proto.String(f.Entity.Name)

	m.AttributeDomain = proto.String(f.Attribute.Domain)
	m.Attribute = proto.String(f.Attribute.Name)

	m.ValueDomain = proto.String(f.Value.Domain)
	m.Value = proto.String(f.Value.Name)

	m.Time = proto.Int64(chrono.TimeMicro(f.Time))

	switch f.Operation {
	case origins.Assertion:
		m.Added = proto.Bool(true)
	case origins.Retraction:
		m.Added = proto.Bool(false)
	default:
		panic("fact: invalid op")
	}

	return proto.Marshal(m)
}
func (s *MySuite) TestToVerifyXmlContentForDataTableDrivenExecution(c *C) {
	value := gauge_messages.ProtoItem_TableDrivenScenario
	scenario := gauge_messages.ProtoScenario{Failed: proto.Bool(false), ScenarioHeading: proto.String("Scenario")}
	scenario1 := gauge_messages.ProtoScenario{Failed: proto.Bool(false), ScenarioHeading: proto.String("Scenario")}
	item := &gauge_messages.ProtoItem{TableDrivenScenario: &gauge_messages.ProtoTableDrivenScenario{Scenarios: []*gauge_messages.ProtoScenario{&scenario, &scenario1}}, ItemType: &value}
	spec := &gauge_messages.ProtoSpec{SpecHeading: proto.String("HEADING"), FileName: proto.String("FILENAME"), Items: []*gauge_messages.ProtoItem{item}}
	specResult := &gauge_messages.ProtoSpecResult{ProtoSpec: spec, ScenarioCount: proto.Int(1), Failed: proto.Bool(false)}
	suiteResult := &gauge_messages.ProtoSuiteResult{SpecResults: []*gauge_messages.ProtoSpecResult{specResult}}
	message := &gauge_messages.SuiteExecutionResult{SuiteResult: suiteResult}

	builder := &XmlBuilder{currentId: 0}
	bytes, err := builder.getXmlContent(message)
	var suites JUnitTestSuites
	xml.Unmarshal(bytes, &suites)

	c.Assert(err, Equals, nil)
	c.Assert(len(suites.Suites), Equals, 1)
	c.Assert(suites.Suites[0].Errors, Equals, 0)
	c.Assert(suites.Suites[0].Failures, Equals, 0)
	c.Assert(suites.Suites[0].Package, Equals, "FILENAME")
	c.Assert(suites.Suites[0].Name, Equals, "HEADING")
	c.Assert(suites.Suites[0].Tests, Equals, 2)
	c.Assert(suites.Suites[0].Timestamp, Equals, builder.suites.Suites[0].Timestamp)
	c.Assert(suites.Suites[0].SystemError.Contents, Equals, "")
	c.Assert(suites.Suites[0].SystemOutput.Contents, Equals, "")
	c.Assert(len(suites.Suites[0].TestCases), Equals, 2)
	c.Assert(suites.Suites[0].TestCases[0].Name, Equals, "Scenario 0")
	c.Assert(suites.Suites[0].TestCases[1].Name, Equals, "Scenario 1")
}
Beispiel #17
0
// Serialize serializes this RPC into a buffer.
func (g *Get) Serialize() ([]byte, error) {
	get := &pb.GetRequest{
		Region: g.regionSpecifier(),
		Get: &pb.Get{
			Row:       g.key,
			Column:    familiesToColumn(g.families),
			TimeRange: &pb.TimeRange{},
		},
	}
	if g.maxVersions != DefaultMaxVersions {
		get.Get.MaxVersions = &g.maxVersions
	}
	if g.fromTimestamp != MinTimestamp {
		get.Get.TimeRange.From = &g.fromTimestamp
	}
	if g.toTimestamp != MaxTimestamp {
		get.Get.TimeRange.To = &g.toTimestamp
	}
	if g.closestBefore {
		get.Get.ClosestRowBefore = proto.Bool(true)
	}
	if g.existsOnly {
		get.Get.ExistenceOnly = proto.Bool(true)
	}
	if g.filters != nil {
		pbFilter, err := g.filters.ConstructPBFilter()
		if err != nil {
			return nil, err
		}
		get.Get.Filter = pbFilter
	}
	return proto.Marshal(get)
}
Beispiel #18
0
func PKGEN_Handler(acMessagePkReq *AcPublicKeyMessageRequest) (acMsgResponse *AcPublicKeyMessageResponse, err error) {
	var responseType AcPublicKeyMessageResponseAcPKRespMsgType
	responseType = AcPublicKeyMessageResponse_PKR_GEN

	reqNick := acMessagePkReq.GetNick()
	reqHost := acMessagePkReq.GetHost()
	reqServ := acMessagePkReq.GetServer()

	acutl.DebugLog.Printf("(CALL) PKGEN <- %s ! %s / %s\n", reqNick, reqHost, reqServ)

	if len(reqServ) == 0 || len(reqNick) == 0 {
		retErr := &acutl.AcError{Value: -1, Msg: "PKGEN_Handler().Get{Nick|Server}(): 0 bytes", Err: nil}
		acMsgResponse = &AcPublicKeyMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-1),
			Blob:      []byte(retErr.Error()),
		}
		acutl.DebugLog.Printf("(RET[!]) PKGEN -> (-1) ! %s\n", retErr.Error())
		return acMsgResponse, retErr
	}

	myNewKeys, err := ackp.CreateKxKeys(reqNick, reqHost, reqServ)
	if err != nil {
		retErr := &acutl.AcError{Value: -2, Msg: "PKGEN_Handler().CreateMyKeys(): ", Err: err}
		acMsgResponse = &AcPublicKeyMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-2),
			Blob:      []byte(retErr.Error()),
		}
		acutl.DebugLog.Printf("(RET[!]) PKGEN -> (-2) ! %s\n", retErr.Error())
		return acMsgResponse, retErr
	}
	// create the cached version instead of in CreateMyKeys()
	PK, err := accp.CreatePKMessageNACL(myNewKeys.GetPubkey()[:])
	if err != nil {
		retErr := &acutl.AcError{Value: -3, Msg: "PKGEN_Handler().CreateCachePubkey: ", Err: err}
		acMsgResponse = &AcPublicKeyMessageResponse{
			Type:      &responseType,
			Bada:      proto.Bool(false),
			ErrorCode: proto.Int32(-3),
			Blob:      []byte(retErr.Error()),
		}
		acutl.DebugLog.Printf("(RET[!]) PKGEN -> (-3) ! %s\n", retErr.Error())
		return acMsgResponse, retErr
	}
	myNewKeys.Pubkey = string(PK)

	// create the Public Key storage if it's empty...
	ackp.ACmap.SetPKMapEntry(reqServ, reqNick, myNewKeys)
	acMsgResponse = &AcPublicKeyMessageResponse{
		Type:      &responseType,
		Bada:      proto.Bool(true),
		ErrorCode: proto.Int32(0),
	}
	acutl.DebugLog.Printf("(RET) PKGEN -> (0) ! Key Generated.\n")
	return acMsgResponse, nil
}
Beispiel #19
0
func (executor *specExecutor) setSkipInfo(protoStep *gauge_messages.ProtoStep, step *parser.Step) {
	protoStep.StepExecutionResult = &gauge_messages.ProtoStepExecutionResult{}
	protoStep.StepExecutionResult.Skipped = proto.Bool(false)
	if _, ok := executor.errMap.stepErrs[step]; ok {
		protoStep.StepExecutionResult.Skipped = proto.Bool(true)
		protoStep.StepExecutionResult.SkippedReason = proto.String("Step implemenatation not found")
	}
}
Beispiel #20
0
// NewRowRange is TODO
func NewRowRange(startRow, stopRow []byte, startRowInclusive, stopRowInclusive bool) *RowRange {
	return &RowRange{
		StartRow:          startRow,
		StartRowInclusive: proto.Bool(startRowInclusive),
		StopRow:           stopRow,
		StopRowInclusive:  proto.Bool(stopRowInclusive),
	}
}
Beispiel #21
0
// This function tests that basic workflow works.
func TestSuccessPath(t *testing.T) {
	pbs := []*pb.LanzRecord{
		{
			ConfigRecord: &pb.ConfigRecord{
				Timestamp:    proto.Uint64(146591697107544),
				LanzVersion:  proto.Uint32(1),
				NumOfPorts:   proto.Uint32(146),
				SegmentSize:  proto.Uint32(512),
				MaxQueueSize: proto.Uint32(524288000),
				PortConfigRecord: []*pb.ConfigRecord_PortConfigRecord{
					{
						IntfName:      proto.String("Cpu"),
						SwitchId:      proto.Uint32(2048),
						PortId:        proto.Uint32(4096),
						InternalPort:  proto.Bool(false),
						HighThreshold: proto.Uint32(50000),
						LowThreshold:  proto.Uint32(25000),
					},
				},
				GlobalUsageReportingEnabled: proto.Bool(true),
			},
		},
		{
			CongestionRecord: &pb.CongestionRecord{
				Timestamp: proto.Uint64(146591697107546),
				IntfName:  proto.String("Cpu"),
				SwitchId:  proto.Uint32(2048),
				PortId:    proto.Uint32(4096),
				QueueSize: proto.Uint32(30000),
			},
		},
		{
			ErrorRecord: &pb.ErrorRecord{
				Timestamp:    proto.Uint64(146591697107549),
				ErrorMessage: proto.String("Error"),
			},
		},
	}

	conn := &testConnector{reader: bytes.NewReader(pbsToStream(pbs))}
	ch := make(chan *pb.LanzRecord)
	c, done := launchClient(ch, conn)
	for i, p := range pbs {
		r, ok := <-ch
		if !ok {
			t.Fatalf("Unexpected closed channel")
		}
		if !test.DeepEqual(p, r) {
			t.Fatalf("Test case %d: expected %v, but got %v", i, p, r)
		}
	}
	c.Stop()
	<-done
	if conn.open {
		t.Fatalf("Connection still open after stopping")
	}
}
Beispiel #22
0
// NewColumnRangeFilter is TODO
func NewColumnRangeFilter(minColumn, maxColumn []byte,
	minColumnInclusive, maxColumnInclusive bool) *ColumnRangeFilter {
	return &ColumnRangeFilter{
		MinColumn:          minColumn,
		MaxColumn:          maxColumn,
		MinColumnInclusive: proto.Bool(minColumnInclusive),
		MaxColumnInclusive: proto.Bool(maxColumnInclusive),
	}
}
func TestFileStoreUpdate(t *testing.T) {
	cleanSnapshot("./snapshot/")
	fs := NewKiteFileStore(".", 5000000, 1*time.Second)
	fs.Start()

	for i := 0; i < 100; i++ {
		//创建消息
		msg := &protocol.BytesMessage{}
		msg.Header = &protocol.Header{
			MessageId:    proto.String(fmt.Sprintf("%x", i) + "26c03f00665862591f696a980b5ac"),
			Topic:        proto.String("trade"),
			MessageType:  proto.String("pay-succ"),
			ExpiredTime:  proto.Int64(time.Now().Add(10 * time.Minute).Unix()),
			DeliverLimit: proto.Int32(100),
			GroupId:      proto.String("go-kite-test"),
			Commit:       proto.Bool(true),
			Fly:          proto.Bool(false)}
		msg.Body = []byte("hello world")

		entity := store.NewMessageEntity(protocol.NewQMessage(msg))
		// log.Printf("------------%s", entity.Header)
		succ := fs.Save(entity)
		if !succ {
			t.Fail()
		}
	}

	//commit and check
	for i := 0; i < 100; i++ {
		id := fmt.Sprintf("%x", i) + "26c03f00665862591f696a980b5ac"

		//创建消息
		msg := &store.MessageEntity{
			MessageId:    id,
			DeliverCount: 1,
			SuccGroups:   []string{},
			FailGroups:   []string{"s-mts-test"}}

		succ := fs.UpdateEntity(msg)
		if !succ {
			t.Fail()
		}
		//check entity
		entity := fs.Query(id)
		// log.Printf("++++++++++++++|%s|%s", entity.Header, string(entity.GetBody().([]byte)))
		if nil == entity {
			t.Fail()
		} else if !entity.Commit && entity.DeliverCount != 1 &&
			entity.FailGroups[0] != "s-mts-test" {
			t.Fail()
			// log.Println(entity)
		}
	}
	fs.Stop()
	// cleanSnapshot("./snapshot/")
}
Beispiel #24
0
// Compile all information exported through the hackerspace API and send it
// back to the requestor.
func (a *SpaceAPI) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	var msg = proto.Clone(a.conf.SpaceapiMd)
	var md *doorky.SpaceAPIMetadata
	var door *doorky.DoorSecret
	var out []byte
	var err error
	var ok bool

	md, ok = msg.(*doorky.SpaceAPIMetadata)
	if !ok {
		log.Print("Error: message is not of type SpaceAPIMetadata")
		http.Error(rw, http.StatusText(http.StatusInternalServerError),
			http.StatusInternalServerError)
	}

	for _, door = range a.conf.Secret {
		var lockInfo = new(doorky.SpaceAPIDoorLockSensor)
		var name = door.GetName()
		var ts time.Time
		var isOpen bool

		ts, isOpen, err = a.ts.LastValue(name)
		if err != nil {
			log.Print("Error fetching door status for ", name, ": ", err)
			continue
		}

		lockInfo.Value = proto.Bool(!isOpen)
		lockInfo.Location = proto.String(door.GetLocation())
		lockInfo.Name = proto.String(name)
		lockInfo.Description = proto.String("Last update: " + ts.String())

		if md.Sensors == nil {
			md.Sensors = new(doorky.SpaceAPISensors)
		}
		md.Sensors.DoorLocked = append(md.Sensors.DoorLocked, lockInfo)

		if a.conf.PrimaryDoor != nil && a.conf.GetPrimaryDoor() == name {
			md.State.Open = proto.Bool(isOpen)
			md.State.Lastchange = proto.Int64(ts.Unix())
		}
	}

	out, err = json.MarshalIndent(md, "    ", "    ")
	if err != nil {
		log.Print("Error marshalling JSON: ", err)
		http.Error(rw, http.StatusText(http.StatusInternalServerError)+": "+
			"Error marshalling response: "+err.Error(),
			http.StatusInternalServerError)
	}

	_, err = rw.Write(out)
	if err != nil {
		log.Print("Error writing response: ", err)
	}
}
func (t *NotificationTemplate) GetActionChains() []*protobuf.ActionChain {

	//set actionChain
	actionChain1 := &protobuf.ActionChain{
		ActionId: proto.Int32(1),
		Type:     protobuf.ActionChain_Goto.Enum(),
		Next:     proto.Int32(10000),
	}

	//notification
	actionChain2 := &protobuf.ActionChain{
		ActionId:  proto.Int32(10000),
		Type:      protobuf.ActionChain_notification.Enum(),
		Title:     proto.String(t.Title),
		Text:      proto.String(t.Text),
		Logo:      proto.String(t.Logo),
		Ring:      proto.Bool(t.IsRing),
		Clearable: proto.Bool(t.IsClearable),
		Buzz:      proto.Bool(t.IsVibrate),
		Next:      proto.Int32(10010),
	}

	//goto
	actionChain3 := &protobuf.ActionChain{
		ActionId: proto.Int32(10010),
		Type:     protobuf.ActionChain_Goto.Enum(),
		Next:     proto.Int32(10030),
	}

	//appStartUp
	appStartUp := &protobuf.AppStartUp{
		Android: proto.String(""),
		Symbia:  proto.String(""),
		Ios:     proto.String(""),
	}

	//start app
	actionChain4 := &protobuf.ActionChain{
		ActionId:     proto.Int32(10030),
		Type:         protobuf.ActionChain_startapp.Enum(),
		Appid:        proto.String(""),
		Autostart:    proto.Bool(t.TransmissionType == 1),
		Appstartupid: appStartUp,
		FailedAction: proto.Int32(100),
		Next:         proto.Int32(100),
	}
	//end
	actionChain5 := &protobuf.ActionChain{
		ActionId: proto.Int32(100),
		Type:     protobuf.ActionChain_eoa.Enum(),
	}

	actionChains := []*protobuf.ActionChain{actionChain1, actionChain2, actionChain3, actionChain4, actionChain5}

	return actionChains
}
func fakeRunQuery(in *pb.Query, out *pb.QueryResult) error {
	expectedIn := &pb.Query{
		App:     proto.String("dev~fake-app"),
		Kind:    proto.String("Gopher"),
		Compile: proto.Bool(true),
	}
	if !proto.Equal(in, expectedIn) {
		return fmt.Errorf("unsupported argument: got %v want %v", in, expectedIn)
	}
	*out = pb.QueryResult{
		Result: []*pb.EntityProto{
			{
				Key: &pb.Reference{
					App:  proto.String("s~test-app"),
					Path: path1,
				},
				EntityGroup: path1,
				Property: []*pb.Property{
					{
						Meaning: pb.Property_TEXT.Enum(),
						Name:    proto.String("Name"),
						Value: &pb.PropertyValue{
							StringValue: proto.String("George"),
						},
					},
					{
						Name: proto.String("Height"),
						Value: &pb.PropertyValue{
							Int64Value: proto.Int64(32),
						},
					},
				},
			},
			{
				Key: &pb.Reference{
					App:  proto.String("s~test-app"),
					Path: path2,
				},
				EntityGroup: path1, // ancestor is George
				Property: []*pb.Property{
					{
						Meaning: pb.Property_TEXT.Enum(),
						Name:    proto.String("Name"),
						Value: &pb.PropertyValue{
							StringValue: proto.String("Rufus"),
						},
					},
					// No height for Rufus.
				},
			},
		},
		MoreResults: proto.Bool(false),
	}
	return nil
}
func TestConvert2Entity(t *testing.T) {

	options := MysqlOptions{
		Addr:         "localhost:3306",
		Username:     "******",
		Password:     "",
		ShardNum:     4,
		BatchUpSize:  1000,
		BatchDelSize: 1000,
		FlushPeriod:  1 * time.Minute,
		MaxIdleConn:  2,
		MaxOpenConn:  4}

	hs := newDbShard(options)

	c := convertor{}
	sqlwrapper := newSqlwrapper("kite_msg", hs, store.MessageEntity{})
	sqlwrapper.initSQL()
	c.columns = sqlwrapper.columns

	//创建消息
	msg := &protocol.BytesMessage{}
	msg.Header = &protocol.Header{
		MessageId:    proto.String("26c03f00665462591f696a980b5a6c4"),
		Topic:        proto.String("trade"),
		MessageType:  proto.String("pay-succ"),
		ExpiredTime:  proto.Int64(time.Now().Add(10 * time.Minute).Unix()),
		DeliverLimit: proto.Int32(100),
		GroupId:      proto.String("go-kite-test"),
		Commit:       proto.Bool(false),
		Fly:          proto.Bool(false)}
	msg.Body = []byte("hello world")

	entity := store.NewMessageEntity(protocol.NewQMessage(msg))
	entity.SuccGroups = []string{"go-kite-test"}
	hn, _ := os.Hostname()
	entity.KiteServer = hn

	params := c.Convert2Params(entity)
	t.Logf("TestConvert2Entity|Convert2Params|%s\n", params)
	econ := &store.MessageEntity{}
	c.Convert2Entity(params, econ, func(colname string) bool {
		return false
	})
	t.Logf("TestConvert2Entity|Convert2Entity|%s\n", econ)
	if econ.MessageId != entity.MessageId {
		t.Fail()
	}

	if econ.ExpiredTime != entity.ExpiredTime {
		t.Fail()
	}

}
Beispiel #28
0
func (ch *authHSChan) sendResult(accepted, isKnown bool) error {
	authResult := &packet.AuthHSResult{Accepted: proto.Bool(accepted)}
	if accepted {
		authResult.IsKnownContact = proto.Bool(isKnown)
	}
	authPkt := &packet.AuthHSPacket{Result: authResult}
	rawPkt, err := proto.Marshal(authPkt)
	if err != nil {
		return err
	}
	return ch.conn.sendPacket(ch.chanID, rawPkt)
}
Beispiel #29
0
// Freeze a Group into a flattened protobuf-based structure
// ready to be persisted to disk.
func FreezeGroup(group acl.Group) (*freezer.Group, error) {
	frozenGroup := &freezer.Group{}
	frozenGroup.Name = proto.String(group.Name)
	frozenGroup.Inherit = proto.Bool(group.Inherit)
	frozenGroup.Inheritable = proto.Bool(group.Inheritable)
	for _, id := range group.AddUsers() {
		frozenGroup.Add = append(frozenGroup.Add, uint32(id))
	}
	for _, id := range group.RemoveUsers() {
		frozenGroup.Remove = append(frozenGroup.Remove, uint32(id))
	}
	return frozenGroup, nil
}
Beispiel #30
0
// ColumnsToProto converts a slice of model.ColumnInfo to a slice of tipb.ColumnInfo.
func ColumnsToProto(columns []*model.ColumnInfo, pkIsHandle bool) []*tipb.ColumnInfo {
	cols := make([]*tipb.ColumnInfo, 0, len(columns))
	for _, c := range columns {
		col := columnToProto(c)
		if pkIsHandle && mysql.HasPriKeyFlag(c.Flag) {
			col.PkHandle = proto.Bool(true)
		} else {
			col.PkHandle = proto.Bool(false)
		}
		cols = append(cols, col)
	}
	return cols
}