forked from wuchunfu/kubespace
/
stream.go
222 lines (203 loc) · 5.29 KB
/
stream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*
Copyright 2021 The DnsJia Authors.
WebSite: https://github.com/dnsjia/luban
Email: OpenSource@dnsjia.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package websocket
import (
"bytes"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/foce123/kubespace/common"
"github.com/foce123/kubespace/models"
"github.com/foce123/kubespace/models/cmdb"
"github.com/foce123/kubespace/pkg/asciicast2"
"github.com/foce123/kubespace/pkg/utils"
"github.com/gorilla/websocket"
)
type wsMsg struct {
Type string `json:"type"`
Cols int `json:"cols"`
Rows int `json:"rows"`
Close bool `json:"close"`
}
type wsConn struct {
sync.RWMutex
Ws *websocket.Conn
}
func (c *wsConn) WriteMessage(messageType int, data []byte) error {
c.Lock()
err := c.Ws.WriteMessage(messageType, data)
c.Unlock()
return err
}
func NewWsConn(conn *websocket.Conn) *wsConn {
return &wsConn{Ws: conn}
}
type RecordData struct {
Event string `json:"event"` // 输入输出事件
Time float64 `json:"time"` // 时间差
Data []byte `json:"data"` // 数据
}
type Meta struct {
TERM string
Width int
Height int
UserName string
ConnectId string
HostId uint
HostName string
}
type WebSocketStream struct {
sync.RWMutex
Terminal *Terminal // ssh客户端
Conn *wsConn // socket 连接
messageType int // 发送的数据类型
recorder []*RecordData // 操作记录
CreatedAt models.LocalTime // 创建时间
UpdatedAt models.LocalTime // 最新的更新时间
Meta Meta // 元信息
written bool // 是否已写入记录, 一个流只允许写入一次
}
// NewWebSocketSteam 创建websocket数据流
func NewWebSocketSteam(terminal *Terminal, connection *wsConn, meta Meta) *WebSocketStream {
return &WebSocketStream{
Terminal: terminal,
Conn: connection,
messageType: websocket.BinaryMessage,
CreatedAt: models.LocalTime{
Time: time.Now(),
},
UpdatedAt: models.LocalTime{
Time: time.Now(),
},
recorder: make([]*RecordData, 0),
Meta: meta,
}
}
func (r *WebSocketStream) Read(p []byte) (n int, err error) {
// 处理前端发送过来的消息
t, message, err := r.Conn.Ws.ReadMessage()
var msgObj wsMsg
jsonErr := json.Unmarshal(message, &msgObj)
if jsonErr == nil {
switch msgObj.Type {
// 改变终端大小
case "resizePty":
if msgObj.Cols > 0 && msgObj.Rows > 0 {
r.Meta.Width = msgObj.Cols
r.Meta.Height = msgObj.Rows
if err := r.Terminal.session.WindowChange(msgObj.Rows, msgObj.Cols); err != nil {
common.LOG.Info(fmt.Sprintf("ssh pty change windows size failed:\t %v", err))
}
}
return
case "closePty":
if msgObj.Close {
if err := r.Terminal.Close(); err != nil {
common.LOG.Info(fmt.Sprintf("Close pty failed:\t %v", err))
}
}
return
}
}
r.Lock()
//r.recorder = append(r.recorder, &RecordData{
// Time: time.Since(r.CreatedAt.Time).Seconds(),
// Event: "i",
// Data: message,
//})
defer r.Unlock()
r.UpdatedAt = models.LocalTime{
Time: time.Now(),
} // 更新时间
r.messageType = t
n = len(message)
copy(p, message) // 将stdin复制到stdout
return
}
func (r *WebSocketStream) Write(p []byte) (n int, err error) {
n = len(p)
var msgObj wsMsg
jsonErr := json.Unmarshal(p, &msgObj)
if jsonErr == nil {
switch msgObj.Type {
// 忽略自定义消息
case "resizePty":
return
case "closePty":
return
}
}
r.Lock()
var data = make([]byte, len(p))
copy(data, p)
r.recorder = append(r.recorder, &RecordData{
Time: time.Since(r.CreatedAt.Time).Seconds(),
Event: "o",
Data: data,
})
defer r.Unlock()
if r.Conn != nil {
}
// 超时
_ = r.Conn.Ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
err = r.Conn.WriteMessage(r.messageType, p)
r.UpdatedAt = models.LocalTime{
Time: time.Now(),
} // 更新时间
return
}
func (r *WebSocketStream) Write2Log() error {
// 记录用户的操作
r.Lock()
defer r.Unlock()
if r.written {
return nil
}
recorders := r.recorder
if len(recorders) != 0 {
b := new(bytes.Buffer)
meta := asciicast2.CastV2Header{
Width: r.Meta.Width,
Height: r.Meta.Height,
Timestamp: time.Now().Unix(),
Title: r.Meta.ConnectId,
Env: &map[string]string{
"SHELL": "/bin/bash", "TERM": r.Meta.TERM,
},
}
cast, buffer := asciicast2.NewCastV2(meta, b)
for _, v := range recorders {
cast.Record(v.Time, v.Data, v.Event)
}
compressData := utils.ZlibCompress(buffer.Bytes())
if len(compressData) > 320 {
record := cmdb.SSHRecord{
ConnectID: r.Meta.ConnectId,
HostName: r.Meta.HostName,
UserName: r.Meta.UserName,
Records: compressData,
ConnectTime: r.CreatedAt,
LogoutTime: models.LocalTime{
Time: time.Now(),
},
HostId: r.Meta.HostId,
}
common.DB.Create(&record)
}
}
r.written = true
return nil
}