Debian Codegraph @

core/lstreams_resolver.go

raw
1 package core
2
3 import (
4 "fmt"
5 "strings"
6
7 "github.com/dimonomid/nerdlog/shellescape"
8 "github.com/dimonomid/ssh_config"
9 "github.com/gobwas/glob"
10 "github.com/juju/errors"
11 )
12
13 type LStreamsResolver struct {
14 params LStreamsResolverParams
15 }
16
17 type LStreamsResolverParams struct {
18 // CurOSUser is the current OS username, it's used as the last resort when
19 // determining the user for a particular host connection.
20 CurOSUser string
21
22 // If UseExternalSSH is true, we'll use external ssh binary instead of
23 // internal ssh library (i.e. ShellTransportSSHBin instead of
24 // ShellTransportSSHLib).
25 UseExternalSSH bool
26
27 // ConfigLogStreams is the nerdlog-specific config, typically coming from
28 // ~/.config/nerdlog/logstreams.yaml.
29 ConfigLogStreams ConfigLogStreams
30
31 // SSHConfig is the general SSH config, typically coming from ~/.ssh/config
32 SSHConfig *ssh_config.Config
33 }
34
35 func NewLStreamsResolver(params LStreamsResolverParams) *LStreamsResolver {
36 return &LStreamsResolver{
37 params: params,
38 }
39 }
40
41 type LogStream struct {
42 // Name is an arbitrary string which will be included in log messages as the
43 // "lstream" context tag; it must uniquely identify the LogStream.
44 Name string
45
46 // NOTE: all fields below are shell-specific; so if at some point we want
47 // to support other kinds of backends, we'll probably need to factor all
48 // these details to a separate struct like LogStreamShell or something.
49
50 // Transport specifies how we can get shell access to the host containing
51 // the logstream.
52 Transport ConfigLogStreamShellTransport
53
54 // LogFiles contains a list of files which are part of the logstream, like
55 // ["/var/log/syslog", "/var/log/syslog.1"]. The [0]th item is the latest log
56 // file [1]st is the previous one, etc. One special case here is journalctl:
57 // if [0]th item is "journalctl", then we won't use plain log files, and
58 // instead will get the data straight from journalctl.
59 //
60 // It must contain at least a single item, otherwise LogStream is invalid.
61 LogFiles []string
62
63 Options LogStreamOptions
64 }
65
66 // ConfigLogStreamShellTransportSSHLib contains params for the ssh transport
67 // using internal ssh library.
68 type ConfigLogStreamShellTransportSSHLib struct {
69 Host ConfigHost
70 Jumphost *ConfigHost
71 }
72
73 // ConfigLogStreamShellTransportSSHBin contains params for the ssh transport
74 // using external ssh binary.
75 type ConfigLogStreamShellTransportSSHBin struct {
76 // Host is just the hostname, like "myserver.com" or an IP address.
77 Host string
78
79 // Port is optional: if present, it'll be passed to the ssh binary using
80 // the -p flag, otherwise the -p flag will not be given at all.
81 Port string
82 // User is optional: if present, the destination param to the ssh binary
83 // will be prefixed with "<user>@", otherwise the destination will be just
84 // the Host.
85 User string
86 }
87
88 type ConfigLogStreamShellTransportLocalhost struct {
89 // No details are needed here
90 }
91
92 type ConfigLogStreamShellTransport struct {
93 SSHLib *ConfigLogStreamShellTransportSSHLib
94 SSHBin *ConfigLogStreamShellTransportSSHBin
95 Localhost *ConfigLogStreamShellTransportLocalhost
96 }
97
98 type LogStreamOptions struct {
99 SudoMode SudoMode
100
101 // ShellInit can contain arbitrary shell commands which will be executed
102 // right after connecting to the host. A common use case is setting
103 // custom env vars for tests, like: "export TZ=America/New_York", but
104 // might be useful outside of tests as well.
105 ShellInit []string
106 }
107
108 // SudoMode can be used to configure nerdlog to read log files with "sudo -n".
109 // See constants below for more details.
110 type SudoMode string
111
112 const (
113 // SudoModeNone is the same as an empty string, and it obviously means that
114 // no sudo will be used. It exists as a separate mode to make it possible to
115 // override the mode to not use sudo even if some config specifies some
116 // non-empty sudo mode.
117 SudoModeNone SudoMode = "none"
118
119 // SudoModeFull means that the whole nerdlog_agent.sh script will be executed
120 // with "sudo -n". Useful for cases when the log files are owned by root but
121 // sudo doesn't require a password.
122 SudoModeFull SudoMode = "full"
123
124 // If needed, we might implement something like SudoModeGranular, which would
125 // mean that the agent script runs without sudo, but then internally it
126 // executes some commands with sudo. It would mean a more complicated setup
127 // and more maintenance burden and harder to configure sudoers file, so
128 // postponed until we actually need it (if at all).
129 )
130
131 var ValidSudoModes = map[SudoMode]struct{}{
132 SudoModeNone: {},
133 SudoModeFull: {},
134 }
135
136 type ConfigHost struct {
137 // Addr is the address to connect to, in the same format which is used by
138 // net.Dial. To copy-paste some docs from net.Dial: the address has the form
139 // "host:port". The host must be a literal IP address, or a host name that
140 // can be resolved to IP addresses. The port must be a literal port number or
141 // a service name.
142 //
143 // Examples: "golang.org:http", "192.0.2.1:http", "198.51.100.1:22".
144 Addr string
145 // User is the username to authenticate as.
146 User string
147 }
148
149 func (ch *ConfigHost) Key() string {
150 return fmt.Sprintf("%s@%s", ch.Addr, ch.User)
151 }
152
153 func (ls LogStream) LogFileLast() string {
154 // LogFiles must contain at least a single item, so we don't check anything
155 // here, and let it panic naturally if the invariant breaks due to some bug.
156 return ls.LogFiles[0]
157 }
158
159 func (ls LogStream) LogFilePrev() (string, bool) {
160 if len(ls.LogFiles) >= 2 {
161 return ls.LogFiles[1], true
162 }
163
164 return "", false
165 }
166
167 // Resolve parses the given logstream spec, and returns the mapping from
168 // LogStream.Name to the corresponding LogStream. Examples of logstream spec are:
169 //
170 // - "[email protected]:22:/var/log/syslog"
171 // - "[email protected]:22"
172 // - "[email protected]"
173 // - "myserver.com"
174 func (r *LStreamsResolver) Resolve(lstreamsStr string) (map[string]LogStream, error) {
175 lstreamsStr = strings.TrimSpace(lstreamsStr)
176
177 parsedLogStreams := map[string]LogStream{}
178
179 // Special case for an empty input: it's allowed and just results in no
180 // logstreams.
181 if lstreamsStr == "" {
182 return parsedLogStreams, nil
183 }
184
185 // TODO: when json is supported, splitting by commas will need to be improved.
186 parts := strings.Split(lstreamsStr, ",")
187 for i, part := range parts {
188 part = strings.TrimSpace(part)
189
190 if part == "" {
191 return nil, errors.Errorf("entry #%d is empty", i+1)
192 }
193
194 cfs, err := r.parseLogStreamSpecEntry(part)
195 if err != nil {
196 return nil, errors.Annotatef(err, "parsing entry #%d (%s)", i+1, part)
197 }
198
199 for _, ch := range cfs {
200 key := ch.Name
201
202 if _, exists := parsedLogStreams[key]; exists {
203 return nil, errors.Errorf("the logstream %s is present at least twice", key)
204 }
205
206 parsedLogStreams[key] = ch
207 }
208 }
209
210 return parsedLogStreams, nil
211 }
212
213 // draftLogStream is a draft version of LogStream; it's used as temporary
214 // storage in the process of resolving logstreams.
215 type draftLogStream struct {
216 name string
217 host ConfigHost
218 jumphost *ConfigHost
219 logFiles []string
220 options LogStreamOptions
221 }
222
223 // parseLogStreamSpecEntry parses a single logstream spec entry like
224 // "[email protected]:22:/var/log/syslog", or "myserver.com", or
225 // "myserver-*", and returns the corresponding LogStream-s. Note that the spec
226 // might contain a glob, in which case we might return more than 1 LogStream.
227 // If the glob didn't match anything, an error is returned.
228 //
229 // TODO: it should take a predefined config, to support globs
230 func (r *LStreamsResolver) parseLogStreamSpecEntry(s string) ([]LogStream, error) {
231 parts, err := shellescape.Parse(s)
232 if err != nil {
233 return nil, errors.Trace(err)
234 }
235
236 var plstream *parsedLStream
237 var jhconf *ConfigHost
238 var logFiles []string
239
240 curFlag := ""
241 for _, part := range parts {
242 if curFlag == "" && len(part) > 0 && part[0] == '-' {
243 curFlag = part
244 continue
245 }
246
247 switch curFlag {
248 case "-J", "--jumphost":
249 jhparsed, err := r.parseLStreamStr(part)
250 if err != nil {
251 return nil, errors.Annotatef(err, "parsing %q as a jumphost", part)
252 }
253
254 //if jhparsed.logFileLast != "" || jhparsed.logFilePrev != "" {
255 //return nil, errors.Annotatef(err, "jumphost config shouldn't contain files")
256 //}
257
258 jhPort := jhparsed.port
259
260 if len(jhparsed.colonParts) > 1 {
261 return nil, errors.Errorf("parsing %q as a jumphost: too many colons", part)
262 }
263
264 jhconf = &ConfigHost{
265 Addr: fmt.Sprintf("%s:%s", jhparsed.hostname, jhPort),
266 User: jhparsed.user,
267 }
268
269 case "":
270 var err error
271 plstream, err = r.parseLStreamStr(part)
272 if err != nil {
273 return nil, errors.Annotatef(err, "parsing %q as a logstream", part)
274 }
275
276 if len(plstream.colonParts) > 0 {
277 logFiles = append(logFiles, plstream.colonParts[0])
278 }
279
280 if len(plstream.colonParts) > 1 {
281 logFiles = append(logFiles, plstream.colonParts[1])
282 }
283
284 if len(plstream.colonParts) > 2 {
285 return nil, errors.Errorf("%q: too many colons", part)
286 }
287 default:
288 return nil, errors.Errorf("invalid flag %s", curFlag)
289 }
290
291 curFlag = ""
292 }
293
294 if plstream == nil {
295 return nil, errors.Errorf("no logstream specified in %q", s)
296 }
297
298 lstreams := []draftLogStream{
299 {
300 name: s,
301
302 host: ConfigHost{
303 Addr: fmt.Sprintf("%s:%s", plstream.hostname, plstream.port),
304 User: plstream.user,
305 },
306 jumphost: jhconf,
307
308 logFiles: logFiles,
309 },
310 }
311
312 // Expand from nerdlog config.
313 lstreams, err = expandFromLogStreamsConfig(
314 lstreams, r.params.ConfigLogStreams, expandOpts{},
315 )
316 if err != nil {
317 return nil, errors.Annotatef(err, "expanding from nerdlog config")
318 }
319
320 // Expand from ssh config.
321 lsConfigFromSSHConfig, err := sshConfigToLSConfig(r.params.SSHConfig)
322 if err != nil {
323 return nil, errors.Annotatef(err, "parsing ssh config")
324 }
325
326 lstreams, err = expandFromLogStreamsConfig(
327 lstreams, lsConfigFromSSHConfig, expandOpts{
328 // If using internal ssh library, then expand everything as usual: expand
329 // globs and fill in the missing details. But if using external ssh, then
330 // only expand globs, and leave filling all the missing connection
331 // details up to ssh.
332 skipFillingConnDetails: r.params.UseExternalSSH,
333 },
334 )
335 if err != nil {
336 return nil, errors.Annotatef(err, "expanding from ssh config")
337 }
338
339 if !r.params.UseExternalSSH {
340 // We're not using external ssh binary, so also try to fill in the
341 // details from the parsed ssh config, and then from the defaults too.
342
343 lstreams, err = setLogStreamsConnDefaults(lstreams, r.params.CurOSUser)
344 if err != nil {
345 return nil, errors.Annotatef(err, "setting defaults")
346 }
347 } else {
348 // We're using external ssh binary: in this case, we don't fill in the
349 // details from ssh config or from the defaults manually, and instead leave
350 // all this up to the external ssh binary.
351 }
352
353 // Regardless of the external or internal ssh, we still need to fill in
354 // the default logfiles.
355 lstreams, err = setLogStreamsFileDefaults(lstreams)
356 if err != nil {
357 return nil, errors.Annotatef(err, "setting defaults")
358 }
359
360 // Check if some of the items were clearly indended to be globs matching
361 // something (those with asterisks in them), and didn't match anything.
362 for _, ls := range lstreams {
363 // TODO: would perhaps be useful to implement a function like IsValidDialAddress,
364 // which checks a bunch of other things, but for now, a single asterisk check
365 // will do.
366 if strings.Contains(ls.host.Addr, "*") {
367 return nil, errors.Errorf("glob %q didn't match anything (having address %q)", s, ls.host.Addr)
368 }
369 }
370
371 // Convert draft logstreams to the actual ones.
372 ret := make([]LogStream, 0, len(lstreams))
373 for _, ls := range lstreams {
374
375 var transport ConfigLogStreamShellTransport
376 // Using kinda hackish logic: if the hostname part is "localhost", then
377 // ignore the port and user completely, and just use local shell.
378 //
379 // Maybe we need to treat some other strings similarly, like
380 // "localhost.localdomain", or "127.0.0.1", or "::1"; but not sure if it
381 // would actually bring any value. So for now, only "localhost" has this
382 // special treatment (which is also the default when one opens Nerdlog for
383 // the first time).
384 if strings.HasPrefix(ls.host.Addr, "localhost:") {
385 // Use local shell
386 transport = ConfigLogStreamShellTransport{
387 Localhost: &ConfigLogStreamShellTransportLocalhost{},
388 }
389 } else {
390 // Use ssh
391 if !r.params.UseExternalSSH {
392 // Use internal ssh library
393 transport = ConfigLogStreamShellTransport{
394 SSHLib: &ConfigLogStreamShellTransportSSHLib{
395 Host: ls.host,
396 Jumphost: ls.jumphost,
397 },
398 }
399 } else {
400 // Use external ssh binary
401 parsedAddr, err := parseAddr(ls.host.Addr)
402 if err != nil {
403 return nil, errors.Annotatef(err, "parsing addr %s for external ssh binary", ls.host.Addr)
404 }
405
406 transport = ConfigLogStreamShellTransport{
407 SSHBin: &ConfigLogStreamShellTransportSSHBin{
408 Host: parsedAddr.host,
409 Port: parsedAddr.port,
410 User: ls.host.User,
411 },
412 }
413 }
414 }
415
416 ret = append(ret, LogStream{
417 Name: ls.name,
418 Transport: transport,
419 LogFiles: ls.logFiles,
420 Options: ls.options,
421 })
422 }
423
424 return ret, nil
425 }
426
427 type parsedLStream struct {
428 hostname string
429 user string
430 port string
431
432 colonParts []string
433 }
434
435 func (r *LStreamsResolver) parseLStreamStr(s string) (*parsedLStream, error) {
436 // Parsing the logstream descriptor like
437 // "user@hostname:/path/to/logfile:/path/to/logfile.1"
438
439 // Parse user, if present
440 username := ""
441 atIdx := strings.IndexRune(s, '@')
442 if atIdx == 0 {
443 return nil, errors.Errorf("username is empty")
444 } else if atIdx > 0 {
445 username = s[:atIdx]
446 s = s[atIdx+1:]
447 }
448
449 port := ""
450 colonParts := []string{}
451 parts := strings.Split(s, ":")
452 if len(parts) == 0 || parts[0] == "" {
453 return nil, errors.Errorf("no hostname")
454 }
455
456 if len(parts) > 1 {
457 port = parts[1]
458 }
459
460 if len(parts) > 2 {
461 colonParts = parts[2:]
462 }
463
464 return &parsedLStream{
465 hostname: parts[0],
466 user: username,
467 port: port,
468 colonParts: colonParts,
469 }, nil
470 }
471
472 type ConfigLogStreamWKey struct {
473 // Key is the key at which the corresponding ConfigLogStream was
474 // stored in the ConfigLogStreams map.
475 Key string
476
477 ConfigLogStream
478 }
479
480 type expandOpts struct {
481 // If skipFillingConnDetails is true, then the connection details (host,
482 // port, username) will not be filled from the config. This must be set to
483 // true when the config was parsed from the ssh config and we're using
484 // external ssh binary: in this case, filling all the missing details should
485 // be left up to the external ssh binary.
486 skipFillingConnDetails bool
487 }
488
489 // expandFromLogStreamsConfig goes through each of the logstreams, and
490 // potentially expands every item as per the provided config.
491 func expandFromLogStreamsConfig(
492 logStreams []draftLogStream,
493 lsConfig ConfigLogStreams,
494 opts expandOpts,
495 ) ([]draftLogStream, error) {
496 // If there's no config, cut it short.
497 if lsConfig == nil {
498 return logStreams, nil
499 }
500
501 var ret []draftLogStream
502
503 for i, ls := range logStreams {
504 var matchedConfigItems []*ConfigLogStreamWKey
505
506 addr, err := parseAddr(ls.host.Addr)
507 if err != nil {
508 return nil, errors.Annotatef(err, "logstream #%d, parsing address", i+1)
509 }
510
511 globPattern := addr.host
512 matcher, err := glob.Compile(globPattern)
513 if err != nil {
514 return nil, errors.Annotatef(err, "logstream #%d, parsing hostname %q as a glob pattern", i+1, addr.host)
515 }
516
517 for _, key := range lsConfig.Keys() {
518 if matcher.Match(key) {
519 matchedConfigItems = append(matchedConfigItems, &ConfigLogStreamWKey{
520 Key: key,
521 ConfigLogStream: lsConfig[key],
522 })
523 }
524 }
525
526 // If there's no match, just copy that logstream unchanged.
527 if len(matchedConfigItems) == 0 {
528 ret = append(ret, ls)
529 continue
530 }
531
532 // There are some matches, so we need to expand things.
533 for _, matchedItem := range matchedConfigItems {
534 lsCopy := ls
535 addrCopy := addr
536
537 // Always override the name with the key from the config.
538 lsCopy.name = strings.Replace(lsCopy.name, globPattern, matchedItem.Key, -1)
539
540 if !opts.skipFillingConnDetails {
541 // Overwrite the host address (since what we've had might be a glob):
542 // either with the Hostname if it's specified explicitly, or if not, then
543 // with the item key.
544 if matchedItem.Hostname != "" {
545 addrCopy.host = matchedItem.Hostname
546 } else {
547 addrCopy.host = matchedItem.Key
548 }
549
550 // Everything else we'll only override if it's not specified already.
551
552 if addrCopy.port == "" {
553 addrCopy.port = matchedItem.Port
554 }
555
556 if lsCopy.host.User == "" {
557 lsCopy.host.User = matchedItem.User
558 }
559 } else {
560 // We're asked to skip filling conn details, so just replace the host
561 // with the matched item's key (because or original host might have
562 // been a glob), and leave the port and user as is.
563 addrCopy.host = matchedItem.Key
564 }
565
566 // For non-connection details, override them if not specified already.
567
568 if lsCopy.options.SudoMode == "" {
569 lsCopy.options.SudoMode = matchedItem.Options.EffectiveSudoMode()
570 }
571
572 if lsCopy.options.ShellInit == nil {
573 lsCopy.options.ShellInit = matchedItem.Options.ShellInit
574 }
575
576 if len(lsCopy.logFiles) == 0 {
577 lsCopy.logFiles = matchedItem.LogFiles
578 }
579
580 lsCopy.host.Addr = fmt.Sprintf("%s:%s", addrCopy.host, addrCopy.port)
581
582 ret = append(ret, lsCopy)
583 }
584 }
585
586 return ret, nil
587 }
588
589 // setLogStreamsConnDefaults goes through each of the logstreams, and fills in
590 // missing pieces for which it knows the defaults for how to connect to the
591 // hosts: port 22, user as the current OS user.
592 //
593 // Note that it shouldn't be used when we're utilizing external ssh binary:
594 // in this case, we want to leave it all up to the ssh.
595 func setLogStreamsConnDefaults(
596 logStreams []draftLogStream,
597 osUser string,
598 ) ([]draftLogStream, error) {
599 ret := make([]draftLogStream, 0, len(logStreams))
600
601 for i, ls := range logStreams {
602 port, err := portFromAddr(ls.host.Addr)
603 if err != nil {
604 return nil, errors.Annotatef(err, "logstream #%d, getting port", i+1)
605 }
606
607 if port == "" {
608 ls.host.Addr += "22"
609 }
610
611 if ls.host.User == "" {
612 ls.host.User = osUser
613 }
614
615 ret = append(ret, ls)
616 }
617
618 return ret, nil
619 }
620
621 // setLogStreamsFileDefaults goes through each of the logstreams, and fills in
622 // missing non-connection pieces, such as default log files.
623 func setLogStreamsFileDefaults(logStreams []draftLogStream) ([]draftLogStream, error) {
624 ret := make([]draftLogStream, 0, len(logStreams))
625
626 for _, ls := range logStreams {
627 if len(ls.logFiles) == 0 {
628 // Will be autodetected by the agent script.
629 ls.logFiles = append(ls.logFiles, "auto")
630 }
631
632 if len(ls.logFiles) == 1 {
633 // Will be autodetected by the agent script.
634 ls.logFiles = append(ls.logFiles, "auto")
635 }
636
637 ret = append(ret, ls)
638 }
639
640 return ret, nil
641 }
642
643 type parsedAddr struct {
644 host string
645 port string
646 }
647
648 func parseAddr(addr string) (parsedAddr, error) {
649 parts := strings.Split(addr, ":")
650 if len(parts) != 2 {
651 return parsedAddr{}, errors.Errorf("not a valid addr %q, expected host:port", addr)
652 }
653
654 return parsedAddr{
655 host: parts[0],
656 port: parts[1],
657 }, nil
658 }
659
660 // hostnameFromAddr takes an address like net.Dial takes, in the form of
661 // "host:port", and returns the host part.
662 func hostnameFromAddr(addr string) (string, error) {
663 parts := strings.Split(addr, ":")
664 if len(parts) != 2 {
665 return "", errors.Errorf("not a valid addr %q, expected host:port", addr)
666 }
667
668 return parts[0], nil
669 }
670
671 // portFromAddr takes an address like net.Dial takes, in the form of
672 // "host:port", and returns the port part.
673 func portFromAddr(addr string) (string, error) {
674 parts := strings.Split(addr, ":")
675 if len(parts) != 2 {
676 return "", errors.Errorf("not a valid addr %q, expected host:port", addr)
677 }
678
679 return parts[1], nil
680 }
681
682 func sshConfigToLSConfig(sshConfig *ssh_config.Config) (ConfigLogStreams, error) {
683 if sshConfig == nil {
684 return nil, nil
685 }
686
687 ret := make(ConfigLogStreams, len(sshConfig.Hosts))
688
689 for _, host := range sshConfig.Hosts {
690 if len(host.Patterns) == 0 {
691 continue
692 }
693
694 name := host.Patterns[0].String()
695 if name == "" {
696 continue
697 }
698
699 // If it's a pattern, ignore it
700 // (there might be valid use cases where we'd want to use them, but
701 // not bothering for now)
702 if strings.ContainsAny(name, "*?[]") {
703 continue
704 }
705
706 hostname, _ := sshConfig.Get(name, "HostName")
707 port, _ := sshConfig.Get(name, "Port")
708 user, _ := sshConfig.Get(name, "User")
709
710 if hostname == "" && port == "" && user == "" {
711 // We can't get anything useful out of this entry anyway, so don't add it
712 continue
713 }
714
715 ret[name] = ConfigLogStream{
716 Hostname: hostname,
717 Port: port,
718 User: user,
719 }
720 }
721
722 return ret, nil
723 }