-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathsysinfo_linux.go
More file actions
274 lines (249 loc) · 8.97 KB
/
sysinfo_linux.go
File metadata and controls
274 lines (249 loc) · 8.97 KB
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
//go:build linux
// +build linux
/*
Copyright (c) 2023 Snowflake Inc. All rights reserved.
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 server
import (
"bufio"
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
pb "github.com/Snowflake-Labs/sansshell/services/sysinfo"
"github.com/Snowflake-Labs/sansshell/services/util"
"github.com/Snowflake-Labs/sansshell/telemetry/metrics"
"github.com/euank/go-kmsg-parser/v2/kmsgparser"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/sys/unix"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
// for testing
var (
journalctlBin = "/usr/bin/journalctl"
getKmsgParser = func() (kmsgparser.Parser, error) {
return kmsgparser.NewParser()
}
generateJournalCmd = func(p *pb.JournalRequest) ([]string, error) {
cmd := []string{journalctlBin}
if p.Unit != "" {
cmd = append(cmd, fmt.Sprintf("--unit=%s", p.Unit))
}
if p.TailLine == 0 {
return nil, status.Errorf(codes.InvalidArgument, "cannot tail zero journal entry")
} else if p.TailLine > 0 {
cmd = append(cmd, fmt.Sprintf("--lines=%d", p.TailLine))
}
if p.TimeSince != nil {
timeStr := p.TimeSince.AsTime().In(time.Local).Format(pb.TimeFormat_YYYYMMDDHHMMSS)
cmd = append(cmd, fmt.Sprintf("--since=%v", timeStr))
}
if p.TimeUntil != nil {
timeStr := p.TimeUntil.AsTime().In(time.Local).Format(pb.TimeFormat_YYYYMMDDHHMMSS)
cmd = append(cmd, fmt.Sprintf("--until=%v", timeStr))
}
// since json output contains all necessary information we need for now
// set the format and extract fields we need
cmd = append(cmd, "--output=json")
return cmd, nil
}
)
var getUptime = func() (time.Duration, error) {
sysinfo := &unix.Sysinfo_t{}
if err := unix.Sysinfo(sysinfo); err != nil {
return 0, status.Errorf(codes.Internal, "err in get the system info from unix")
}
uptime := time.Duration(sysinfo.Uptime) * time.Second
return uptime, nil
}
// Based on: https://pkg.go.dev/github.com/euank/go-kmsg-parser
// kmsg-parser only allows us to read message from /dev/kmsg in a blocking way
// we set 2 seconds timeout to explicitly close the channel
// If the package releases new feature to support non-blocking read, we can
// make corresponding changes below to get rid of hard code timeout setting
var getKernelMessages = func(timeout time.Duration, cancelCh <-chan struct{}) ([]*pb.DmsgRecord, error) {
parser, err := getKmsgParser()
if err != nil {
return nil, err
}
var records []*pb.DmsgRecord
messages := parser.Parse()
done := false
timeoutCh := time.After(timeout)
for !done {
// Select doesn't care about the order of statements, a chatty enough kernel will continue pushing messages
// into kmsg and therefore our cancellation and timeout logic will not be reached ever,
// so we do this check first to ensure we don't miss our "deadlines" or client-side cancellation
select {
case <-cancelCh:
parser.Close()
done = true
continue
default:
}
select {
case <-timeoutCh:
parser.Close()
done = true
continue
default:
}
select {
case msg, ok := <-messages:
if !ok {
done = true
}
// process the message
records = append(records, &pb.DmsgRecord{
Message: msg.Message,
Time: timestamppb.New(msg.Timestamp),
})
// messages channel can have excessive idle time, we want to utilize that to avoid excessive CPU usage
// hence we do a blocking read of the messages channel (no default statement) but at the same time
// do blocking read from other channels in case this idle window exceeds timeout or if client cancels command
case <-timeoutCh:
parser.Close()
done = true
case <-cancelCh:
parser.Close()
done = true
}
}
return records, nil
}
// sanitizeString replaces non-printable characters (except common whitespace)
// with the Unicode replacement character, ensuring the output is valid UTF-8.
func sanitizeString(s string) string {
return strings.Map(func(r rune) rune {
if r == utf8.RuneError {
return unicode.ReplacementChar
}
if unicode.IsPrint(r) || r == '\n' || r == '\r' || r == '\t' {
return r
}
return unicode.ReplacementChar
}, s)
}
// journalValueToString converts a single journalctl JSON value to a string.
// systemd's journalctl --output=json encodes non-UTF8 / binary fields as
// JSON arrays of byte values (numbers 0-255) instead of strings.
func journalValueToString(v any) string {
switch val := v.(type) {
case string:
return val
case []any:
buf := make([]byte, 0, len(val))
for _, elem := range val {
f, ok := elem.(float64)
if !ok || f < 0 || f > math.MaxUint8 || f != math.Trunc(f) {
// Not a valid byte array (mixed types, out-of-range, or
// fractional values). Fall back to a textual representation
// so the proto string field is always populated and the
// server never crashes on unexpected input.
return fmt.Sprintf("%v", v)
}
buf = append(buf, byte(f))
}
return sanitizeString(string(buf))
default:
return fmt.Sprintf("%v", v)
}
}
// journalEntryToStringMap converts a map[string]any (from JSON unmarshal) to
// map[string]string suitable for the JournalRecordRaw proto entry field.
func journalEntryToStringMap(raw map[string]any) map[string]string {
out := make(map[string]string, len(raw))
for k, v := range raw {
out[k] = journalValueToString(v)
}
return out
}
var getJournalRecordsAndSend = func(ctx context.Context, req *pb.JournalRequest, stream pb.SysInfo_JournalServer) error {
recorder := metrics.RecorderFromContextOrNoop(ctx)
command, err := generateJournalCmd(req)
if err != nil {
recorder.CounterOrLog(ctx, sysinfoJournalFailureCounter, 1, attribute.String("reason", "generate_cmd_err"))
return err
}
run, err := util.RunCommand(ctx, command[0], command[1:])
if err != nil {
recorder.CounterOrLog(ctx, sysinfoJournalFailureCounter, 1, attribute.String("reason", "run_err"))
return err
}
if err := run.Error; run.ExitCode != 0 || err != nil {
recorder.CounterOrLog(ctx, sysinfoJournalFailureCounter, 1, attribute.String("reason", "run_err"))
return status.Errorf(codes.Internal, "error from running - %v\nstdout:\n%s\nstderr:\n%s", err, util.TrimString(run.Stdout.String()), util.TrimString(run.Stderr.String()))
}
// parse the output
scanner := bufio.NewScanner(run.Stdout)
for scanner.Scan() {
// Based on https://man.archlinux.org/man/journalctl.1#OUTPUT_OPTIONS
// set output to json will "format entries as JSON objects, separated by newline characters"
// so we can parse each entry line by line
text := scanner.Text()
var journalRaw map[string]any
if err := json.Unmarshal([]byte(text), &journalRaw); err != nil {
return status.Errorf(codes.Internal, "parse the journal entry from json string to map err: %v", err)
}
journalMap := journalEntryToStringMap(journalRaw)
if req.EnableJson {
journalRecordRaw := &pb.JournalRecordRaw{}
journalRecordRaw.Entry = journalMap
if err := stream.Send(&pb.JournalReply{
Response: &pb.JournalReply_JournalRaw{
JournalRaw: journalRecordRaw,
},
}); err != nil {
recorder.CounterOrLog(ctx, sysinfoJournalFailureCounter, 1, attribute.String("reason", "stream_send_err"))
return status.Errorf(codes.Internal, "journal: send error %v", err)
}
} else {
// default format
journalRecord := &pb.JournalRecord{}
// Parse the string value as an int64
realtime, err := strconv.ParseInt(journalMap["__REALTIME_TIMESTAMP"], 10, 64)
if err != nil {
return status.Errorf(codes.Internal, "journal entry realtime converts error: %v from string to int64", err)
}
journalRecord.RealtimeTimestamp = timestamppb.New(time.Unix(0, realtime*int64(time.Microsecond)))
journalRecord.Hostname = journalMap["_HOSTNAME"]
journalRecord.SyslogIdentifier = journalMap["SYSLOG_IDENTIFIER"]
journalRecord.Message = journalMap["MESSAGE"]
// some log entries may not have pid, since they are not generated by a process
if pidStr, ok := journalMap["_PID"]; ok {
pid, err := strconv.Atoi(pidStr)
if err != nil {
return status.Errorf(codes.Internal, "pid converts error: %v from string to int32", err)
}
journalRecord.Pid = int32(pid)
}
// send the record directly
if err := stream.Send(&pb.JournalReply{
Response: &pb.JournalReply_Journal{
Journal: journalRecord,
},
}); err != nil {
recorder.CounterOrLog(ctx, sysinfoJournalFailureCounter, 1, attribute.String("reason", "stream_send_err"))
return status.Errorf(codes.Internal, "journal: send error %v", err)
}
}
}
return nil
}