Example #1
0
func handleStatistic(ws *websocket.Conn) {
	for k, v := range ws.Config().Header {
		log.Debug.Println(k, " - ", v)
	}

	ws.Write([]byte("Hi"))
}
Example #2
0
func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	err = scanLogs(ws)
	if err != nil {
		return
	}
}
Example #3
0
File: apps.go Project: jbuck/rack
func AppLogs(ws *websocket.Conn) error {
	defer ws.Close()

	app := mux.Vars(ws.Request())["app"]

	a, err := models.GetApp(app)

	if awsError(err) == "ValidationError" {
		return fmt.Errorf("no such app: %s", app)
	}

	if err != nil {
		return err
	}

	logs := make(chan []byte)
	done := make(chan bool)

	a.SubscribeLogs(logs, done)

	for data := range logs {
		ws.Write(data)
	}

	return nil
}
func handleTrafficWS(conn *websocket.Conn) {
	trafficMutex.Lock()
	for _, traf := range traffic {
		if !traf.Position_valid { // Don't send unless a valid position exists.
			continue
		}
		trafficJSON, _ := json.Marshal(&traf)
		conn.Write(trafficJSON)
	}
	trafficMutex.Unlock()
	// Subscribe the socket to receive updates.
	trafficUpdate.AddSocket(conn)

	// Connection closes when function returns. Since uibroadcast is writing and we don't need to read anything (for now), just keep it busy.
	for {
		buf := make([]byte, 1024)
		_, err := conn.Read(buf)
		if err != nil {
			break
		}
		if buf[0] != 0 { // Dummy.
			continue
		}
		time.Sleep(1 * time.Second)
	}
}
Example #5
0
func socketHandler(ws *websocket.Conn) {
	for {
		receivedStream := make([]byte, 256)
		byteCount, err := ws.Read(receivedStream)

		if err != nil {
			return
		}

		if byteCount > 0 {
			inputHeaders := make(map[string]string)

			decode_err := json.Unmarshal(receivedStream[:byteCount], &inputHeaders)

			if decode_err != nil {
				return
			}
			out := runPlugins("secred_key", "endpoint_XXX", "consumer_XXX")

			jsonOut, encode_err := json.Marshal(out.Headers)
			if encode_err != nil {
				return
			}

			ws.Write(jsonOut)
		}
	}
}
Example #6
0
// sendMetrics sends the current state of tasks to the F12 API
func SendMetrics(ws *websocket.Conn, userID string, tasks map[string]demand.Task) error {
	var err error = nil
	var index int = 0

	metrics := metrics{
		Tasks:     make([]taskMetrics, len(tasks)),
		CreatedAt: time.Now().Unix(),
	}

	for name, task := range tasks {
		metrics.Tasks[index] = taskMetrics{App: name, RunningCount: task.Running, PendingCount: task.Requested}
		index++
	}

	payload := metricsPayload{
		User:    userID,
		Metrics: metrics,
	}

	b, err := json.Marshal(payload)
	if err != nil {
		return fmt.Errorf("Failed to encode API json. %v", err)
	}

	_, err = ws.Write(b)
	if err != nil {
		return fmt.Errorf("Failed to send metrics: %v", err)
	}

	return err
}
func handleStatusWS(conn *websocket.Conn) {
	//	log.Printf("Web client connected.\n")

	timer := time.NewTicker(1 * time.Second)
	for {
		// The below is not used, but should be if something needs to be streamed from the web client ever in the future.
		/*		var msg SettingMessage
				err := websocket.JSON.Receive(conn, &msg)
				if err == io.EOF {
					break
				} else if err != nil {
					log.Printf("handleStatusWS: %s\n", err.Error())
				} else {
					// Use 'msg'.
				}
		*/

		// Send status.
		<-timer.C
		update, _ := json.Marshal(&globalStatus)
		_, err := conn.Write(update)

		if err != nil {
			//			log.Printf("Web client disconnected.\n")
			break
		}
	}
}
Example #8
0
func configureCertificate(ws *websocket.Conn, httpsCertFileContent string, httpsKeyFileContent string) (bool, error) {
	if len(httpsCertFileContent) > 0 {
		httpsCertFilePath := beego.AppConfig.String("HTTPSCertFile")
		err := ioutil.WriteFile(httpsCertFilePath, []byte(httpsCertFileContent), 0644)
		if err != nil {
			return false, err
		}
		ws.Write([]byte("The GUI certificate is replaced\n"))
	}

	if len(httpsKeyFileContent) > 0 {
		httpsKeyFilePath := beego.AppConfig.String("HTTPSKeyFile")
		err := ioutil.WriteFile(httpsKeyFilePath, []byte(httpsKeyFileContent), 0644)
		if err != nil {
			return false, err
		}
		ws.Write([]byte("The GUI key is replaced\n"))
	}

	if len(httpsCertFileContent) > 0 || len(httpsKeyFileContent) > 0 {
		return true, nil
	} else {
		return false, nil
	}
}
func Handlews2(ws *websocket.Conn) {
	var stats types.Stats
	m := NewMonMan()
	var c []Containers
	var oc []Containers

	cli, err := client.NewEnvClient()
	if err != nil {
		fmt.Println(err)
	}
	for {
		fmt.Println("Elements copied: ", copy(oc, c))
		m.GetContainer()
		for n, cont := range m.ID {
			r, _ := cli.ContainerStats(context.Background(), cont, false)
			b, _ := ioutil.ReadAll(r.Body)
			json.Unmarshal(b, &stats)
			tmp := Containers{calculateCPUPercent(stats.PreCPUStats, stats.CPUStats), stats.MemoryStats.Usage, m.User[n], 0}
			c = append(c, tmp)
		}
		fc := UpdateList(oc, c)
		fmt.Println("New List: ", c)
		fmt.Println("Old List: ", oc)
		fmt.Println("Final List: ", fc)
		b, _ := json.Marshal(fc)
		ws.Write(b)
		time.Sleep(1000 * time.Millisecond)
	}
}
Example #10
0
func wsServer(ws *websocket.Conn) {
	var buf string
	defer func() {
		if err := ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		} else {
			log.Println("Websocket closed")
		}
	}()
	//q := ws.Request().URL.Query()
	//name := q.Get("name")
	stopped := false
	ticker := time.Tick(time.Duration(1) * time.Second)
	for !stopped {
		select {
		case <-ticker:
			val := expvar.Get(metricsVar)
			if val == nil {
				buf = ""
			} else {
				buf = val.String()
			}
			_, err := ws.Write([]byte(buf))
			if err != nil {
				log.Printf("Websocket error: %s\n", err.Error())
				stopped = true
			}

		}
	}
}
Example #11
0
func outLoop(ws *websocket.Conn, out <-chan []byte, errors chan<- error) {
	for msg := range out {
		_, err := ws.Write(msg)
		if err != nil {
			errors <- err
		}
	}
}
Example #12
0
File: cli.go Project: ajoulie/goa
// WSWrite sends STDIN lines to a websocket server.
func WSWrite(ws *websocket.Conn) {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		t := scanner.Text()
		ws.Write([]byte(t))
		fmt.Printf(">> %s\n", t)
	}
}
Example #13
0
func (a *Api) execContainer(ws *websocket.Conn) {
	qry := ws.Request().URL.Query()
	containerId := qry.Get("id")
	command := qry.Get("cmd")
	ttyWidth := qry.Get("w")
	ttyHeight := qry.Get("h")
	token := qry.Get("token")
	cmd := strings.Split(command, ",")

	if !a.manager.ValidateConsoleSessionToken(containerId, token) {
		ws.Write([]byte("unauthorized"))
		ws.Close()
		return
	}

	log.Debugf("starting exec session: container=%s cmd=%s", containerId, command)
	clientUrl := a.manager.DockerClient().URL

	execConfig := &dockerclient.ExecConfig{
		AttachStdin:  true,
		AttachStdout: true,
		AttachStderr: true,
		Tty:          true,
		Cmd:          cmd,
		Container:    containerId,
		Detach:       true,
	}

	execId, err := a.manager.DockerClient().ExecCreate(execConfig)
	if err != nil {
		log.Errorf("error calling exec: %s", err)
		return
	}

	if err := a.hijack(clientUrl.Host, "POST", "/exec/"+execId+"/start", true, ws, ws, ws, nil, nil); err != nil {
		log.Errorf("error during hijack: %s", err)
		return
	}

	// resize
	w, err := strconv.Atoi(ttyWidth)
	if err != nil {
		log.Error(err)
		return
	}

	h, err := strconv.Atoi(ttyHeight)
	if err != nil {
		log.Error(err)
		return
	}

	if err := a.manager.DockerClient().ExecResize(execId, w, h); err != nil {
		log.Errorf("error resizing exec tty: %s", err)
		return
	}

}
Example #14
0
// send a formated reply
func wsSend(ws *websocket.Conn, action, txt string) {
	response, err := json.Marshal(msgCommon{
		Cmd:  action,
		Data: txt,
	})
	if err == nil {
		ws.Write(response)
	}
}
Example #15
0
func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	logCh, errCh := app.LogReceiver()
	scanner := bufio.NewScanner(ws)
	for scanner.Scan() {
		var entry app.Applog
		data := bytes.TrimSpace(scanner.Bytes())
		if len(data) == 0 {
			continue
		}
		err = json.Unmarshal(data, &entry)
		if err != nil {
			close(logCh)
			err = fmt.Errorf("wslogs: parsing log line %q: %s", string(data), err)
			return
		}
		select {
		case logCh <- &entry:
		case err := <-errCh:
			close(logCh)
			err = fmt.Errorf("wslogs: storing log: %s", err)
			return
		}
	}
	close(logCh)
	err = scanner.Err()
	if err != nil {
		err = fmt.Errorf("wslogs: waiting for log data: %s", err)
		return
	}
	err = <-errCh
	if err != nil {
		err = fmt.Errorf("wslogs: storing log: %s", err)
	}
}
Example #16
0
File: log.go Project: gwmoura/yati
func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	dispatcher := app.NewlogDispatcher()
	scanner := bufio.NewScanner(ws)
	for scanner.Scan() {
		var entry app.Applog
		data := bytes.TrimSpace(scanner.Bytes())
		if len(data) == 0 {
			continue
		}
		err = json.Unmarshal(data, &entry)
		if err != nil {
			dispatcher.Stop()
			err = fmt.Errorf("wslogs: parsing log line %q: %s", string(data), err)
			return
		}
		err = dispatcher.Send(&entry)
		if err != nil {
			// Do not disconnect by returning here, dispatcher will already
			// retry db connection and we gain nothing by ending the WS
			// connection.
			log.Errorf("wslogs: error storing log: %s", err)
		}
	}
	err = dispatcher.Stop()
	if err != nil {
		err = fmt.Errorf("wslogs: error storing log: %s", err)
		return
	}
	err = scanner.Err()
	if err != nil {
		err = fmt.Errorf("wslogs: waiting for log data: %s", err)
		return
	}
}
Example #17
0
func remoteShellHandler(ws *websocket.Conn) {
	var httpErr *errors.HTTP
	defer func() {
		defer ws.Close()
		if httpErr != nil {
			var msg string
			switch httpErr.Code {
			case http.StatusUnauthorized:
				msg = "no token provided or session expired, please login again\n"
			default:
				msg = httpErr.Message + "\n"
			}
			ws.Write([]byte("Error: " + msg))
		}
	}()
	r := ws.Request()
	token := context.GetAuthToken(r)
	if token == nil {
		httpErr = &errors.HTTP{
			Code:    http.StatusUnauthorized,
			Message: "no token provided",
		}
		return
	}
	appName := r.URL.Query().Get(":appname")
	app, err := getAppFromContext(appName, r)
	if err != nil {
		if herr, ok := err.(*errors.HTTP); ok {
			httpErr = herr
		} else {
			httpErr = &errors.HTTP{
				Code:    http.StatusInternalServerError,
				Message: err.Error(),
			}
		}
		return
	}
	unitID := r.URL.Query().Get("unit")
	width, _ := strconv.Atoi(r.URL.Query().Get("width"))
	height, _ := strconv.Atoi(r.URL.Query().Get("height"))
	term := r.URL.Query().Get("term")
	opts := provision.ShellOptions{
		Conn:   ws,
		Width:  width,
		Height: height,
		Unit:   unitID,
		Term:   term,
	}
	err = app.Shell(opts)
	if err != nil {
		httpErr = &errors.HTTP{
			Code:    http.StatusInternalServerError,
			Message: err.Error(),
		}
	}
}
Example #18
0
// main START OMIT
func echoHandler(ws *websocket.Conn) {
	log.Print("data is recived.")
	//io.Copy(ws, ws)
	buf := make([]byte, 100)
	for {
		ws.Read(buf)
		log.Print(string(buf))
		ws.Write(buf)
	}
}
Example #19
0
// Render the frame buffer as JSON
func sendFrameBufferToWebSocket(fb *framebuffer.FrameBuffer, ws *websocket.Conn) error {

	// Send back the frame buffer as JSON
	rc, err := json.MarshalIndent(fb, "", " ")
	if err != nil {
		return err
	}
	_, err = ws.Write(rc)
	return err
}
Example #20
0
func WebsocketHandler(ws *websocket.Conn) {
	id := eventManager.On("*@websocket", func(topic string, payload interface{}) {
		ws.Write([]byte(topic))
	})
	data := make([]byte, 1)
	ws.Read(data)
	// received bytes or connection died: close it.
	eventManager.Off(id)
	ws.Close()
}
Example #21
0
func webHandler(conn *websocket.Conn) {
	data := make([]byte, 120)
	n, err := conn.Read(data)
	checkerr(err)
	fmt.Printf("msg<------[%s]\n", string(data[:n]))
	m, err := conn.Write(data[:n])
	checkerr(err)
	fmt.Printf("msg------->[%s]\n", string(data[:m]))
	defer conn.Close()
}
Example #22
0
// SendEvent will marshal an event to JSON and write it to the connection
// it passes all errors to the Server error channel
func SendEvent(conn *websocket.Conn, ev Event) {
	data, err := json.Marshal(ev)
	if err != nil {
		GlobalServer.Errors <- err
	}

	if _, err := conn.Write(data); err != nil {
		GlobalServer.Errors <- err
	}
}
Example #23
0
func receiveServerMessages(ws *websocket.Conn, closeWs chan bool) {
	for {
		select {
		case <-closeWs:
			return
		default:
		}
		serverMessage := <-serverMsg
		serverMessageString := strings.SplitN(string(serverMessage), ";", 3)
		if len(serverMessageString) == 3 {
			serverMessageId, err := strconv.ParseInt(serverMessageString[0], 10, 64)
			CheckError(err)
			if serverMessageId < lastReceivedId {
				continue
			}
			lastReceivedId = serverMessageId

			switch serverMessageString[1] {
			case "LOGIN":
				idKey := strings.SplitN(string(serverMessageString[2]), ";", 2)
				idString := idKey[0]
				keyString := idKey[1]
				key, err := strconv.ParseInt(keyString, 10, 32)
				log.Println(key)
				CheckError(err)
				if waitingRequests[int32(key)] != nil {
					waitingRequestsArray := strings.Split(string(waitingRequests[int32(key)]), ";")
					id, err := strconv.Atoi(idString)
					CheckError(err)
					clientId = id
					clientNick = waitingRequestsArray[1]
					delete(waitingRequests, int32(key))
				}
			case "OK":
				key, err := strconv.ParseInt(serverMessageString[2], 10, 32)
				CheckError(err)
				if waitingRequests[int32(key)] != nil {
					delete(waitingRequests, int32(key))
				}
			case "F":
				//				if clientId > 0 {
				//	log.Println(clientId)
				sendMap := server.ParseMsgFromServerToStruct(serverMessageString[2], clientId)

				if sendMap {
					_, err := ws.Write([]byte(serverMessageString[2]))
					CheckError(err)
				}
				//				}

			}
		}

	}
}
Example #24
0
func writeBadRequest(errString string, ws *websocket.Conn) (fatal bool) {
	logger.Log(errString)
	var out Response
	out.Message = errString
	data, err := json.Marshal(out)
	if err != nil {
		data = []byte(`{"Success":false}`)
	}
	_, err = ws.Write(data)
	return err != nil
}
Example #25
0
// handles reading input from the terminal and passing it through the websocket
// connection.
func termDaemon(t *io.ReadCloser, ws *websocket.Conn) {
	reader := bufio.NewReader(*t)
	for {
		msg := make([]byte, 1024)
		n, err := reader.Read(msg)
		if err != nil {
			return
		}
		ws.Write(msg[:n])
	}
}
Example #26
0
func SendEventClient(conn *websocket.Conn, ev Event) error {
	data, err := json.Marshal(ev)
	if err != nil {
		return err
	}

	if _, err := conn.Write(data); err != nil {
		return err
	}
	return nil
}
Example #27
0
func echoServer(ws *websocket.Conn) {
	request := make([]byte, 10000)
	n, err := ws.Read(request)
	if err != nil {
		fmt.Println("Error", err.Error())
		return
	}
	rStr := string(request[:n])
	fmt.Println("Read:", n, "It was ", rStr, " type:", ws.Request().FormValue("l"))
	ws.Write([]byte(rStr))
}
Example #28
0
// Helper function to send an WS request to a given path. urlStr is assumed to
// be the url from a httptest.Server
func SendWSRequest(urlStr, data string, t *testing.T) (string, error) {
	if data == "" {
		return "", fmt.Errorf("cannot send no data to a websocket")
	}
	u, err := url.Parse(urlStr)
	if err != nil {
		return "", err
	}
	u.Scheme = "ws"
	origin := "http://localhost/"
	errc := make(chan error)
	wsc := make(chan *websocket.Conn)
	go func() {
		ws, err := websocket.Dial(u.String(), "", origin)
		if err != nil {
			errc <- err
			return
		}
		wsc <- ws
	}()
	var ws *websocket.Conn
	select {
	case err := <-errc:
		return "", err
	case ws = <-wsc:
	case <-time.After(time.Second * 2):
		return "", fmt.Errorf("websocket dial timed out")
	}
	defer ws.Close()
	msgc := make(chan string)
	go func() {
		if _, err := ws.Write([]byte(data)); err != nil {
			errc <- err
			return
		}
		var msg = make([]byte, 512)
		var n int
		if n, err = ws.Read(msg); err != nil {
			errc <- err
			return
		}
		msgc <- string(msg[:n])
	}()
	select {
	case err := <-errc:
		return "", err
	case msg := <-msgc:
		t.Logf("response from ws: '%s'", msg)
		return msg, nil
	case <-time.After(time.Second * 2):
		return "", fmt.Errorf("websocket request timed out")
	}
}
Example #29
0
func sendMsg(conn *websocket.Conn, msg string) (err error) {
	if _, err = conn.Write([]byte(msg)); err != nil {
		log.Error(err.Error())
		return
	}
	var rec string
	if err = websocket.Message.Receive(conn, &rec); err != nil {
		log.Error(err.Error())
		return
	}
	return
}
Example #30
0
func keepAlive(ws *websocket.Conn, quit chan bool) {
	c := time.Tick(5 * time.Second)
	b := []byte{}

	for {
		select {
		case <-c:
			ws.Write(b)
		case <-quit:
			return
		}
	}
}