예제 #1
0
파일: qubot.go 프로젝트: sevein/qubot
// handleEvents takes each type of event to its corresponding callback.
// A full list of events can be found in the source code: https://goo.gl/ESCO4K.
func (q *Qubot) handleEvent(event *slack.RTMEvent) error {
	switch e := event.Data.(type) {
	case *slack.ConnectingEvent:
		logger.Debug("qubot", "Connection attempt", "count", e.Attempt)
	case *slack.ConnectedEvent:
		logger.Info("qubot", "Connected to Slack!")
		return q.onConnectedEvent(e)
	case *slack.HelloEvent:
		logger.Info("qubot", "Slack sent greetings!")
	case *slack.LatencyReport:
		logger.Debug("qubot", "Latency report", "duration", e.Value)
	case *slack.MessageEvent:
		logger.Debug("qubot", "Message received")
		return q.onMessageEvent(e)
	case *slack.InvalidAuthEvent:
		panic("Unrecoverable error: InvalidAuthEvent")
	case *slack.RTMError:
	case *slack.AckErrorEvent:
	case *slack.ConnectionErrorEvent:
	case *slack.DisconnectedEvent:
	case *slack.MessageTooLongEvent:
	case *slack.OutgoingErrorEvent:
	default:
		logger.Debug("qubot", "Unknown event received", "type", event.Type)
	}
	return nil
}
예제 #2
0
파일: Client.go 프로젝트: cokeboL/GoWorld
func sendCoroutine(client *Client) {
	for {
		if !client.running {
			return
		}

		select {
		case <-client.chStop:
			Logger.Info(LogConf.NetCoreClient, client.idx, "sendCoroutine exit.")
			return
		case buf := <-client.sendQ:
			if err := (*client.conn).SetWriteDeadline(time.Now().Add(NetConf.WRITE_BLOCK_TIME)); err != nil {
				client.Stop()
				Logger.Info(LogConf.NetCoreClient, client.idx, "SetWriteDeadline error: %v", err)
			}
			writeLen, err := client.conn.Write(buf)
			if err != nil || writeLen != len(buf) {
				client.Stop()
				Logger.Info(LogConf.NetCoreClient, client.idx, "Write error, len: %d error: %v", writeLen, buf)
			} else {
				//Logger.Info(LogConf.NetCoreClient, client.idx, "Write %v", buf)
			}

		}
	}
}
예제 #3
0
파일: Room.go 프로젝트: cokeboL/ZIM
func handleClientLeaveRoom(client *NetCore.Client, msg *NetCore.NetMsg) bool {
	client.RemoveCloseCB("leaveRoom")

	msg.Buf = ErrConf.GetEmptyRspBuffer(ErrConf.NO_ERR)
	client.SendMsg(msg)

	if room, ok := idRoomMap[client.Id]; ok {
		Logger.Info(LogConf.WorkerClientJob, client.Idx, "client leave room id: %d RoomId: %d", client.Id, room.Id)

		notify := &LeaveRoomNotify{
			Id: NetCore.ClientIDType(client.Id),
		}
		msg.Cmd = MsgConf.ClientLeaveRoomNotify
		if buf, err := json.Marshal(notify); err == nil {
			msg.Buf = buf
		} else {
			return false
		}

		delete(room.Guests, client.Id)

		if len(room.Guests) > 0 {
			for _, v := range room.Guests {
				v.SendMsg(msg)
			}
		} else {
			delete(rooms, room.Id)
		}
	}

	Logger.Info(LogConf.WorkerClientJob, client.Idx, "handleClientLeaveRoom client Idx: %d id: %d", client.Idx, client.Id)

	return true
}
예제 #4
0
func (handler *Handler) resolveTask(task *models.Task) {
	err := handler.bbs.ResolvingTask(task)
	if err != nil {
		logger.Info("handler.resolving-failed", map[string]interface{}{
			"task":  task.Guid,
			"error": err.Error(),
		})

		return
	}

	err = handler.natsClient.Publish(task.ReplyTo, task.ToJSON())
	if err != nil {
		logger.Error("handler.publish-failed", map[string]interface{}{
			"task":  task.Guid,
			"error": err.Error(),
		})

		return
	}

	err = handler.bbs.ResolveTask(task)
	if err != nil {
		logger.Error("handler.resolve-failed", map[string]interface{}{
			"task":  task.Guid,
			"error": err.Error(),
		})

		return
	}

	logger.Info("handler.resolved", map[string]interface{}{
		"task": task.Guid,
	})
}
예제 #5
0
파일: Client.go 프로젝트: cokeboL/ZIM
func readCoroutine(client *Client) {
	defer Commen.HandlePanic()

	head := make([]byte, PACK_HEAD_LEN)
	var readLen = 0
	var err error

	for {
		if !client.running {
			goto Exit
		}

		if err = (*client.conn).SetReadDeadline(time.Now().Add(NetConf.READ_BLOCK_TIME)); err != nil {
			//Logger.Info(LogConf.NetCoreClient, client.Idx, "SetReadDeadline error: %v", err)
			goto Exit
		}

		lastRead := time.Now().UTC()
		readLen, err = io.ReadFull(client.conn, head)
		if err != nil || readLen < PACK_HEAD_LEN {
			Logger.Info(LogConf.NetCoreClient, client.Idx, "Read head error: %v %v %v", err, lastRead, time.Now().UTC())
			goto Exit
		}

		if err = (*client.conn).SetReadDeadline(time.Now().Add(NetConf.READ_BLOCK_TIME)); err != nil {
			Logger.Info(LogConf.NetCoreClient, client.Idx, "SetReadDeadline error: %v", err)
			goto Exit
		}

		var msg = new(NetMsg)
		//var msg = &NetMsg{}

		msg.BufLen = binary.LittleEndian.Uint32(head[0:4])
		msg.Cmd = binary.LittleEndian.Uint32(head[4:8])
		//msg.action = binary.LittleEndian.Uint16(head[6:8])

		if msg.BufLen > 0 {
			msg.Buf = make([]byte, msg.BufLen)
			readLen, err := io.ReadFull(client.conn, msg.Buf)
			if err != nil || readLen != int(msg.BufLen) {
				Logger.Info(LogConf.NetCoreClient, client.Idx, "Read body error: %v", err)
				goto Exit
			}
		}
		//Logger.Info(LogConf.NetCoreClient, client.Idx, "msg read ---->>> : %d %d %v", msg.Cmd, msg.BufLen, msg.Buf)

		if ENABLE_MSG_COROUTINE {
			client.recvQ <- msg
		} else {
			client.HandleMsg(msg)
		}

	}

Exit:
	client.Stop()
	Logger.Info(LogConf.NetCoreClient, client.Idx, "%d readCoroutine exit.", client.Idx)
	return
}
예제 #6
0
파일: Client.go 프로젝트: ccppluagopy/Zebra
func (client *Client) CancelWaitRegist() {
	Logger.Info(LogConf.NetCoreClient, client.Idx, "CancelWaitRegist, client Idx: %d  111", client.Idx)
	key := fmt.Sprintf("WaitRegist_%d", client.Idx)
	if _, ok := clientValidTimerMap[key]; ok {
		delete(clientValidTimerMap, key)
	}
	Logger.Info(LogConf.NetCoreClient, client.Idx, "CancelWaitRegist, client Idx: %d  222", client.Idx)
}
예제 #7
0
func main() {
	// Metron is intended to be light-weight so we occupy only one core
	runtime.GOMAXPROCS(1)

	flag.Parse()
	config, err := config.ParseConfig(*configFilePath)
	if err != nil {
		panic(fmt.Errorf("Unable to parse config: %s", err))
	}

	logger := logger.NewLogger(*debug, *logFilePath, "metron", config.Syslog)

	statsStopChan := make(chan struct{})
	batcher, eventWriter := initializeMetrics(config, statsStopChan, logger)

	go func() {
		err := http.ListenAndServe(net.JoinHostPort("localhost", pprofPort), nil)
		if err != nil {
			logger.Errorf("Error starting pprof server: %s", err.Error())
		}
	}()

	logger.Info("Startup: Setting up the Metron agent")
	marshaller, err := initializeDopplerPool(config, batcher, logger)
	if err != nil {
		panic(fmt.Errorf("Could not initialize doppler connection pool: %s", err))
	}

	messageTagger := tagger.New(config.Deployment, config.Job, config.Index, marshaller)
	aggregator := messageaggregator.New(messageTagger, logger)
	eventWriter.SetWriter(aggregator)

	dropsondeUnmarshaller := eventunmarshaller.New(aggregator, batcher, logger)
	metronAddress := fmt.Sprintf("127.0.0.1:%d", config.IncomingUDPPort)
	dropsondeReader, err := networkreader.New(metronAddress, "dropsondeAgentListener", dropsondeUnmarshaller, logger)
	if err != nil {
		panic(fmt.Errorf("Failed to listen on %s: %s", metronAddress, err))
	}

	logger.Info("metron started")
	go dropsondeReader.Start()

	dumpChan := signalmanager.RegisterGoRoutineDumpSignalChannel()
	killChan := signalmanager.RegisterKillSignalChannel()

	for {
		select {
		case <-dumpChan:
			signalmanager.DumpGoRoutine()
		case <-killChan:
			logger.Info("Shutting down")
			close(statsStopChan)
			return
		}
	}
}
예제 #8
0
파일: Commen.go 프로젝트: cokeboL/ZIM
func handleHeartBeat(client *Client, msg *NetMsg) bool {
	if client.stype == NetConf.Client {
		Logger.Info(LogConf.NetCoreCommen, client.Idx, "handle Client HeartBeat client Idx: %d", client.Idx)
		client.SendMsg(msg)
	} else {
		Logger.Info(LogConf.NetCoreCommen, client.Idx, "handle Server HeartBeat client Idx: %d", client.Idx)
		msg.Cmd = MsgConf.HeartBeat2
		client.SendMsg(msg)
	}
	return true
}
예제 #9
0
파일: Client.go 프로젝트: cokeboL/GoWorld
func readCoroutine(client *Client) {
	head := make([]byte, PACK_HEAD_LEN)
	var readLen = 0
	var err error

	for {
		if !client.running {
			goto Exit
		}

		if err = (*client.conn).SetReadDeadline(time.Now().Add(NetConf.READ_BLOCK_TIME)); err != nil {
			Logger.Info(LogConf.NetCoreClient, client.idx, "SetReadDeadline error: %v", err)
			goto Exit
			return
		}

		readLen, err = io.ReadFull(client.conn, head)
		if err != nil || readLen < PACK_HEAD_LEN {
			Logger.Info(LogConf.NetCoreClient, client.idx, "Read head error: %v", err)
			goto Exit
			return
		}

		if err = (*client.conn).SetReadDeadline(time.Now().Add(NetConf.READ_BLOCK_TIME)); err != nil {
			Logger.Info(LogConf.NetCoreClient, client.idx, "SetReadDeadline error: %v", err)
			goto Exit
			return
		}

		//var msg = new(NetMsg)
		var msg = &NetMsg{}

		msg.BufLen = binary.LittleEndian.Uint32(head[0:4])
		msg.Cmd = binary.LittleEndian.Uint32(head[4:8])
		//msg.action = binary.LittleEndian.Uint16(head[6:8])

		if msg.BufLen > 0 {
			msg.Buf = make([]byte, msg.BufLen)
			readLen, err := io.ReadFull(client.conn, msg.Buf)
			if err != nil || readLen != int(msg.BufLen) {
				Logger.Info(LogConf.NetCoreClient, client.idx, "Read body error: %v", err)
				goto Exit
				return
			}
		}

		client.recvQ <- msg
	}

Exit:
	client.Stop()
	Logger.Info(LogConf.NetCoreClient, client.idx, "readCoroutine exit.")
	return
}
예제 #10
0
파일: Client.go 프로젝트: ccppluagopy/Zebra
func (client *Client) WaitRegist() {
	Logger.Info(LogConf.NetCoreClient, client.Idx, "WaitRegist, client Idx: %d  111", client.Idx)
	key := fmt.Sprintf("WaitRegist_%d", client.Idx)
	clientValidTimerMap[key] = clientValidTimer.NewTimer(key, int64((NetConf.WAIT_REGIST_TIME)*time.Second), func() {
		if _, ok := clientValidTimerMap[key]; ok {
			Logger.Info(LogConf.NetCoreClient, client.Idx, "WaitRegist TimeOut, client Idx: %d", client.Idx)
			client.Stop()
		}
	}, false)
	Logger.Info(LogConf.NetCoreClient, client.Idx, "WaitRegist, client Idx: %d  222", client.Idx)
}
예제 #11
0
func (handler *Handler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	var task *models.Task

	err := json.NewDecoder(request.Body).Decode(&task)
	if err != nil {
		logger.Error("handler.malformed-payload", map[string]interface{}{
			"error": err.Error(),
		})

		writer.WriteHeader(http.StatusBadRequest)

		return
	}

	sleepForARandomInterval("handler.hesitate", 0, 100, map[string]interface{}{
		"task": task.Guid,
	})

	ok := handler.reserveMemory(task.MemoryMB)
	if !ok {
		logger.Info("handler.full", map[string]interface{}{
			"task": task.Guid,
		})

		writer.WriteHeader(http.StatusServiceUnavailable)

		return
	}

	logger.Info("claiming.runonce", map[string]interface{}{
		"task": task.Guid,
	})

	err = handler.bbs.ClaimTask(task, executorID)
	if err != nil {
		handler.releaseMemory(task.MemoryMB)

		logger.Info("handler.claim-failed", map[string]interface{}{
			"task":  task.Guid,
			"error": err.Error(),
		})

		writer.WriteHeader(http.StatusConflict)

		return
	}

	go handler.runTask(task)

	writer.WriteHeader(http.StatusCreated)
}
예제 #12
0
파일: Room.go 프로젝트: cokeboL/ZIM
func handleClientRoomChat(client *NetCore.Client, msg *NetCore.NetMsg) bool {
	if room, ok := idRoomMap[client.Id]; ok {
		msg.Cmd = MsgConf.ClientRoomChatBroad
		for id, v := range room.Guests {
			v.SendMsg(msg)
			Logger.Info(LogConf.WorkerClientJob, client.Idx, "handleClientRoomChat send to client: %d", id)
		}
		return true
	}

	Logger.Info(LogConf.WorkerClientJob, client.Idx, "handleClientRoomChat err: not in room id: %d", client.Id)

	return true
}
예제 #13
0
파일: video_merge.go 프로젝트: szqh97/test
func (avl *av_list) process_in_moved_to(file string) error {
	var (
		f_a, f_v   string
		outf       string
		channel_id string
	)

	// check the file name is like ./1.1111111.1111111.a.mp4
	splitedfile := strings.Split(file, ".")
	if len(splitedfile) == 5 {
		channel_id = splitedfile[0]
	} else {
		logger.Warn("file %s is error", file)
	}

	if f, ok := (*avl)[channel_id]; ok {
		delete(*avl, channel_id)

		if string(splitedfile[3]) == "a" {
			f_a = file
			f_v = f
			outf = strings.Join(strings.Split(f, ".")[0:3], ".") + ".mp4"
		} else if string(splitedfile[3]) == "v" {
			f_v = file
			f_a = f
			outf = strings.Join(strings.Split(f, ".")[0:3], ".") + ".mp4"
		}
		logger.Info("f_v: " + f_v + ", f_a: " + f_a + ", outf: " + outf)

		time.Sleep(time.Duration(time.Second * 5))
		// merge video and audio
		cmd := exec.Command("ffmpeg", "-y", "-i", f_v, "-i", f_a, "-codec", "copy", outf)
		//cmd := exec.Command("ffmpeg", " -y -i ", f_v, "-i ", f_a, " -codec copy ", outf, " >/dev/null 2>&1 ")
		logger.Info("cmd's args is: ", cmd.Args)
		err := cmd.Run()
		if err != nil {
			logger.Fatal("ffmpeg merge video error:", err)
		} else {
			cmd = exec.Command("rm", "-f", f_v, " ", f_a)
			err = cmd.Run()
			if err != nil {
				logger.Warn("rm files error: %s", err)
			}
		}
	} else {
		(*avl)[channel_id] = file
	}
	return nil
}
예제 #14
0
파일: main.go 프로젝트: sevein/qubot
func main() {
	flag.Parse()

	v := appVersion()
	if version {
		fmt.Println(v)
		os.Exit(0)
	}
	logger.Info("main", v)

	cfg, err := loadConfig()
	if err != nil {
		logger.Error("main", "The configuration could not be loaded", "error", err, "path", conf)
		os.Exit(1)
	}

	// Start service
	q := qubot.Init(cfg)
	q.Handle(handlers.PingHandler, handlers.TauntHandler)
	err = q.Start()
	if err != nil {
		logger.Error("main", "Qubot could not be started", "error", err)
		q.Close()
		os.Exit(1)
	}

	// More advanced management on signals here: https://goo.gl/fuylKX
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan,
		syscall.SIGINT, // aka os.Interrupt
		syscall.SIGTERM,
		syscall.SIGUSR1)

SELECT:
	select {
	case sig := <-sigChan:
		switch sig {
		case syscall.SIGINT, syscall.SIGTERM:
			q.Close()
		case syscall.SIGUSR1:
			q.Report()
			goto SELECT
		}
	case <-q.Done():
		logger.Info("main", "Qubot stopped")
	}

	logger.Info("main", "¡Adiós!")
}
예제 #15
0
func handleStaging(bbs bbs.StagerBBS, natsClient yagnats.NATSClient) {
	var task uint64

	natsClient.SubscribeWithQueue("stage", "stager", func(msg *yagnats.Message) {
		var message stagingMessage

		err := json.Unmarshal(msg.Payload, &message)
		if err != nil {
			logger.Fatal("staging-request.invalid", map[string]interface{}{
				"error":   err.Error(),
				"payload": string(msg.Payload),
			})
			return
		}

		for i := 0; i < message.Count; i++ {
			guid := atomic.AddUint64(&task, 1)

			task := &models.Task{
				Guid:     fmt.Sprintf("task-%d", guid),
				MemoryMB: message.MemoryMB,

				ReplyTo: msg.ReplyTo,
			}

			logger.Info("staging-request.desire", map[string]interface{}{
				"task": task,
			})

			go bbs.DesireTask(task)
		}
	})
}
예제 #16
0
파일: Server.go 프로젝트: cokeboL/ZIM
func StartTcpServer(addr string, chStop chan int) {
	chAppStop = chStop

	go func() {
		tcpAddr, err := net.ResolveTCPAddr("tcp4", addr)
		listener, err := net.ListenTCP("tcp", tcpAddr)
		if err != nil {
			Logger.Error(LogConf.NetCoreServer, LogConf.SERVER, "Listening error: %v", err)
			os.Exit(-1)
		}
		defer listener.Close()

		serverRunning = true

		Logger.Info(LogConf.NetCoreServer, LogConf.SERVER, "NetCore Start OK...")

		for {
			if !serverRunning {
				break
			}
			conn, err := listener.AcceptTCP()
			if err != nil {
				Logger.Error(LogConf.NetCoreServer, LogConf.SERVER, "Error accept: %v", err)
			} else {
				newClient(conn)
			}
		}
		chAppStop <- ErrConf.TCP_SERVER_ERR
	}()
}
예제 #17
0
파일: compile.go 프로젝트: sspans/hooktftp
func CompileHook(hookDef iHookDef) (Hook, error) {
	var ok bool
	var components HookComponents

	if hookDef.GetRegexp() == "" {
		return nil, fmt.Errorf("Cannot find regexp from hook %v", hookDef)
	}

	if components, ok = hookMap[hookDef.GetType()]; !ok {
		return nil, fmt.Errorf("Cannot find template from hook %v", hookDef)
	}

	transform, err := regexptransform.NewRegexpTransform(
		hookDef.GetRegexp(),
		hookDef.GetTemplate(),
		components.escape,
	)
	if err != nil {
		return nil, err
	}

	return func(path string) (io.ReadCloser, error) {
		newPath, err := transform(path)
		if err != nil {
			return nil, err
		}

		logger.Info("Executing hook: %s %s -> %s", hookDef, path, newPath)
		reader, err := components.Execute(newPath)
		if err != nil {
			return nil, err
		}
		return reader, nil
	}, nil
}
예제 #18
0
파일: Agent.go 프로젝트: cokeboL/ZIM
func dial(addr string) (*net.TCPConn, error) {
	var conn *net.TCPConn
	var err error
	var count = 0
	var tcpAddr *net.TCPAddr
	if tcpAddr, err = net.ResolveTCPAddr("tcp4", addr); err != nil {
		return nil, err
	}

	for {
		count++
		if count > NetConf.MAX_DIAL_TIMES {
			return nil, err
		}

		conn, err = net.DialTCP("tcp", nil, tcpAddr)

		Logger.Info(LogConf.NetCoreAgent, LogConf.SERVER, "Agent dial time: %d addr %s %v", count, addr, conn)
		if err == nil {
			return conn, nil
		}

		time.Sleep(NetConf.DIAL_INTERNAL)
	}

	return nil, nil
}
예제 #19
0
파일: Agent.go 프로젝트: cokeboL/ZIM
func NewAgent(agent **Client, addr string, stype uint32, timerName string) int {
	agentClient := newAgentClient(addr)

	if agentClient == nil {
		return ErrConf.AGENT_ERR
	}

	*agent = agentClient

	//timerKey := timerName + fmt.Sprintf("%d", agentClient.Idx)
	if timerName != "" {
		timer := agentHeartbeatTmer.NewTimer(timerName+fmt.Sprintf("%d", agentClient.Idx), int64(NetConf.HEARTBEART_TIME), int64(NetConf.HEARTBEART_TIME), func() {
			Logger.Error(LogConf.NetCoreAgent, LogConf.SERVER, "Agent heart %v %v", lastHeart, time.Now().UTC())
			lastHeart = time.Now().UTC()
			agentClient.HeartBeat()
		}, true)

		agentClient.AddCloseCB("courierClose", func(client *Client) {
			Logger.Info(LogConf.NetCoreAgent, LogConf.SERVER, "Server close, server type: %d", stype)
			agentHeartbeatTmer.DeleteTimer(timer)
			go NewAgent(agent, addr, stype, timerName)
		})
	}

	go func() {
		time.Sleep(time.Second)
		agentClient.Regist(stype)
	}()

	return 0
}
예제 #20
0
func (handler *Handler) runTask(task *models.Task) {
	defer handler.releaseMemory(task.MemoryMB)

	logger.Info("task.claimed", map[string]interface{}{
		"task": task.Guid,
	})

	sleepForARandomInterval("task.create-container", 500, 1000, map[string]interface{}{
		"task": task.Guid,
	})

	logger.Info("task.start", map[string]interface{}{
		"task": task.Guid,
	})

	err := handler.bbs.StartTask(task, "container")
	if err != nil {
		logger.Error("task.start-failed", map[string]interface{}{
			"task":  task.Guid,
			"error": err.Error(),
		})

		return
	}

	sleepForARandomInterval("task.run", 5000, 5001, map[string]interface{}{
		"task": task.Guid,
	})

	logger.Info("task.completing", map[string]interface{}{
		"task": task.Guid,
	})

	err = handler.bbs.CompleteTask(task, false, "", "")
	if err != nil {
		logger.Error("task.complete-failed", map[string]interface{}{
			"task":  task.Guid,
			"error": err.Error(),
		})

		return
	}

	logger.Info("task.completed", map[string]interface{}{
		"task": task.Guid,
	})
}
예제 #21
0
파일: Client.go 프로젝트: cokeboL/ZIM
func sendCoroutine(client *Client) {
	defer Commen.HandlePanic()

	if ENABLE_MSG_COROUTINE {
		go msgCoroutine(client)
	} else {
		go readCoroutine(client)
	}

	var buf []byte
	for {
		if !client.running {
			return
		}

		//select {
		/*
			case <-client.chStop:
				Logger.Info(LogConf.NetCoreClient, client.Idx, "%d sendCoroutine exit.", client.Idx)
				return
		*/
		//case buf := <-client.sendQ:
		buf = <-client.sendQ
		if buf == nil {
			Logger.Info(LogConf.NetCoreClient, client.Idx, "%d sendCoroutine exit.", client.Idx)
			return
		}
		if err := (*client.conn).SetWriteDeadline(time.Now().Add(NetConf.WRITE_BLOCK_TIME)); err != nil {
			client.Stop()
			return
			//Logger.Info(LogConf.NetCoreClient, client.Idx, "SetWriteDeadline error: %v", err)
		}

		writeLen, err := client.conn.Write(buf)
		//Logger.Info(LogConf.NetCoreClient, client.Idx, "Write--->>, len: %d buf: %v", writeLen, buf)
		if err != nil || writeLen != len(buf) {
			client.Stop()
			return
			Logger.Info(LogConf.NetCoreClient, client.Idx, "Write error, len: %d error: %v", writeLen, buf)
		} else {
			//Logger.Info(LogConf.NetCoreClient, client.Idx, "Write %v", buf)
		}

		//}
	}
}
예제 #22
0
파일: Handlers.go 프로젝트: cokeboL/GoWorld
func handleRegist(client *NetCore.Client, msg *NetCore.NetMsg) {
	if client != courier {
		Logger.Warn(LogConf.WorkerServerJob, LogConf.SERVER, "handleRegist error, %v %v!", courier, client)
	}
	Logger.Info(LogConf.WorkerServerJob, LogConf.SERVER, "handleRegist OK, %v %v!", courier, client)

	NetCore.MarkServer(client, NetConf.Courier)
}
예제 #23
0
파일: handler.go 프로젝트: cokeboL/GoWorld
func ServersForEach(cb NetCore.ClientForEachCB) {
	Logger.Info(LogConf.CourierServerJob, LogConf.SERVER, "ServerForEach")

	mutex.Lock()
	for _, client := range serverMap {
		cb(client)
	}
	mutex.Unlock()
}
예제 #24
0
파일: Client.go 프로젝트: cokeboL/ZIM
func (client *Client) HeartBeat() {
	if client.IsRunning() {
		Logger.Info(LogConf.NetCoreClient, client.Idx, "HeartBeat %d HeartBeat---------", client.Idx)
		buf := make([]byte, PACK_HEAD_LEN)
		binary.LittleEndian.PutUint32(buf, 0)
		binary.LittleEndian.PutUint32(buf[4:8], MsgConf.HeartBeat)
		client.sendQ <- buf
	}
}
예제 #25
0
파일: video_merge.go 프로젝트: szqh97/test
func main() {
	install_logger()
	pid_file := "./var/run/video_merge.pid"
	pid_locker, err := pidlock.Lock_write_pid_file(pid_file)
	logger.Info("starting ...")
	//monitorpath := "/home/li_yun/Projects/test/go"
	monitorpath, err := getMonitorPath()
	if err != nil {
		logger.Fatal("get monitor path error: %s", err)
		os.Exit(1)
	}
	log.Println(monitorpath)
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		logger.Fatal("newWatcher error: %s", err)
	}

	done := make(chan bool)
	// Process events
	go func() {
		avfile_list := make(av_list)
		for {
			select {
			case ev := <-watcher.Event:
				(&avfile_list).process_in_moved_to(ev.Name)
			case err := <-watcher.Error:
				logger.Warn("errror: %s", err)
			}
		}
	}()

	// only monitor FSN_RENAME event
	err = watcher.WatchFlags(monitorpath, fsnotify.FSN_MOVEDTO)
	if err != nil {
		logger.Fatal("add watch flags error: %s", err)
	}

	<-done
	/* ... do stuff ... */
	watcher.Close()
	pid_locker.Close()
	logger.Info("done ...")

}
예제 #26
0
func sleepForARandomInterval(reason string, minSleepTime, maxSleepTime int, data map[string]interface{}) {
	interval := rand.Intn(maxSleepTime-minSleepTime) + minSleepTime
	duration := time.Duration(interval) * time.Millisecond

	data["duration"] = fmt.Sprintf("%s", duration)

	logger.Info(reason, data)

	time.Sleep(duration)
}
예제 #27
0
파일: Client.go 프로젝트: cokeboL/ZIM
func (client *Client) Clear() {

	//client.CancelWaitRegist()

	for _, cb := range client.cbMap {
		cb(client)
	}
	client.ClearAllCloseCB()
	Logger.Info(LogConf.NetCoreClient, client.Idx, "client %d clear", client.Idx)
}
예제 #28
0
파일: handler.go 프로젝트: cokeboL/GoWorld
func handleRegist(client *NetCore.Client, msg *NetCore.NetMsg) {
	stype := binary.LittleEndian.Uint32(msg.Buf)
	NetCore.MarkServer(client, stype)
	addServerToMap(client)
	client.AddCloseCB("removeServer", removeServerFromMap)

	Logger.Info(LogConf.CourierServerJob, LogConf.SERVER, "Server Regist client idx: %d buf len: %d %d", client.GetIdx(), len(msg.Buf), stype)

	binary.LittleEndian.PutUint32(msg.Buf[0:4], NetConf.Courier)
	client.SendMsg(msg)
}
예제 #29
0
파일: TimerWheel.go 프로젝트: cokeboL/ZIM
func (timerWheel *TimerWheel) DeleteTimerByKey(key *string) {
	for _, wheel := range timerWheel.wheels {
		for _, timer := range wheel {
			if *key == timer.key {
				delete(wheel, *key)
				return
			}
		}
	}
	Logger.Info(LogConf.TimerWheel, LogConf.SERVER, "Couldn't find timer by name: %s", *key)
}
예제 #30
0
파일: MysqlMgr.go 프로젝트: cokeboL/GoWorld
func (msqlMgr *MysqlMgr) start(addr string) {
	var err error
	if msqlMgr.db, err = sql.Open("mysql", "user:password@/dbname"); err != nil {
		Logger.Error(LogConf.DBMgrMysql, LogConf.SERVER, "MysqlMgr %d Open Error: %v", msqlMgr.idx, err)
		msqlMgr.restart(addr)
		return
	}

	msqlMgr.restarting = false

	Logger.Info(LogConf.DBMgrMysql, LogConf.SERVER, "MysqlMgr %d Open Success!", msqlMgr.idx)
}