-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathannotation_scraper.go
176 lines (156 loc) · 4.66 KB
/
annotation_scraper.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
/*
* Copyright the original author or authors.
*
* 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 log
import (
"bufio"
"context"
"fmt"
"io"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/citrusframework/yaks/pkg/util/log"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
// SelectorScraper scrapes all pods with a given selector.
type SelectorScraper struct {
client kubernetes.Interface
namespace string
defaultContainerName string
labelSelector string
podScrapers sync.Map
counter uint64
L log.Logger
}
// NewSelectorScraper creates a new SelectorScraper.
func NewSelectorScraper(client kubernetes.Interface, namespace string, defaultContainerName string, labelSelector string) *SelectorScraper {
return &SelectorScraper{
client: client,
namespace: namespace,
defaultContainerName: defaultContainerName,
labelSelector: labelSelector,
L: log.WithName("scraper").WithName("label").WithValues("selector", labelSelector),
}
}
// Start returns a reader that streams the log of all selected pods.
func (s *SelectorScraper) Start(ctx context.Context) *bufio.Reader {
pipeIn, pipeOut := io.Pipe()
bufPipeIn := bufio.NewReader(pipeIn)
bufPipeOut := bufio.NewWriter(pipeOut)
closeFun := func() error {
bufPipeOut.Flush()
return pipeOut.Close()
}
go s.periodicSynchronize(ctx, bufPipeOut, closeFun)
return bufPipeIn
}
func (s *SelectorScraper) periodicSynchronize(ctx context.Context, out *bufio.Writer, clientCloser func() error) {
if err := s.synchronize(ctx, out); err != nil {
s.L.Info("Could not synchronize log")
}
select {
case <-ctx.Done():
// cleanup
s.podScrapers.Range(func(_, v interface{}) bool {
if canc, isCanc := v.(context.CancelFunc); isCanc {
canc()
}
return true
})
if err := clientCloser(); err != nil {
s.L.Error(err, "Unable to close the client")
}
case <-time.After(2 * time.Second):
go s.periodicSynchronize(ctx, out, clientCloser)
}
}
func (s *SelectorScraper) synchronize(ctx context.Context, out *bufio.Writer) error {
pods, err := s.listPods(ctx)
if err != nil {
return err
}
present := make(map[string]bool)
for _, pod := range pods.Items {
if pod.Status.Phase == corev1.PodRunning || pod.Status.Phase == corev1.PodPending {
present[pod.Name] = true
if _, ok := s.podScrapers.Load(pod.Name); !ok {
s.addPodScraper(ctx, pod.Name, out)
}
}
}
toBeRemoved := make(map[string]bool)
s.podScrapers.Range(func(k, _ interface{}) bool {
if str, isStr := k.(string); isStr {
if _, ok := present[str]; !ok {
toBeRemoved[str] = true
}
}
return true
})
for podName := range toBeRemoved {
if scr, ok := s.podScrapers.Load(podName); ok {
if canc, ok2 := scr.(context.CancelFunc); ok2 {
canc()
s.podScrapers.Delete(podName)
}
}
}
return nil
}
func (s *SelectorScraper) addPodScraper(ctx context.Context, podName string, out *bufio.Writer) {
podScraper := NewPodScraper(s.client, s.namespace, podName, s.defaultContainerName)
podCtx, podCancel := context.WithCancel(ctx)
id := atomic.AddUint64(&s.counter, 1)
prefix := fmt.Sprintf("[%s %s-%s] ", podName, s.defaultContainerName, strconv.FormatUint(id, 10))
podReader := podScraper.Start(podCtx)
s.podScrapers.Store(podName, podCancel)
go func() {
defer podCancel()
if _, err := out.WriteString(prefix + "Monitoring pod " + podName + "\n"); err != nil {
s.L.Error(err, "Cannot write to output")
return
}
for {
str, err := podReader.ReadString('\n')
if err == io.EOF {
return
} else if err != nil {
s.L.Error(err, "Cannot read from pod stream")
return
}
if _, err := out.WriteString(prefix + str); err != nil {
s.L.Error(err, "Cannot write to output")
return
}
out.Flush()
if podCtx.Err() != nil {
return
}
}
}()
}
func (s *SelectorScraper) listPods(ctx context.Context) (*corev1.PodList, error) {
list, err := s.client.CoreV1().Pods(s.namespace).List(ctx, metav1.ListOptions{
LabelSelector: s.labelSelector,
})
if err != nil {
return nil, err
}
return list, nil
}