forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logs.go
176 lines (159 loc) · 4.5 KB
/
logs.go
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
package cmd
import (
"fmt"
"io"
"time"
"github.com/spf13/cobra"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/util"
"k8s.io/client-go/kubernetes"
cmdutil "github.com/jenkins-x/jx/pkg/jx/cmd/util"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type LogsOptions struct {
CommonOptions
Container string
Namespace string
Filter string
}
var (
logs_long = templates.LongDesc(`
Tails the logs of the newest pod for a Deployment.
`)
logs_example = templates.Examples(`
# Tails the log of the latest pod in deployment myapp
jx logs myapp
# Tails the log of the container foo in the latest pod in deployment myapp
jx logs myapp -c foo
`)
)
func NewCmdLogs(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := &LogsOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
}
cmd := &cobra.Command{
Use: "logs [deployment]",
Short: "Tails the log of the latest pod for a deployment",
Long: logs_long,
Example: logs_example,
Aliases: []string{"log"},
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
cmdutil.CheckErr(err)
},
}
cmd.Flags().StringVarP(&options.Container, "container", "c", "", "The name of the container to log")
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", "", "the namespace to look for the Deployment. Defaults to the current namespace")
cmd.Flags().StringVarP(&options.Filter, "filter", "f", "", "Fitlers the available deployments if no deployment argument is provided")
return cmd
}
func (o *LogsOptions) Run() error {
args := o.Args
client, curNs, err := o.Factory.CreateClient()
if err != nil {
return err
}
ns := o.Namespace
if ns == "" {
ns = curNs
}
names, err := kube.GetDeploymentNames(client, ns, o.Filter)
if err != nil {
return err
}
if len(names) == 0 {
if o.Filter == "" {
return fmt.Errorf("There are no Deployments")
} else {
return fmt.Errorf("There are no Deployments matching filter: " + o.Filter)
}
}
name := ""
if len(args) == 0 {
n, err := util.PickName(names, "Pick Deployment:")
if err != nil {
return err
}
name = n
} else {
name = args[0]
if util.StringArrayIndex(names, name) < 0 {
return util.InvalidArg(name, names)
}
}
for {
pod, err := waitForReadyPodForDeployment(client, ns, name, names)
if err != nil {
return err
}
if pod == "" {
return fmt.Errorf("No pod found for namespace %s with name %s", ns, name)
}
args := []string{"logs", "-n", ns, "-f"}
if o.Container != "" {
args = append(args, "-c", o.Container)
}
args = append(args, pod)
err = o.runCommand("kubectl", args...)
if err != nil {
return nil
}
}
}
// waitForReadyPodForDeployment waits for a ready pod in a Deployment in the given namespace with the given name
func waitForReadyPodForDeployment(c *kubernetes.Clientset, ns string, name string, names []string) (string, error) {
deployment, err := c.AppsV1beta2().Deployments(ns).Get(name, metav1.GetOptions{})
if err != nil || deployment == nil {
return "", util.InvalidArg(name, names)
}
selector := deployment.Spec.Selector
if selector == nil {
return "", fmt.Errorf("No selector defined on Deployment %s in namespace %s", name, ns)
}
labels := selector.MatchLabels
if labels == nil {
return "", fmt.Errorf("No MatchLabels defined on the Selector of Deployment %s in namespace %s", name, ns)
}
return waitForReadyPodForSelector(c, ns, labels)
}
func waitForReadyPodForSelector(c *kubernetes.Clientset, ns string, labels map[string]string) (string, error) {
selector, err := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{MatchLabels: labels})
if err != nil {
return "", err
}
fmt.Printf(util.ColorStatus("Waiting for a running pod in namespace %s with labels %v\n"), ns, labels)
for {
pods, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{
LabelSelector: selector.String(),
})
if err != nil {
return "", err
}
name := ""
lastTime := time.Time{}
for _, pod := range pods.Items {
phase := pod.Status.Phase
if phase == corev1.PodRunning {
created := pod.CreationTimestamp
if name == "" || created.After(lastTime) {
lastTime = created.Time
name = pod.Name
}
}
}
if name != "" {
fmt.Printf(util.ColorStatus("Found newest pod: %s\n"), util.ColorInfo(name))
return name, nil
}
// TODO replace with a watch flavour
time.Sleep(time.Second)
}
}