summaryrefslogtreecommitdiff
path: root/internal/session/spec.go
blob: 6df11fd0d286d00fa7a4c1571b08a8390735fbd4 (plain)
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
package session

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"strings"

	"github.com/mimecast/dtail/internal/config"
	"github.com/mimecast/dtail/internal/omode"
	"github.com/mimecast/dtail/internal/regex"
)

// Spec captures the mutable, per-connection workload a DTail client wants to run.
type Spec struct {
	Mode        omode.Mode `json:"mode"`
	Files       []string   `json:"files"`
	Options     string     `json:"options,omitempty"`
	Query       string     `json:"query,omitempty"`
	Regex       string     `json:"regex,omitempty"`
	RegexInvert bool       `json:"regex_invert,omitempty"`
	Timeout     int        `json:"timeout,omitempty"`
}

// NewSpec returns a session specification from client args.
func NewSpec(args config.Args) Spec {
	files := splitFiles(args.What)
	if args.Serverless && len(files) == 0 && supportsServerlessPipe(args.Mode) {
		files = []string{"-"}
	}

	return Spec{
		Mode:        args.Mode,
		Files:       files,
		Options:     args.SerializeOptions(),
		Query:       strings.TrimSpace(args.QueryStr),
		Regex:       args.RegexStr,
		RegexInvert: args.RegexInvert,
		Timeout:     args.Timeout,
	}
}

// Commands returns the legacy command stream for this session specification.
func (s Spec) Commands() ([]string, error) {
	switch {
	case s.Mode == omode.HealthClient:
		return []string{"health"}, nil
	case s.Query != "":
		return s.queryCommands()
	default:
		return s.readCommands(s.Mode.String())
	}
}

// StartCommand returns the SESSION START command for this specification.
func (s Spec) StartCommand() (string, error) {
	payload, err := s.encodedPayload()
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("SESSION START %s", payload), nil
}

// UpdateCommand returns the SESSION UPDATE command for this specification.
func (s Spec) UpdateCommand(generation uint64) (string, error) {
	payload, err := s.encodedPayload()
	if err != nil {
		return "", err
	}

	if generation == 0 {
		return fmt.Sprintf("SESSION UPDATE %s", payload), nil
	}

	return fmt.Sprintf("SESSION UPDATE %d %s", generation, payload), nil
}

func (s Spec) queryCommands() ([]string, error) {
	if s.Mode != omode.MapClient && s.Mode != omode.TailClient {
		return nil, fmt.Errorf("session spec query mode requires map or tail mode, got %s", s.Mode)
	}

	regexValue, err := s.serializedRegex()
	if err != nil {
		return nil, err
	}

	commands := []string{fmt.Sprintf("map:%s %s", s.Options, s.Query)}
	readMode := "cat"
	if s.Mode == omode.TailClient {
		readMode = "tail"
	}

	for _, file := range s.Files {
		if s.Timeout > 0 {
			commands = append(commands, fmt.Sprintf("timeout %d %s %s %s", s.Timeout, readMode, file, regexValue))
			continue
		}
		commands = append(commands, fmt.Sprintf("%s:%s %s %s", readMode, s.Options, file, regexValue))
	}

	return commands, nil
}

func (s Spec) readCommands(mode string) ([]string, error) {
	switch s.Mode {
	case omode.TailClient, omode.CatClient, omode.GrepClient:
	default:
		return nil, fmt.Errorf("unsupported session mode %s", s.Mode)
	}

	regexValue, err := s.serializedRegex()
	if err != nil {
		return nil, err
	}

	var commands []string
	for _, file := range s.Files {
		commands = append(commands, fmt.Sprintf("%s:%s %s %s", mode, s.Options, file, regexValue))
	}

	return commands, nil
}

func (s Spec) serializedRegex() (string, error) {
	flag := regex.Default
	if s.RegexInvert {
		flag = regex.Invert
	}

	re, err := regex.New(s.Regex, flag)
	if err != nil {
		return "", err
	}

	return re.Serialize()
}

func splitFiles(what string) []string {
	if strings.TrimSpace(what) == "" {
		return nil
	}

	rawFiles := strings.Split(what, ",")
	files := make([]string, 0, len(rawFiles))
	for _, file := range rawFiles {
		file = strings.TrimSpace(file)
		if file == "" {
			continue
		}
		files = append(files, file)
	}
	return files
}

func supportsServerlessPipe(mode omode.Mode) bool {
	switch mode {
	case omode.TailClient, omode.CatClient, omode.GrepClient, omode.MapClient:
		return true
	default:
		return false
	}
}

func (s Spec) encodedPayload() (string, error) {
	payload, err := json.Marshal(s)
	if err != nil {
		return "", fmt.Errorf("marshal session spec: %w", err)
	}

	return base64.StdEncoding.EncodeToString(payload), nil
}