Beispiel #1
0
func receieve(socketrep *zmq.Socket, s Server) {
	var d database
	d.Map = make(map[int]*mydetails)
	go d.statemachinecommit(s)
	for {
		fmt.Println("tcp://127.0.0.1:7001")
		msg, err := socketrep.RecvBytes(0)

		fmt.Println("recived")
		if err != nil {
			fmt.Println(err)
		}
		var req request
		json.Unmarshal(msg, &req)
		fmt.Println("parsing----------------------------------------------------------------------------------------")
		fmt.Println(s.leaderid)
		fmt.Println("parsing")
		fmt.Println(req)
		resp := d.parse(req, s)
		fmt.Println(resp)
		message, _ := json.Marshal(resp)
		socketrep.SendBytes(message, 0)

	}

}
func StartZeromqProtoRepServer(port string) {
	var socket *zmq.Socket
	var err error

	if socket, err = zmq.NewSocket(zmq.REP); err != nil {
		log.Fatal(err)
	}

	if err = socket.Bind("tcp://0.0.0.0:" + port); err != nil {
		log.Fatal(err)
	}

	for {
		request, _ := socket.RecvBytes(0)

		var body pb.Request

		proto.Unmarshal(request, &body)

		response, _ := proto.Marshal(&pb.Response{
			Method:        body.Method,
			PayloadLength: int64(len(body.Payload)),
		})

		socket.SendBytes(response, 0)
	}
}
Beispiel #3
0
func send(requester *zmq.Socket, req *proto.Request) {
	data, err := protobuf.Marshal(req)
	panicOnErr(err)
	requester.SendBytes(data, 0)

	reply, err := requester.RecvBytes(0)
	panicOnErr(err)
	response := new(proto.Response)
	err = protobuf.Unmarshal(reply, response)
	panicOnErr(err)
	fmt.Println("Received ", response.String())
}
Beispiel #4
0
func (s Servernode) RecieveMessage(responder *zmq.Socket) {
	for {
		msgbytes, err := responder.RecvBytes(0)

		var data Envelope
		if err != nil {
			panic(err)
		}
		err1 := json.Unmarshal(msgbytes, &data)
		if err1 != nil {
			panic("panic in Unmarshling the data")
		}
		s.inbox <- &data
	}
}
Beispiel #5
0
// process project
func processProjectQueueHandler(receiver *zmq.Socket) {

	for {
		time.Sleep(time.Second * 1)

		msgbytes, err := receiver.RecvBytes(0) // blocked receiving

		if err != nil {
			glog.Error("Error receiving from zmq :", err)
			continue
		}
		var project common.Project
		err = json.Unmarshal(msgbytes, &project)
		if err != nil {
			glog.Error("Failed to unmarshal ", err)
			continue
		}

		var user common.SignupUser

		err = mgoSignupUsersCollection.FindId(project.UserId).One(&user)
		if err != nil {

			glog.Error("error obtaining user  information :", err, " userid= ", project.UserId.Hex()) // most likely not found
			continue
		} else {

			remainingSpace := user.Quota - user.UsedSpace
			if remainingSpace > 0 {

				go processAproject(&project, remainingSpace)
			} else {

				updateProjectMessageAndStatus(&project, "You have no space left for the project.", "error")
			}
		}

	}

}
Beispiel #6
0
//send reset email to  users
func SendResetEmailQueueHandler(receiver *zmq.Socket) {
	var err error

	sg := sendgrid.NewSendGridClient(ConfigSections.BackendWorker.SendGridUser, ConfigSections.BackendWorker.SendGridPassword)

	for { // loop forever;

		time.Sleep(time.Second * 1)
		select {

		default:
			msgbytes, _ := receiver.RecvBytes(0)

			var data map[string]interface{} = make(map[string]interface{})

			//err = json.Unmarshal(msgbytes, &signupUser)
			err = json.Unmarshal(msgbytes, &data)
			if err != nil {
				glog.Error("Failed to unmarshal ", err)
				continue
			}

			var resetString string
			var userIdHex string
			var email string
			userIdHex = data["id"].(string)
			resetString = data["reset_string"].(string)
			email = data["email"].(string)

			message := sendgrid.NewMail()
			message.AddTo(email)
			message.SetSubject("Password reset")

			var resetUrl string
			var urlPort string

			urlPort = ""

			resetUrl = fmt.Sprintf("https://%s%s/view/edit-profile?user_id=%s&reset_string=%s",
				ConfigSections.Common.BaseUrl,
				urlPort,
				userIdHex,
				resetString)

			text := `
		    
Welcome to Code/Grep,

Please click on the link below to reset your password:

` + resetUrl +
				`


Thank you,

Code/Grep - Code Browsing Made Easy


		    `

			message.SetText(text)

			message.SetFrom("Code/Grep <*****@*****.**>")

			if err = sg.Send(message); err == nil {

			} else {
				glog.Error("Error sending confirmation email : ", err)
			}

		}
		runtime.Gosched() // avoid hogging cpu
	}
}
Beispiel #7
0
func (w *worker) socketLoop(s *zmq.Socket, send <-chan Data, recv chan<- Data, state zmq.State) {
	if recv != nil {
		defer close(recv)
	}

	var (
		sendBuf     Data
		sendPending bool
		recvBuf     Data
		recvPending bool
	)

	for {
		var (
			err error

			sendActive <-chan Data
			recvActive chan<- Data
		)

		if !sendPending {
			sendActive = send
		}

		if recvPending {
			recvActive = recv
		}

		select {
		case <-w.notifier:
			const fullState = zmq.POLLIN | zmq.POLLOUT

			if state&fullState != fullState {
				if state, err = s.GetEvents(); err != nil {
					handleGeneralError(err)
					return
				}
			}

		case <-w.closer:
			return

		case sendBuf, sendPending = <-sendActive:
			if !sendPending {
				send = nil
			}

		case recvActive <- recvBuf:
			recvPending = false
			recvBuf.Bytes = nil
		}

		for {
			loop := false

			if sendPending && state&zmq.POLLOUT != 0 {
				flags := zmq.DONTWAIT

				if sendBuf.More {
					flags |= zmq.SNDMORE
				}

				if _, err = s.SendBytes(sendBuf.Bytes, flags); err == nil {
					sendPending = false
					sendBuf.Bytes = nil
					loop = true
				} else if !handleIOError(err) {
					return
				}

				if state, err = s.GetEvents(); err != nil {
					handleGeneralError(err)
					return
				}
			}

			if !recvPending && state&zmq.POLLIN != 0 {
				if data, err := s.RecvBytes(zmq.DONTWAIT); err == nil {
					if more, err := s.GetRcvmore(); err == nil {
						recvBuf.Bytes = data
						recvBuf.More = more
						recvPending = true
						loop = true
					} else {
						handleGeneralError(err)
						return
					}
				} else if !handleIOError(err) {
					return
				}

				if state, err = s.GetEvents(); err != nil {
					handleGeneralError(err)
					return
				}
			}

			if !loop {
				break
			}
		}
	}
}
/******************************************************************************
* 概述:    接收处理推送信息
* 函数名:    dealSub
* 返回值:
* 参数列表:  参数名          参数类型      取值范围     描述
*
*******************************************************************************/
func (this *ZmqSocket) dealSub(soc *zmq4.Socket, msgHeadFlag *bool) error {
	//	log4.Debug("start deal sub0...")
	//	this.mchooseMutex.RLocker()
	if !this.mChoose {
		//	this.mchooseMutex.RUnlock()
		return nil
	}
	log4.Debug("start deal sub...")
	//	this.mchooseMutex.RUnlock()
	for {
		if *msgHeadFlag {
			topic, err := soc.Recv(zmq4.DONTWAIT)
			if err != nil {
				errno1 := zmq4.AsErrno(err)
				switch errno1 {
				case zmq4.Errno(syscall.EAGAIN):
					return nil
				case zmq4.Errno(syscall.EINTR):
					continue
				default:
					log4.Debug("zmq req Get err %v, %d!", errno1, errno1)
				}
			}
			if len(topic) == 0 {
				//				log4.Debug("sub return1")
				return nil
			}
			//			log4.Debug("recv sub head =", topic)
			*msgHeadFlag = false
		} else {
			stream, err2 := soc.RecvBytes(zmq4.DONTWAIT)
			if err2 != nil {
				errno1 := zmq4.AsErrno(err2)
				switch errno1 {
				case zmq4.Errno(syscall.EAGAIN):
					return nil
				case zmq4.Errno(syscall.EINTR):
					continue
				default:
					log4.Debug("zmq req Get err %v, %d!", errno1, errno1)
				}
			}
			if len(stream) == 0 {
				//				log4.Debug("sub return2")
				return nil
			}
			*msgHeadFlag = true

			frm, err3 := common.UnwrapBaseProto(stream)
			if err3 != nil {
				log4.Error("UnwrapBaseProto falied, %s", err3.Error())
				return err3
			}

			mid := common.UnOffset(*frm.GetBody().Mid, 4)
			if mid[4-1] == 200 {
				log4.Error("sdssdk zmqsub get mid == 200 err")
				continue
			}
			res, err4 := common.UnwrapResponse(frm.GetBody().Mdata)
			if err4 != nil {
				log4.Error("sdssdk sub UnwrapResponse error:", err4)
				continue
			}
			this.mzmq.MdataCache.UpdatePoints(res)
		}
	}
	return nil
}
func pointToPointListener(socket *zmq.Socket, getResponse func(hash []byte) []byte) {
	for {
		req, _ := socket.RecvBytes(0)
		socket.SendBytes(getResponse(req), 0)
	}
}
Beispiel #10
0
func main() {
	flag.Parse(nil)

	address_list := flag.Args
	if len(address_list) == 0 {
		fmt.Println("No Addresses submitted")
		fmt.Println(flag.Help())
		return
	}

	var send, recv bool
	skip := false

	var socket *zmq.Socket
	switch *socket_type {
	case "PUSH":
		socket, _ = zmq.NewSocket(zmq.PUSH)
		send = true
	case "PULL":
		socket, _ = zmq.NewSocket(zmq.PULL)
		recv = true
	case "PUB":
		socket, _ = zmq.NewSocket(zmq.PUB)
		send = true
	case "SUB":
		socket, _ = zmq.NewSocket(zmq.SUB)
		recv = true
		if len(*subscriptions) == 0 {
			socket.SetSubscribe("")
		}
		for _, subscription := range *subscriptions {
			socket.SetSubscribe(subscription)
		}
	case "REQ":
		socket, _ = zmq.NewSocket(zmq.REQ)
		send = true
		recv = true
	case "REP":
		socket, _ = zmq.NewSocket(zmq.REP)
		send = true
		recv = true
		skip = true
	}
	defer socket.Close()

	// connect or bind
	if *mode {
		for _, address := range address_list {
			socket.Connect(address)
		}
	} else {
		for _, address := range address_list {
			socket.Bind(address)
		}
	}

	delim := byte('\n')
	if *null {
		fmt.Println("Setting delim to null")
		delim = byte(0x00)
	}

	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)

	for i := 0; i < *number || *number == -1; i++ {
		if send && !skip {
			line, _ := reader.ReadBytes(delim)
			socket.SendBytes([]byte(line), 0)
		}
		if recv {
			data, _ := socket.RecvBytes(0)
			writer.Write(data)
			writer.Flush()
		}
		if skip {
			skip = false
		}
	}

	fmt.Println("finished", *number)
}