github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/build/cluster/logs.go (about) 1 /* 2 Copyright 2019 The Skaffold Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package cluster 18 19 import ( 20 "bufio" 21 "context" 22 "fmt" 23 "io" 24 "sync" 25 "sync/atomic" 26 "time" 27 28 v1 "k8s.io/api/core/v1" 29 corev1 "k8s.io/client-go/kubernetes/typed/core/v1" 30 31 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/kaniko" 32 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" 33 ) 34 35 func streamLogs(ctx context.Context, out io.Writer, name string, pods corev1.PodInterface) func() { 36 var wg sync.WaitGroup 37 wg.Add(1) 38 39 var written int64 40 var retry int32 = 1 41 go func() { 42 defer wg.Done() 43 44 for atomic.LoadInt32(&retry) == 1 { 45 r, err := pods.GetLogs(name, &v1.PodLogOptions{ 46 Follow: true, 47 Container: kaniko.DefaultContainerName, 48 }).Stream(ctx) 49 if err != nil { 50 log.Entry(ctx).Debug("unable to get kaniko pod logs:", err) 51 time.Sleep(1 * time.Second) 52 continue 53 } 54 55 scanner := bufio.NewScanner(r) 56 for { 57 select { 58 case <-ctx.Done(): 59 return // The build was cancelled 60 default: 61 if !scanner.Scan() { 62 return // No more logs 63 } 64 65 fmt.Fprintln(out, scanner.Text()) 66 atomic.AddInt64(&written, 1) 67 } 68 } 69 } 70 }() 71 72 return func() { 73 atomic.StoreInt32(&retry, 0) 74 wg.Wait() 75 76 // get latest logs if pod was terminated before logs have been streamed 77 if atomic.LoadInt64(&written) == 0 { 78 r, err := pods.GetLogs(name, &v1.PodLogOptions{ 79 Container: kaniko.DefaultContainerName, 80 }).Stream(ctx) 81 if err == nil { 82 io.Copy(out, r) 83 } 84 } 85 } 86 }