Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,11 @@ valar service list
#### Show the logs of the latest deployment

```bash
valar service logs [--follow] [--tail] [--skip n] [service]
valar service logs [--follow] [--tail] [--skip n] [--all | --deployment n] [--timestamps] [--service service]
```

`--all` shows every deployment's log, oldest first, and `--deployment` one deployment's. `--timestamps` prefixes each line with the time it was written. With `--json`, each line is a record such as `{"ts": "...", "deployment": "3", "stream": "output", "line": "..."}`; platform events have `stream: "platform"` with `event` and `attrs`, and further fields may appear. An older platform yields `{"line": "..."}` only. Following records reconnects at the end of the log, so lines written while reconnecting can be missed.

#### Print a service's URLs

Linked custom domains come first, then the service's own `<project>-<service>` domains.
Expand Down
96 changes: 74 additions & 22 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,42 +117,94 @@ func (client *Client) ListServices(project, service string) ([]Service, error) {
return services, nil
}

// StreamServiceLogs streams the logs of the latest service endpoint. A followed
// stream reconnects and resumes if the connection is cut.
func (client *Client) StreamServiceLogs(project, service string, w io.Writer, follow, tail bool, skip int) error {
base := fmt.Sprintf("/projects/%s/services/%s/logs", project, service)
logPath := func(params url.Values) string {
if follow {
params.Set("follow", "true")
params.Set("keepalive", keepaliveInterval.String())
}
return base + "?" + params.Encode()
// LogOptions selects which service log to read and where to start.
type LogOptions struct {
Follow bool
// Tail starts at the end of the log, Skip that many lines further on.
Tail bool
Skip int
// All reads every deployment's log in version order; Deployment reads one
// deployment's. Neither reads the latest deployment's.
All bool
Deployment int
}

// logPath builds the request path for a service log with the given query.
func (opts LogOptions) logPath(project, service string, params url.Values) string {
if opts.Deployment > 0 {
params.Set("deployment", strconv.Itoa(opts.Deployment))
}
if opts.Follow {
params.Set("follow", "true")
params.Set("keepalive", keepaliveInterval.String())
}
return fmt.Sprintf("/projects/%s/services/%s/logs?%s", project, service, params.Encode())
}

// start is the query of the first request. The server refuses all combined
// with seek or skip.
func (opts LogOptions) start() url.Values {
if opts.All {
return url.Values{"all": {"true"}}
}
seek := "start"
if tail {
if opts.Tail {
seek = "end"
}
start := url.Values{"seek": {seek}, "skip": {strconv.Itoa(skip)}}
if !follow {
return client.streamOnce(logPath(start), w)
return url.Values{"seek": {seek}, "skip": {strconv.Itoa(opts.Skip)}}
}

// StreamServiceLogs writes a service log as plain text. A followed stream
// reconnects and resumes if the connection is cut.
func (client *Client) StreamServiceLogs(project, service string, w io.Writer, opts LogOptions) error {
if !opts.Follow {
return client.streamOnce(opts.logPath(project, service, opts.start()), w)
}
// A stream that starts at the beginning of the log resumes at an exact byte
// offset. One anchored to the end of the log, or started at a line offset,
// has no absolute position to resume from, so it re-anchors to the current
// end and may miss lines written while reconnecting.
exact := !tail && skip == 0
// A stream that starts at the beginning of one deployment's log resumes at
// an exact byte offset. One anchored to the end of the log, started at a
// line offset or spanning all deployments has no absolute position to
// resume from, so it re-anchors to the current end and may miss lines
// written while reconnecting.
exact := !opts.Tail && opts.Skip == 0 && !opts.All
return client.follow(followOptions{path: func(resumeAfter int) string {
switch {
case resumeAfter == 0:
return logPath(start)
return opts.logPath(project, service, opts.start())
case exact:
return logPath(url.Values{"seek": {"start"}, "offset": {strconv.Itoa(resumeAfter)}})
return opts.logPath(project, service, url.Values{"seek": {"start"}, "offset": {strconv.Itoa(resumeAfter)}})
default:
return logPath(url.Values{"seek": {"end"}})
return opts.logPath(project, service, url.Values{"seek": {"end"}})
}
}}, w)
}

// StreamServiceLogRecords passes a service log to emit one record at a time.
// Against a server that answers in plain text, each record holds only a line.
func (client *Client) StreamServiceLogRecords(project, service string, opts LogOptions, emit func(LogRecord) error) error {
path := func(params url.Values) string {
params.Set("format", "json")
return opts.logPath(project, service, params)
}
if !opts.Follow {
return client.streamRecordsOnce(path(opts.start()), emit)
}
delivered := 0
count := func(record LogRecord) error {
delivered++
return emit(record)
}
started := false
return client.reconnect(func() error {
params := opts.start()
if started {
// Records have no resume cursor yet, so a reconnect re-anchors to the end.
params = url.Values{"seek": {"end"}}
}
started = true
return client.streamRecordsOnce(path(params), count)
}, func() int { return delivered }, false)
}

// SubmitArtifact submits a new build input artifact to the server.
func (client *Client) SubmitArtifact(project, service, kind string, archive io.ReadCloser) (*Artifact, error) {
var (
Expand Down
186 changes: 168 additions & 18 deletions api/logstream.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -63,21 +64,29 @@ type followOptions struct {
finite bool
}

// follow streams a log, reconnecting when the connection is cut. A follow can
// idle for minutes at a time and intermediaries routinely drop idle
// connections, so a cut is expected rather than fatal.
// follow streams a log, reconnecting when the connection is cut.
func (client *Client) follow(opts followOptions, w io.Writer) error {
counter := &countingWriter{w: w}
return client.reconnect(func() error {
return client.streamOnce(opts.path(counter.bytes), counter)
}, func() int { return counter.bytes }, opts.finite)
}

// reconnect runs once again whenever its stream is cut, until the stream ends
// for good. delivered reports how much has come through so far. A follow can
// idle for minutes at a time and intermediaries routinely drop idle
// connections, so a cut is expected rather than fatal.
func (client *Client) reconnect(once func() error, delivered func() int, finite bool) error {
for tries := 0; ; {
before := counter.bytes
err := client.streamOnce(opts.path(counter.bytes), counter)
if err == nil && opts.finite {
before := delivered()
err := once()
if err == nil && finite {
return nil
}
if !retryable(err) {
return err
}
if counter.bytes > before {
if delivered() > before {
tries = 0
} else if tries++; tries >= maxReconnectTries {
// Nothing is coming through; report it rather than spin or, worse,
Expand Down Expand Up @@ -106,37 +115,59 @@ func reconnectDelay(tries int) time.Duration {
return delay
}

// streamOnce runs a single streaming request, decoding framed responses and
// copying raw ones. A nil error means the server closed the stream.
func (client *Client) streamOnce(path string, w io.Writer) error {
// openStream starts a streaming request and reports whether its response is
// framed. A response the server refused becomes an error.
func (client *Client) openStream(path string) (io.ReadCloser, bool, error) {
req, err := http.NewRequest(http.MethodGet, client.Endpoint+path, nil)
if err != nil {
return fmt.Errorf("client request: %w", err)
return nil, false, fmt.Errorf("client request: %w", err)
}
req.Header.Add("Authorization", "Bearer "+client.Token)

resp, err := client.stream.Do(req)
if err != nil {
return fmt.Errorf("submitting request: %w", err)
return nil, false, fmt.Errorf("submitting request: %w", err)
}
defer resp.Body.Close()
client.noteTokenExpiry(resp.Header)
if resp.StatusCode != http.StatusOK {
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("fetching response: %w", err)
return nil, false, fmt.Errorf("fetching response: %w", err)
}
return client.responseError(resp, body)
return nil, false, client.responseError(resp, body)
}
if contentType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")); err == nil && contentType == logStreamContentType {
return decodeFramedStream(resp.Body, w)
contentType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
return resp.Body, err == nil && contentType == logStreamContentType, nil
}

// streamOnce runs a single streaming request, decoding framed responses and
// copying raw ones. A nil error means the server closed the stream.
func (client *Client) streamOnce(path string, w io.Writer) error {
body, framed, err := client.openStream(path)
if err != nil {
return err
}
if _, err := io.Copy(w, resp.Body); err != nil && err != io.EOF {
defer body.Close()
if framed {
return decodeFramedStream(body, w)
}
if _, err := io.Copy(w, body); err != nil && err != io.EOF {
return fmt.Errorf("copying request: %w", err)
}
return nil
}

// streamRecordsOnce runs a single streaming request for log records.
func (client *Client) streamRecordsOnce(path string, emit func(LogRecord) error) error {
body, framed, err := client.openStream(path)
if err != nil {
return err
}
defer body.Close()
return decodeRecords(body, framed, emit)
}

// decodeFramedStream writes framed log payloads to w and drops keepalives.
func decodeFramedStream(r io.Reader, w io.Writer) error {
scanner := bufio.NewScanner(r)
Expand All @@ -162,3 +193,122 @@ func decodeFramedStream(r io.Reader, w io.Writer) error {
}
return nil
}

// LogRecord is one line of a service log. Raw is the record exactly as the
// server sent it, unknown fields included; it is nil for a line the server
// sent as plain text.
type LogRecord struct {
TS string `json:"ts,omitempty"`
Deployment string `json:"deployment,omitempty"`
Stream string `json:"stream,omitempty"`
Line string `json:"line"`
Raw json.RawMessage `json:"-"`
}

// recordLine is any line of a newline-delimited JSON log response: a record,
// a keepalive or, from a server without records, a frame of text.
type recordLine struct {
TS string `json:"ts"`
Deployment string `json:"deployment"`
Stream string `json:"stream"`
Line *string `json:"line"`
Keepalive bool `json:"keepalive"`
Data []byte `json:"data"`
}

// decodeRecords passes the records of a log response to emit. A server that
// predates records answers in plain text, or in text frames when framed;
// each line of that text becomes a record holding only the line. An unframed
// response is taken as records if its first non-empty line is one.
func decodeRecords(r io.Reader, framed bool, emit func(LogRecord) error) error {
text := &TextRecords{Emit: emit}
var pending []string
decided := framed
scanner := bufio.NewScanner(r)
scanner.Buffer(make([]byte, 0, bufio.MaxScanTokenSize), maxLogFrameSize)
for scanner.Scan() {
line := scanner.Bytes()
if !decided {
if len(bytes.TrimSpace(line)) == 0 {
pending = append(pending, string(line))
continue
}
var probe recordLine
framed = json.Unmarshal(line, &probe) == nil && probe.Line != nil
decided = true
if !framed {
for _, blank := range pending {
if _, err := text.Write([]byte(blank + "\n")); err != nil {
return err
}
}
}
}
if !framed {
if _, err := text.Write(append(line, '\n')); err != nil {
return err
}
continue
}
if len(line) == 0 {
continue
}
var decoded recordLine
if err := json.Unmarshal(line, &decoded); err != nil {
return fmt.Errorf("decoding log record: %w", err)
}
switch {
case decoded.Keepalive:
case decoded.Line != nil:
record := LogRecord{
TS: decoded.TS,
Deployment: decoded.Deployment,
Stream: decoded.Stream,
Line: *decoded.Line,
Raw: bytes.Clone(line),
}
if err := emit(record); err != nil {
return err
}
case decoded.Data != nil:
if _, err := text.Write(decoded.Data); err != nil {
return err
}
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading log stream: %w", err)
}
return text.Flush()
}

// TextRecords turns text into one record per line, passed to Emit. Flush
// emits a final line that has no line break.
type TextRecords struct {
Emit func(LogRecord) error
buf []byte
}

func (tr *TextRecords) Write(b []byte) (int, error) {
tr.buf = append(tr.buf, b...)
for {
i := bytes.IndexByte(tr.buf, '\n')
if i < 0 {
return len(b), nil
}
line := bytes.TrimSuffix(tr.buf[:i], []byte("\r"))
if err := tr.Emit(LogRecord{Line: string(line)}); err != nil {
return 0, err
}
tr.buf = tr.buf[i+1:]
}
}

func (tr *TextRecords) Flush() error {
if len(tr.buf) == 0 {
return nil
}
line := string(tr.buf)
tr.buf = nil
return tr.Emit(LogRecord{Line: line})
}
Loading