/
utils.go
176 lines (153 loc) · 4.33 KB
/
utils.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 2014 The Serviced 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 volume
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/user"
"path/filepath"
"sort"
"strings"
"syscall"
"html/template"
"github.com/docker/go-units"
"github.com/zenoss/glog"
)
var (
ErrNotADirectory = errors.New("not a directory")
ErrBtrfsCommand = errors.New("error running btrfs command")
)
const FlagFileName = ".initialized"
// IsDir() checks if the given dir is a directory. If any error is encoutered
// it is returned and directory is set to false.
func IsDir(dirName string) (dir bool, err error) {
if lstat, err := os.Lstat(dirName); err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
} else {
if !lstat.IsDir() {
return false, ErrNotADirectory
}
}
return true, nil
}
// FileInfoSlice is a os.FileInfo array sortable by modification time
type FileInfoSlice []os.FileInfo
func (p FileInfoSlice) Len() int {
return len(p)
}
func (p FileInfoSlice) Less(i, j int) bool {
return p[i].ModTime().Before(p[j].ModTime())
}
func (p FileInfoSlice) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
// Labels will return the names of the files in the slice, sorted by modification time
func (p FileInfoSlice) Labels() []string {
// This would probably be very slightly more efficient with a heap, but the
// API would be more complicated
sort.Sort(p)
labels := make([]string, p.Len())
for i, label := range p {
labels[i] = label.Name()
}
return labels
}
func IsRoot() bool {
user, err := user.Current()
if err != nil {
glog.Errorf("Unable to determine current user: %s", err)
return false
}
return user.Uid == "0"
}
func IsSudoer() bool {
if !IsRoot() {
err := exec.Command("sudo", "-n", "true").Run()
return err == nil
}
return false
}
// RunBtrFSCmd runs a btrfs command, optionally using sudo
func RunBtrFSCmd(sudoer bool, args ...string) ([]byte, error) {
cmd := append([]string{"btrfs"}, args...)
if sudoer {
cmd = append([]string{"sudo", "-n"}, cmd...)
}
glog.V(4).Infof("Executing: %v", cmd)
output, err := exec.Command(cmd[0], cmd[1:]...).CombinedOutput()
if err != nil {
glog.V(1).Infof("unable to run cmd:%s output:%s error:%s", cmd, string(output), err)
return output, ErrBtrfsCommand
}
return output, err
}
// IsBtrfsFilesystem determines whether the path is a btrfs filesystem
func IsBtrfsFilesystem(path string) bool {
_, err := RunBtrFSCmd(false, "filesystem", "df", path)
return err == nil
}
func FlagFilePath(root string) string {
return filepath.Join(root, FlagFileName)
}
func TouchFlagFile(root string) error {
// Touch the file indicating that this dir has been initialized
initfile := FlagFilePath(root)
if _, err := os.Stat(initfile); os.IsNotExist(err) {
return ioutil.WriteFile(initfile, []byte{}, 0754)
}
return nil
}
func FilesystemBytesSize(path string) uint64 {
s := syscall.Statfs_t{}
syscall.Statfs(path, &s)
return uint64(s.Bsize) * uint64(s.Blocks)
}
func FilesystemBytesAvailable(path string) uint64 {
s := syscall.Statfs_t{}
syscall.Statfs(path, &s)
return uint64(s.Bavail) * uint64(s.Bsize)
}
func FilesystemBytesUsed(path string) uint64 {
s := syscall.Statfs_t{}
syscall.Statfs(path, &s)
return (uint64(s.Blocks) - uint64(s.Bavail)) * uint64(s.Bsize)
}
func DefaultSnapshotLabel(tenant, label string) string {
prefix := tenant + "_"
if !strings.HasPrefix(label, prefix) {
label = prefix + label
}
return label
}
const blockSize uint64 = 64 * 1024
func ToBytes(from uint64) string {
return units.BytesSize(float64(from))
}
func BlocksToBytes(blocks uint64) string {
return ToBytes(blockSize * blocks)
}
func Percent(amt, total uint64) string {
return fmt.Sprintf("%.2g%%", 100*(float64(amt)/float64(total)))
}
func BytesToBlocks(bytes uint64) uint64 {
return bytes / blockSize
}
func Noescape(s string) template.HTML {
return template.HTML(s)
}