-
Notifications
You must be signed in to change notification settings - Fork 15
/
console.go
383 lines (355 loc) · 9.93 KB
/
console.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package main
import (
"bytes"
"context"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"strconv"
"strings"
"time"
"cesanta.com/common/go/mgrpc"
"cesanta.com/common/go/mgrpc/codec"
"cesanta.com/common/go/mgrpc/frame"
"cesanta.com/common/go/ourjson"
"cesanta.com/mos/debug_core_dump"
"cesanta.com/mos/dev"
"cesanta.com/mos/devutil"
"cesanta.com/mos/flags"
"cesanta.com/mos/timestamp"
"github.com/cesanta/errors"
"github.com/cesanta/go-serial/serial"
flag "github.com/spf13/pflag"
)
// console specific flags
var (
baudRateFlag uint
noInput bool
hwFCFlag bool
setControlLines bool
tsfSpec string
catchCoreDumps bool
)
var (
tsFormat string
)
func init() {
flag.BoolVar(&noInput, "no-input", false,
"Do not read from stdin, only print device's output to stdout")
flag.BoolVar(&catchCoreDumps, "catch-core-dumps", true, "Catch and save core dumps")
flag.StringVar(&tsfSpec, "timestamp", "StampMilli",
"Prepend each line with a timestamp in the specified format. A number of specifications are supported:"+
"simple 'yes' or 'true' will use UNIX Epoch + .microseconds; the Go way of specifying date/time "+
"format, as described in https://golang.org/pkg/time/, including the constants "+
"(so --timestamp=UnixDate will work, as will --timestamp=Stamp); the strftime(3) format "+
"(see http://strftime.org/)")
flag.Lookup("timestamp").NoOptDefVal = "true" // support just passing --timestamp
for _, f := range []string{"no-input", "timestamp"} {
hiddenFlags = append(hiddenFlags, f)
}
}
func consoleInit() {
if tsfSpec != "" {
tsFormat = timestamp.ParseTimeStampFormatSpec(tsfSpec)
}
}
func FormatTimestampNow() string {
ts := ""
if tsFormat != "" {
ts = fmt.Sprintf("[%s] ", timestamp.FormatTimestamp(time.Now(), tsFormat))
}
return ts
}
func printConsoleLine(out io.Writer, addTS bool, line []byte) {
if tsfSpec != "" && addTS {
fmt.Printf("%s", FormatTimestampNow())
}
removeNonText(line)
out.Write(line)
}
func analyzeCoreDump(out io.Writer, cd []byte) error {
info, err := debug_core_dump.GetInfoFromCoreDump(cd)
cwd, _ := os.Getwd() // Mac docker cannot mount dirs from /tmp. Thus, create core in the CWD
tf, err := ioutil.TempFile(cwd, fmt.Sprintf("core-%s-%s-%s", info.App, info.Platform, time.Now().Format("20060102-150405.")))
if err != nil {
return errors.Annotatef(err, "failed open core dump file")
}
tfn := tf.Name()
tf.Write([]byte(debug_core_dump.CoreDumpStart))
tf.Write([]byte("\r\n"))
printConsoleLine(out, true, []byte(fmt.Sprintf("mos: wrote to %s (%d bytes)\n", tfn, len(cd))))
if _, err := tf.Write(cd); err != nil {
tf.Close()
return errors.Annotatef(err, "failed to write core dump to %s", tfn)
}
tf.Write([]byte("\r\n"))
tf.Write([]byte(debug_core_dump.CoreDumpEnd))
tf.Close()
printConsoleLine(out, true, []byte("mos: analyzing core dump\n"))
return debug_core_dump.DebugCoreDumpF(tfn, "", true)
}
type chanReader struct {
rch chan []byte
rdata []byte
}
func (chr *chanReader) Read(buf []byte) (int, error) {
if chr.rch == nil {
return 0, io.EOF
}
if len(chr.rdata) == 0 {
rdata, ok := <-chr.rch
if !ok {
return 0, io.EOF
}
chr.rdata = rdata
}
b := bytes.NewBuffer(chr.rdata)
n, err := b.Read(buf)
if err == nil {
chr.rdata = chr.rdata[n:]
}
return n, err
}
func (chr *chanReader) Write(buf []byte) (int, error) {
return 0, io.EOF
}
func (chr *chanReader) Close() error {
rch := chr.rch
chr.rch = nil
if rch != nil {
close(rch)
}
return nil
}
func console(ctx context.Context, devConn *dev.DevConn) error {
var r io.Reader
var w io.Writer
purl, err := url.Parse(*flags.Port)
switch {
case err == nil && (purl.Scheme == "mqtt" || purl.Scheme == "mqtts"):
chr := &chanReader{rch: make(chan []byte)}
opts, topic, err := codec.MQTTClientOptsFromURL(*flags.Port, "", "", "")
if err != nil {
return errors.Errorf("invalid MQTT port URL format")
}
tlsConfig, err := flags.TLSConfigFromFlags()
if err != nil {
return errors.Annotatef(err, "inavlid TLS config")
}
opts.SetTLSConfig(tlsConfig)
opts.SetConnectionLostHandler(func(c mqtt.Client, err error) {
reportf("MQTT connection closed")
chr.Close()
})
cli := mqtt.NewClient(opts)
reportf("Connecting to %s...", opts.Servers[0])
token := cli.Connect()
token.Wait()
if err := token.Error(); err != nil {
return errors.Annotatef(err, "MQTT connect error")
}
topic += "/log"
token = cli.Subscribe(topic, 0 /* qos */, func(c mqtt.Client, m mqtt.Message) {
chr.rch <- m.Payload()
})
token.Wait()
if err := token.Error(); err != nil {
return errors.Annotatef(err, "MQTT subscribe error")
}
reportf("Subscribed to %s", topic)
r = chr
case err == nil && purl.Scheme == "udp":
hpp := strings.Split(purl.Host, ":")
if len(hpp) != 2 {
return errors.Errorf("invalid UDP port URL format, must be udp://:port/ or udp://ip:port/ %q %d", purl.Host, len(hpp))
}
p, err := strconv.Atoi(hpp[1])
if err != nil {
return errors.Errorf("invalid UDP port format, must be udp://:port/ or udp://ip:port/")
}
addr := net.UDPAddr{
IP: net.ParseIP(hpp[0]),
Port: p,
}
udpc, err := net.ListenUDP("udp", &addr)
if err != nil {
return errors.Annotatef(err, "failed to open listner at %+v", addr)
}
if addr.IP != nil {
reportf("Listening on UDP %s:%d...", addr.IP, addr.Port)
} else {
reportf("Listening on UDP port %d...", addr.Port)
}
defer udpc.Close()
r, w = udpc, udpc
case err == nil && (purl.Scheme == "ws" || purl.Scheme == "wss"):
// Connect to mDash and activate event forwarding.
chr := &chanReader{rch: make(chan []byte)}
devConn, err = devutil.CreateDevConnFromFlags(ctx)
if err != nil {
return errors.Trace(err)
}
if _, err = dev.CallDeviceService(ctx, devConn, "Dash.Console.Subscribe", ""); err != nil {
return errors.Trace(err)
}
devConn.RPC.AddHandler("Dash.Console.Event", func(c mgrpc.MgRPC, f *frame.Frame) *frame.Frame {
var ev struct {
DevId string `json:"id"`
Name string `json:"name"`
Data ourjson.RawMessage `json:"data"`
}
f.Params.UnmarshalInto(&ev)
var s string
if ev.Name == "rpc.out.Log" {
var logEv struct {
Timestamp float64 `json:"t"`
FD int `json:"fd"`
Seq int `json:"seq"`
Data string `json:"data"`
}
ev.Data.UnmarshalInto(&logEv)
s = fmt.Sprintf("%d %.3f %d|%s", logEv.Seq, logEv.Timestamp, logEv.FD, logEv.Data)
} else {
b, _ := ev.Data.MarshalJSON()
s = fmt.Sprintf("%s %s\n", ev.Name, string(b))
}
chr.rch <- []byte(s)
return nil
})
r = chr
default:
// Everything else is treated as a serial port.
port, err := devutil.GetPort()
if err != nil {
return errors.Trace(err)
}
sp, err := serial.Open(serial.OpenOptions{
PortName: port,
BaudRate: uint(*flags.BaudRate),
HardwareFlowControl: *flags.HWFC,
DataBits: 8,
ParityMode: serial.PARITY_NONE,
StopBits: 1,
MinimumReadSize: 1,
})
if err != nil {
return errors.Annotatef(err, "failed to open %s", port)
}
if *flags.SetControlLines || *flags.InvertedControlLines {
bFalse := *flags.InvertedControlLines
sp.SetDTR(bFalse)
sp.SetRTS(bFalse)
}
defer sp.Close()
r, w = sp, sp
}
return consoleReadWrite(ctx, r, w)
}
func consoleReadWrite(ctx context.Context, r io.Reader, w io.Writer) error {
in, out := os.Stdin, os.Stdout
cctx, cancel := context.WithCancel(ctx)
go func() { // Serial -> Stdout
var curLine []byte
var coreDump []byte
coreDumping := false
lastCDProgress := 0
cont := false
for {
buf := make([]byte, 1500)
n, err := r.Read(buf)
if err != nil {
reportf("read err %s", err)
cancel()
return
}
if n <= 0 {
continue
}
buf = buf[:n]
for {
lf := bytes.IndexAny(buf, "\n")
if lf < 0 {
break
}
chunk := buf[:lf+1]
curLine = append(curLine, chunk...)
if catchCoreDumps {
tsl := bytes.TrimSpace(curLine)
if !coreDumping && bytes.Compare(tsl, []byte(debug_core_dump.CoreDumpStart)) == 0 {
printConsoleLine(out, !cont, chunk)
printConsoleLine(out, true, []byte("mos: catching core dump\n"))
coreDumping = true
coreDump = nil
} else if coreDumping {
if bytes.Compare(tsl, []byte(debug_core_dump.CoreDumpEnd)) == 0 {
if lastCDProgress > 0 {
printConsoleLine(out, false, []byte("\n"))
}
printConsoleLine(out, true, curLine)
coreDumping = false
lastCDProgress = 0
curLine = nil
if err := analyzeCoreDump(out, coreDump); err != nil {
printConsoleLine(out, true, []byte(fmt.Sprintf("mos: %s\n", err)))
}
} else {
// There should be no empty lines in the CD body.
// If we encounter an empty line, this means device rebooted without finishing the CD.
if len(tsl) == 0 {
printConsoleLine(out, true, []byte("mos: core dump aborted\n"))
coreDumping = false
lastCDProgress = 0
coreDump = nil
} else {
coreDump = append(coreDump, curLine...)
if len(coreDump) > lastCDProgress+32*1024 {
printConsoleLine(out, lastCDProgress == 0, []byte("."))
lastCDProgress = len(coreDump)
}
}
}
}
}
if !coreDumping && curLine != nil {
printConsoleLine(out, !cont, chunk)
}
curLine = nil
buf = buf[lf+1:]
cont = false
}
if !coreDumping && len(buf) > 0 {
printConsoleLine(out, !cont, buf)
cont = true
}
curLine = append(curLine, buf...)
}
}()
if w != nil && !noInput {
go func() { // Stdin -> Serial
for {
buf := make([]byte, 1)
n, err := in.Read(buf)
if n > 0 {
w.Write(buf[:n])
}
if err != nil {
cancel()
return
}
}
}()
}
<-cctx.Done()
return nil
}
func removeNonText(data []byte) {
for i, c := range data {
if (c < 0x20 && c != 0x0a && c != 0x0d && c != 0x1b /* Esc */) || c >= 0x80 {
data[i] = 0x20
}
}
}