Beispiel #1
0
func send(c chan string, socket *zmq.Socket) {
	for {
		msg := <-c
		socket.Send([]byte(msg), 0)
		fmt.Println("Pushed msg: ", msg)
	}
}
Beispiel #2
0
// SendResponse sends a message back to return identites of the received message.
func (receipt *MsgReceipt) SendResponse(socket *zmq.Socket, msg ComposedMsg) {
	socket.SendMultipart(receipt.Identities, zmq.SNDMORE)
	socket.Send([]byte("<IDS|MSG>"), zmq.SNDMORE)
	socket.SendMultipart(msg.ToWireMsg(receipt.Sockets.Key), 0)
	logger.Println("<--", msg.Header.Msg_type)
	logger.Printf("%+v\n", msg.Content)
}
Beispiel #3
0
func send_and_recieve(socket zmq.Socket, in_msg []byte, id string) (res []byte, err error) {
	//		println("in_msg: ", string (in_msg))
	//	println("send ", id)
	var repeat bool
	var r0 []byte
	var err0 error

	repeat = true

	for repeat {

		socket.Send(in_msg, 0)
		//		println("ok")
		r0, err0 = socket.Recv(0)

		if r0 != nil && len(r0) == 3 {
			// это указание повторить запрос еще раз
			repeat = true
			time.Sleep(1e6)
		} else {
			repeat = false
		}
	}
	//	println("recv ", id)
	//			println("out_msg: ", string (r0))
	return r0, err0
}
Beispiel #4
0
// send a message to the zmq REQ socket
func sendMessage(reqsocket zmq.Socket, m Message) {
	var address = PUB_KEY + "." + m.Nick
	b, _ := json.Marshal(m)
	var content = b
	env := envelope{address, string(content)}
	e, _ := json.Marshal(env)
	reqsocket.Send([]byte(e), 0)
	// wait for a reply
	reqsocket.Recv(0)
}
Beispiel #5
0
// The main announcer loop. Receives incoming messages, spits them back out to
// any connected subscribers.
func announcerLoop(listener *gozmq.Socket, sender *gozmq.Socket) {

	for {
		// This blocks until something comes down the pipe.
		msg, listenRecvError := listener.Recv(0)
		if listenRecvError != nil {
			errorHandler("listenRecvError", listenRecvError.Error())
		}

		sender.Send(msg, 0)
	}
}
Beispiel #6
0
// SendResponse sends a message back to return identites of the received message.
func (receipt *MsgReceipt) SendResponse(socket *zmq.Socket, msg ComposedMsg) {

	socket.SendMultipart(receipt.Identities, zmq.SNDMORE)
	socket.Send([]byte("<IDS|MSG>"), zmq.SNDMORE)

	msgParts, err := msg.ToWireMsg(receipt.Sockets.Key)
	if err != nil {
		log.Fatalln(err)
	}
	socket.SendMultipart(msgParts, 0)
	logger.Println("<--", msg.Header.MsgType)
	logger.Printf("%+v\n", msg.Content)
}
/* handling Read/Push/Delete tasks diversion based on task-type */
func goShareZmqRep(socket *zmq.Socket) {
	var err_response string
	for {
		msg, _ := socket.Recv(0)
		message_array := strings.Fields(string(msg))
		response_bytes, axn_status := DBTasks(message_array)

		if axn_status {
			socket.Send([]byte(response_bytes), 0)
		} else {
			err_response = fmt.Sprintf("Error for request sent: %s", msg)
			socket.Send([]byte(err_response), 0)
		}
	}
}
Beispiel #8
0
func zmqSender(s *zmq.Socket, c chan []map[string]interface{}, wg *sync.WaitGroup) {
	defer wg.Done()

	for {
		fmt.Println("waiting channel")
		buf := <-c
		data, err := json.Marshal(buf)
		if err != nil {
			log.Println("json.Marshal():", err)
			continue
		}

		fmt.Println("Send String: " + string(data))
		s.Send(data, zmq.NOBLOCK)
	}
}
Beispiel #9
0
func watchSub(global_sub_socket, global_pub_socket, local_pub_socket zmq.Socket, filename string) {
	for {
		data, _ := global_sub_socket.Recv(0)
		var msg Config
		_ = json.Unmarshal(data, &msg)
		local_config := readConfig(filename)
		if msg.Time > local_config.Time {
			body := []byte(msg.Body)
			writeConfig(filename, body)
			local_pub_socket.Send(body, 0)
		} else if msg.Time < local_config.Time {
			m, _ := json.Marshal(local_config)
			global_pub_socket.Send(m, 0)
		}
		runtime.Gosched()
	}
}
Beispiel #10
0
func (t *TransportZmq) bridge(bridge_in *zmq.Socket) {
	var message interface{}

	// Wait on channel, passing into socket
	// This keeps the socket in a single thread, otherwise we have to lock the entire publisher
	runtime.LockOSThread()

BridgeLoop:
	for {
		select {
		case notify := <-t.bridge_chan:
			bridge_in.Send(notify, 0)

			// Shutdown?
			if string(notify) == zmq_signal_shutdown {
				break BridgeLoop
			}
		case message = <-t.recv_bridge_chan:
		case func() chan<- interface{} {
			if message != nil {
				return t.recv_chan
			}
			return nil
		}() <- message:
			// The reason we flush recv through the bridge and not directly to recv_chan is so that if
			// the poller was quick and had to cache a receive as the channel was full, it will stop
			// polling - flushing through bridge allows us to signal poller to start polling again
			// It is not the publisher's responsibility to do this, and TLS wouldn't need it
			bridge_in.Send([]byte(zmq_signal_input), 0)
			message = nil
		}
	}

	// We should linger by default to ensure shutdown is transmitted
	bridge_in.Close()
	runtime.UnlockOSThread()
	t.wait.Done()
}
Beispiel #11
0
func watchRep(ctx zmq.Context, global_rep_socket, global_sub_socket zmq.Socket, clients *[]string, pub_address string) {
	for {
		data, _ := global_rep_socket.Recv(0)
		var req Request
		_ = json.Unmarshal(data, &req)
		if req.Type == "connect" {
			var creq ConnRequest
			json.Unmarshal(data, &creq)
			if !strSliceContains(*clients, creq.RepAddress) {
				global_sub_socket.Connect(creq.PubAddress)
				reply, _ := json.Marshal(ConnReply{pub_address, *clients})
				global_rep_socket.Send(reply, 0)
				for _, adr := range *clients {
					req_socket := openSocket(ctx, zmq.REQ, adr)
					req_socket.Send(data, 0)
					req_socket.Close()
				}
				*clients = append(*clients, creq.RepAddress)
				log.Printf("Connected: " + creq.RepAddress)
			}
		}
		runtime.Gosched()
	}
}
Beispiel #12
0
// WritePb sends any protobuf along a ZMQ socket. This makes sure to bundle our
// type identifier at the beginning of the message.
func WritePb(sock *zmq.Socket, remote []byte, pb interface{}) error {
	// TODO(mark): What happens if two goroutines end up in here at the same
	// time? Will ZMQ get angry; interleaved messages?
	var ptype byte = 0
	switch pb.(type) {
	case *Command:
		ptype = 1
	case *StillAlive:
		ptype = 2
	case *CommandFinished:
		ptype = 3
	case *CommandOutput:
		ptype = 4
	}
	if ptype == 0 {
		return errors.New(fmt.Sprintf("attempted to send unknown object: %v", pb))
	}

	buf, err := proto.Marshal(pb.(proto.Message))
	if err != nil {
		return err
	}

	// TODO: This probably copies the entire message again. It's totally a
	// premature optimization to fix that now... maybe later.
	tbuf := make([]byte, len(buf)+1)
	tbuf[0] = ptype
	copy(tbuf[1:], buf)

	if remote != nil {
		err = sock.Send(remote, zmq.SNDMORE)
		if err != nil {
			return err
		}

		err = sock.Send(make([]byte, 0), zmq.SNDMORE)
		if err != nil {
			return err
		}
	}

	err = sock.Send(tbuf, 0)
	if err != nil {
		return err
	}
	return nil
}
// Create and send our ZMQ response
func send_response(service_response *brubeckServiceResponse, socket zmq.Socket, passphrase string) {
	// build our ZMQ message string from the response
	service_response.end_timestamp = time.Now().Unix()
	if len(service_response.method) == 0 {
		service_response.method = "response"
	}
	header := fmt.Sprintf("%s %d:%s %d:%d %d:%d %d:%d %d:%s %d:%s %d:%s %d:%s %d:%s %d:%s",
		service_response.sender,
		len(service_response.conn_id), service_response.conn_id,
		len(strconv.FormatInt(service_response.request_timestamp, 10)), service_response.request_timestamp,
		len(strconv.FormatInt(service_response.start_timestamp, 10)), service_response.start_timestamp,
		len(strconv.FormatInt(service_response.end_timestamp, 10)), service_response.end_timestamp,
		len(passphrase), passphrase,
		len(service_response.origin_sender_id), service_response.origin_sender_id,
		len(service_response.origin_conn_id), service_response.origin_conn_id,
		len(service_response.origin_out_addr), service_response.origin_out_addr,
		len(service_response.path), service_response.path,
		len(service_response.method), service_response.method,
	)
	arguments, _ := json.Marshal(service_response.arguments)
	headers, _ := json.Marshal(service_response.headers)
	msg := fmt.Sprintf("%s %d:%d%d:%s%d:%s%d:%s%d:%s",
		header,
		len(strconv.Itoa(service_response.status_code)), service_response.status_code,
		len(service_response.status_message), service_response.status_message,
		len(string(arguments)), string(arguments),
		len(string(headers)), string(headers),
		len(service_response.body), service_response.body,
	)
	// send our message
	println(msg)
	socket.Send([]byte(service_response.sender), zmq.SNDMORE)
	socket.Send(nil, zmq.SNDMORE)
	socket.Send([]byte(msg), 0)

	// We are done, nothing to report
	return
}
Beispiel #14
0
// the listen and server for mongrel, expects an address like this
// @addr = string config parameter like this:
//    m2go.ListenAndServe("tcp://127.0.0.1:9555|tcp://127.0.0.1:9556|54c6755b-9628-40a4-9a2d-cc82a816345e", handler)
func ListenAndServe(addr string, handler http.Handler) {
	var Context zmq.Context
	var SocketIn zmq.Socket
	var SocketOut zmq.Socket
	var hasExited bool
	var err error

	m2addr := strings.Split(addr, "|") //

	log.Printf("m2go serving  %s\n", addr)

	/*
	  Connection to ZMQ setup
	*/
	connect := func() {
		if Context, err = zmq.NewContext(); err != nil {
			panic("No ZMQ Context?")
		}

		// listen for incoming requests
		if SocketIn, err = Context.NewSocket(zmq.PULL); err != nil {
			panic("No ZMQ Socket?")
		}
		SocketIn.Connect(m2addr[0])

		if SocketOut, err = Context.NewSocket(zmq.PUB); err != nil {
			panic("No ZMQ Socket Outbound??")
		}
		// outbound response on a different channel
		SocketOut.SetSockOptString(zmq.IDENTITY, m2addr[2])
		//socket.SetSockOptString(zmq.SUBSCRIBE, filter)
		SocketOut.Connect(m2addr[1])
	}

	connect()

	handleResponse := func(response []byte) {
		SocketOut.Send(response, 0)
	}
	stopper := func() {
		if !hasExited {
			hasExited = true
			SocketOut.Close()
			SocketIn.Close()
			Context.Close()
		}
	}
	defer stopper()

	for {
		// each inbound request
		m2data, err := SocketIn.Recv(0)
		//log.Println(string(m2data))
		if err != nil {
			log.Println("ZMQ Socket Input accept error ", err.Error())
		} else {
			go HandleM2Request(m2data, handleResponse, handler)
		}
	}
	log.Print("after close of runner")
}
Beispiel #15
0
func publishConfig(config Config, global_pub_socket, local_pub_socket zmq.Socket) {
	m, _ := json.Marshal(config)
	global_pub_socket.Send(m, 0)
	local_pub_socket.Send([]byte(config.Body), 0)
}