github.com/vmware/govmomi@v0.43.0/vim25/progress/loger.go (about) 1 /* 2 Copyright (c) 2024-2024 VMware, Inc. All Rights Reserved. 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 progress 18 19 import ( 20 "fmt" 21 "io" 22 "sync" 23 "time" 24 ) 25 26 type LogFunc func(msg string) (int, error) 27 28 type ProgressLogger struct { 29 log LogFunc 30 prefix string 31 32 wg sync.WaitGroup 33 34 sink chan chan Report 35 done chan struct{} 36 } 37 38 func NewProgressLogger(log LogFunc, prefix string) *ProgressLogger { 39 p := &ProgressLogger{ 40 log: log, 41 prefix: prefix, 42 43 sink: make(chan chan Report), 44 done: make(chan struct{}), 45 } 46 47 p.wg.Add(1) 48 49 go p.loopA() 50 51 return p 52 } 53 54 // loopA runs before Sink() has been called. 55 func (p *ProgressLogger) loopA() { 56 var err error 57 58 defer p.wg.Done() 59 60 tick := time.NewTicker(100 * time.Millisecond) 61 defer tick.Stop() 62 63 called := false 64 65 for stop := false; !stop; { 66 select { 67 case ch := <-p.sink: 68 err = p.loopB(tick, ch) 69 stop = true 70 called = true 71 case <-p.done: 72 stop = true 73 case <-tick.C: 74 line := fmt.Sprintf("\r%s", p.prefix) 75 p.log(line) 76 } 77 } 78 79 if err != nil && err != io.EOF { 80 p.log(fmt.Sprintf("\r%sError: %s\n", p.prefix, err)) 81 } else if called { 82 p.log(fmt.Sprintf("\r%sOK\n", p.prefix)) 83 } 84 } 85 86 // loopA runs after Sink() has been called. 87 func (p *ProgressLogger) loopB(tick *time.Ticker, ch <-chan Report) error { 88 var r Report 89 var ok bool 90 var err error 91 92 for ok = true; ok; { 93 select { 94 case r, ok = <-ch: 95 if !ok { 96 break 97 } 98 err = r.Error() 99 case <-tick.C: 100 line := fmt.Sprintf("\r%s", p.prefix) 101 if r != nil { 102 line += fmt.Sprintf("(%.0f%%", r.Percentage()) 103 detail := r.Detail() 104 if detail != "" { 105 line += fmt.Sprintf(", %s", detail) 106 } 107 line += ")" 108 } 109 p.log(line) 110 } 111 } 112 113 return err 114 } 115 116 func (p *ProgressLogger) Sink() chan<- Report { 117 ch := make(chan Report) 118 p.sink <- ch 119 return ch 120 } 121 122 func (p *ProgressLogger) Wait() { 123 close(p.done) 124 p.wg.Wait() 125 }