yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/multicloud/progress.go (about)

     1  // Copyright 2019 Yunion
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package multicloud
    16  
    17  import (
    18  	"io"
    19  	"time"
    20  )
    21  
    22  func NewProgress(totalSize int64, maxPercent int, reader io.Reader, callback func(progress float32)) io.Reader {
    23  	body := &sProgress{
    24  		total:      totalSize,
    25  		maxPercent: maxPercent,
    26  		callback:   callback,
    27  	}
    28  	return io.TeeReader(reader, body)
    29  }
    30  
    31  type sProgress struct {
    32  	refreshSeconds int
    33  	count          int64
    34  	total          int64
    35  	start          time.Time
    36  	callback       func(progress float32)
    37  	maxPercent     int
    38  }
    39  
    40  func (r *sProgress) Write(p []byte) (int, error) {
    41  	if r.start.IsZero() {
    42  		r.start = time.Now()
    43  	}
    44  	n := len(p)
    45  	r.count += int64(n)
    46  	if r.callback != nil && r.total > 0 && time.Now().Sub(r.start) > time.Second*1 {
    47  		r.callback(float32(float64(r.count) / float64(r.total) * float64(r.maxPercent)))
    48  		r.start = time.Now()
    49  	}
    50  	return n, nil
    51  }