-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Stream logs from deployed containers #30
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
/* | ||
Copyright 2018 Google LLC | ||
|
||
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 kubernetes | ||
|
||
import ( | ||
"bufio" | ||
"fmt" | ||
"io" | ||
"time" | ||
|
||
"github.com/pkg/errors" | ||
"github.com/sirupsen/logrus" | ||
"k8s.io/api/core/v1" | ||
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
corev1 "k8s.io/client-go/kubernetes/typed/core/v1" | ||
restclient "k8s.io/client-go/rest" | ||
) | ||
|
||
const streamRetryDelay = 1 * time.Second | ||
|
||
// TODO(@r2d4): Figure out how to mock this out. fake.NewSimpleClient | ||
// won't mock out restclient.Request and will just return a nil stream. | ||
var getStream = func(r *restclient.Request) (io.ReadCloser, error) { | ||
return r.Stream() | ||
} | ||
|
||
func StreamLogsRetry(out io.Writer, client corev1.CoreV1Interface, image string, retry int) { | ||
for i := 0; i < retry; i++ { | ||
if err := StreamLogs(out, client, image); err != nil { | ||
logrus.Infof("Error getting logs %s", err) | ||
} | ||
time.Sleep(streamRetryDelay) | ||
} | ||
} | ||
|
||
// nolint: interfacer | ||
func StreamLogs(out io.Writer, client corev1.CoreV1Interface, image string) error { | ||
pods, err := client.Pods("").List(meta_v1.ListOptions{ | ||
IncludeUninitialized: true, | ||
}) | ||
if err != nil { | ||
return errors.Wrap(err, "getting pods") | ||
} | ||
logrus.Infof("Looking for logs to stream for %s", image) | ||
for _, p := range pods.Items { | ||
for _, c := range p.Spec.Containers { | ||
logrus.Debugf("Found container %s with image %s", c.Name, c.Image) | ||
if c.Image == image { | ||
logrus.Infof("Trying to stream logs from pod: %s container: %s", p.Name, c.Name) | ||
pods := client.Pods(p.Namespace) | ||
if err := WaitForPodReady(pods, p.Name); err != nil { | ||
return errors.Wrap(err, "waiting for pod ready") | ||
} | ||
req := client.Pods(p.Namespace).GetLogs(p.Name, &v1.PodLogOptions{ | ||
Follow: true, | ||
Container: c.Name, | ||
SinceTime: &meta_v1.Time{Time: time.Now()}, | ||
}) | ||
rc, err := getStream(req) | ||
if err != nil { | ||
return errors.Wrap(err, "setting up container log stream") | ||
} | ||
defer rc.Close() | ||
header := fmt.Sprintf("[%s %s]", p.Name, c.Name) | ||
if err := streamRequest(out, header, rc); err != nil { | ||
return errors.Wrap(err, "streaming request") | ||
} | ||
|
||
return nil | ||
} | ||
} | ||
} | ||
|
||
return fmt.Errorf("Image %s not found", image) | ||
} | ||
|
||
func streamRequest(out io.Writer, header string, rc io.Reader) error { | ||
r := bufio.NewReader(rc) | ||
for { | ||
// Read up to newline | ||
line, err := r.ReadBytes('\n') | ||
if err == io.EOF { | ||
break | ||
} | ||
if err != nil { | ||
return errors.Wrap(err, "reading bytes from log stream") | ||
} | ||
msg := fmt.Sprintf("%s %s", header, line) | ||
if _, err := out.Write([]byte(msg)); err != nil { | ||
return errors.Wrap(err, "writing to out") | ||
} | ||
} | ||
logrus.Infof("%s exited", header) | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
/* | ||
Copyright 2018 Google LLC | ||
|
||
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 kubernetes | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"io" | ||
"testing" | ||
|
||
"github.com/GoogleCloudPlatform/skaffold/testutil" | ||
v1 "k8s.io/api/core/v1" | ||
"k8s.io/client-go/kubernetes/fake" | ||
restclient "k8s.io/client-go/rest" | ||
) | ||
|
||
func errorGetStream(r *restclient.Request) (io.ReadCloser, error) { | ||
return nil, fmt.Errorf("error stream") | ||
} | ||
|
||
func fakeGetStream(r *restclient.Request) (io.ReadCloser, error) { | ||
b := bytes.NewBufferString("logs\nlogs\nlogs\n") | ||
return closerBuffer{b}, nil | ||
} | ||
|
||
func getStreamWithError(r *restclient.Request) (io.ReadCloser, error) { | ||
return closerBuffer{testutil.BadReader{}}, nil | ||
} | ||
|
||
type closerBuffer struct { | ||
io.Reader | ||
} | ||
|
||
func (closerBuffer) Close() error { return nil } | ||
|
||
func TestStreamLogs(t *testing.T) { | ||
var tests = []struct { | ||
description string | ||
initialObj *v1.Pod | ||
getStream func(r *restclient.Request) (io.ReadCloser, error) | ||
out io.Writer | ||
|
||
shouldErr bool | ||
}{ | ||
{ | ||
description: "get logs no error", | ||
initialObj: podReadyState, | ||
getStream: fakeGetStream, | ||
out: &bytes.Buffer{}, | ||
}, | ||
{ | ||
description: "pod bad state", | ||
initialObj: podBadPhase, | ||
getStream: fakeGetStream, | ||
out: &bytes.Buffer{}, | ||
shouldErr: true, | ||
}, | ||
{ | ||
description: "error getting stream", | ||
initialObj: podReadyState, | ||
getStream: errorGetStream, | ||
out: &bytes.Buffer{}, | ||
shouldErr: true, | ||
}, | ||
{ | ||
description: "error reading stream", | ||
initialObj: podReadyState, | ||
getStream: getStreamWithError, | ||
out: &bytes.Buffer{}, | ||
shouldErr: true, | ||
}, | ||
{ | ||
description: "error bad writer", | ||
initialObj: podReadyState, | ||
getStream: fakeGetStream, | ||
out: testutil.BadWriter{}, | ||
shouldErr: true, | ||
}, | ||
} | ||
|
||
for _, test := range tests { | ||
t.Run(test.description, func(t *testing.T) { | ||
client := fake.NewSimpleClientset(test.initialObj) | ||
getStream = test.getStream | ||
err := StreamLogs(test.out, client.CoreV1(), "image_name") | ||
testutil.CheckError(t, test.shouldErr, err) | ||
}) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we put these into the Pods("") query instead of doing the selection here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think that field selectors support anything nested like container image fields. I couldn't find any examples of this