-
Notifications
You must be signed in to change notification settings - Fork 254
/
util.go
89 lines (77 loc) · 2.26 KB
/
util.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
package util
import (
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"strings"
"syscall"
"time"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/apis/meta/v1"
)
// CountingReader is a reader that keeps track of how much has been read
type CountingReader struct {
Reader io.ReadCloser
Current int64
}
// RandAlphaNum provides an implementation to generate a random alpha numeric string of the specified length
func RandAlphaNum(n int) string {
rand.Seed(time.Now().UnixNano())
var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, n)
for i := range b {
b[i] = letter[rand.Intn(len(letter))]
}
return string(b)
}
// GetNamespace returns the namespace the pod is executing in
func GetNamespace() string {
return getNamespace("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
}
func getNamespace(path string) string {
if data, err := ioutil.ReadFile(path); err == nil {
if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
return ns
}
}
return v1.NamespaceSystem
}
// ParseEnvVar provides a wrapper to attempt to fetch the specified env var
func ParseEnvVar(envVarName string, decode bool) (string, error) {
value := os.Getenv(envVarName)
if decode {
v, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return "", errors.Errorf("error decoding environment variable %q", envVarName)
}
value = fmt.Sprintf("%s", v)
}
return value, nil
}
// Read reads bytes from the stream and updates the prometheus clone_progress metric according to the progress.
func (r *CountingReader) Read(p []byte) (n int, err error) {
n, err = r.Reader.Read(p)
r.Current += int64(n)
return n, err
}
// Close closes the stream
func (r *CountingReader) Close() error {
return r.Reader.Close()
}
// GetAvailableSpace gets the amount of available space at the path specified.
func GetAvailableSpace(path string) int64 {
var stat syscall.Statfs_t
syscall.Statfs(path, &stat)
return int64(stat.Bavail) * int64(stat.Bsize)
}
// MinQuantity calculates the minimum of two quantities.
func MinQuantity(availableSpace, imageSize *resource.Quantity) resource.Quantity {
if imageSize.Cmp(*availableSpace) == 1 {
return *availableSpace
}
return *imageSize
}