Debian Codegraph @

utils.go

raw symbols SCIP
1 package zfs
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8 "os/exec"
9 "regexp"
10 "runtime"
11 "strconv"
12 "strings"
13
14 "github.com/google/uuid"
15 )
16
17 type command struct {
18 Command string
19 Stdin io.Reader
20 Stdout io.Writer
21 }
22
23 func (c *command) Run(arg ...string) ([][]string, error) {
24 cmd := exec.Command(c.Command, arg...)
25
26 var stdout, stderr bytes.Buffer
27
28 if c.Stdout == nil {
29 cmd.Stdout = &stdout
30 } else {
31 cmd.Stdout = c.Stdout
32 }
33
34 if c.Stdin != nil {
35 cmd.Stdin = c.Stdin
36 }
37 cmd.Stderr = &stderr
38
39 id := uuid.New().String()
40 joinedArgs := strings.Join(cmd.Args, " ")
41
42 logger.Log([]string{"ID:" + id, "START", joinedArgs})
43 if err := cmd.Run(); err != nil {
44 return nil, &Error{
45 Err: err,
46 Debug: strings.Join([]string{cmd.Path, joinedArgs[1:]}, " "),
47 Stderr: stderr.String(),
48 }
49 }
50 logger.Log([]string{"ID:" + id, "FINISH"})
51
52 // assume if you passed in something for stdout, that you know what to do with it
53 if c.Stdout != nil {
54 return nil, nil
55 }
56
57 lines := strings.Split(stdout.String(), "\n")
58
59 // last line is always blank
60 lines = lines[0 : len(lines)-1]
61 output := make([][]string, len(lines))
62
63 for i, l := range lines {
64 output[i] = strings.Fields(l)
65 }
66
67 return output, nil
68 }
69
70 func setString(field *string, value string) {
71 v := ""
72 if value != "-" {
73 v = value
74 }
75 *field = v
76 }
77
78 func setUint(field *uint64, value string) error {
79 var v uint64
80 if value != "-" {
81 var err error
82 v, err = strconv.ParseUint(value, 10, 64)
83 if err != nil {
84 return err
85 }
86 }
87 *field = v
88 return nil
89 }
90
91 func (d *Dataset) parseLine(line []string) error {
92 var err error
93
94 if len(line) != len(dsPropList) {
95 return errors.New("output does not match what is expected on this platform")
96 }
97 setString(&d.Name, line[0])
98 setString(&d.Origin, line[1])
99
100 if err = setUint(&d.Used, line[2]); err != nil {
101 return err
102 }
103 if err = setUint(&d.Avail, line[3]); err != nil {
104 return err
105 }
106
107 setString(&d.Mountpoint, line[4])
108 setString(&d.Compression, line[5])
109 setString(&d.Type, line[6])
110
111 if err = setUint(&d.Volsize, line[7]); err != nil {
112 return err
113 }
114 if err = setUint(&d.Quota, line[8]); err != nil {
115 return err
116 }
117 if err = setUint(&d.Referenced, line[9]); err != nil {
118 return err
119 }
120
121 if runtime.GOOS == "solaris" {
122 return nil
123 }
124
125 if err = setUint(&d.Written, line[10]); err != nil {
126 return err
127 }
128 if err = setUint(&d.Logicalused, line[11]); err != nil {
129 return err
130 }
131 return setUint(&d.Usedbydataset, line[12])
132 }
133
134 /*
135 * from zfs diff`s escape function:
136 *
137 * Prints a file name out a character at a time. If the character is
138 * not in the range of what we consider "printable" ASCII, display it
139 * as an escaped 3-digit octal value. ASCII values less than a space
140 * are all control characters and we declare the upper end as the
141 * DELete character. This also is the last 7-bit ASCII character.
142 * We choose to treat all 8-bit ASCII as not printable for this
143 * application.
144 */
145 func unescapeFilepath(path string) (string, error) {
146 buf := make([]byte, 0, len(path))
147 llen := len(path)
148 for i := 0; i < llen; {
149 if path[i] == '\\' {
150 if llen < i+4 {
151 return "", fmt.Errorf("invalid octal code: too short")
152 }
153 octalCode := path[(i + 1):(i + 4)]
154 val, err := strconv.ParseUint(octalCode, 8, 8)
155 if err != nil {
156 return "", fmt.Errorf("invalid octal code: %w", err)
157 }
158 buf = append(buf, byte(val))
159 i += 4
160 } else {
161 buf = append(buf, path[i])
162 i++
163 }
164 }
165 return string(buf), nil
166 }
167
168 var changeTypeMap = map[string]ChangeType{
169 "-": Removed,
170 "+": Created,
171 "M": Modified,
172 "R": Renamed,
173 }
174
175 var inodeTypeMap = map[string]InodeType{
176 "B": BlockDevice,
177 "C": CharacterDevice,
178 "/": Directory,
179 ">": Door,
180 "|": NamedPipe,
181 "@": SymbolicLink,
182 "P": EventPort,
183 "=": Socket,
184 "F": File,
185 }
186
187 // matches (+1) or (-1).
188 var referenceCountRegex = regexp.MustCompile(`\(([+-]\d+?)\)`)
189
190 func parseReferenceCount(field string) (int, error) {
191 matches := referenceCountRegex.FindStringSubmatch(field)
192 if matches == nil {
193 return 0, fmt.Errorf("regexp does not match")
194 }
195 return strconv.Atoi(matches[1])
196 }
197
198 func parseInodeChange(line []string) (*InodeChange, error) {
199 llen := len(line) // nolint:ifshort // llen *is* actually used
200 if llen < 1 {
201 return nil, fmt.Errorf("empty line passed")
202 }
203
204 changeType := changeTypeMap[line[0]]
205 if changeType == 0 {
206 return nil, fmt.Errorf("unknown change type '%s'", line[0])
207 }
208
209 switch changeType {
210 case Renamed:
211 if llen != 4 {
212 return nil, fmt.Errorf("mismatching number of fields: expect 4, got: %d", llen)
213 }
214 case Modified:
215 if llen != 4 && llen != 3 {
216 return nil, fmt.Errorf("mismatching number of fields: expect 3..4, got: %d", llen)
217 }
218 default:
219 if llen != 3 {
220 return nil, fmt.Errorf("mismatching number of fields: expect 3, got: %d", llen)
221 }
222 }
223
224 inodeType := inodeTypeMap[line[1]]
225 if inodeType == 0 {
226 return nil, fmt.Errorf("unknown inode type '%s'", line[1])
227 }
228
229 path, err := unescapeFilepath(line[2])
230 if err != nil {
231 return nil, fmt.Errorf("failed to parse filename: %w", err)
232 }
233
234 var newPath string
235 var referenceCount int
236 switch changeType {
237 case Renamed:
238 newPath, err = unescapeFilepath(line[3])
239 if err != nil {
240 return nil, fmt.Errorf("failed to parse filename: %w", err)
241 }
242 case Modified:
243 if llen == 4 {
244 referenceCount, err = parseReferenceCount(line[3])
245 if err != nil {
246 return nil, fmt.Errorf("failed to parse reference count: %w", err)
247 }
248 }
249 default:
250 newPath = ""
251 }
252
253 return &InodeChange{
254 Change: changeType,
255 Type: inodeType,
256 Path: path,
257 NewPath: newPath,
258 ReferenceCountChange: referenceCount,
259 }, nil
260 }
261
262 // example input for parseInodeChanges
263 // M / /testpool/bar/
264 // + F /testpool/bar/hello.txt
265 // M / /testpool/bar/hello.txt (+1)
266 // M / /testpool/bar/hello-hardlink
267
268 func parseInodeChanges(lines [][]string) ([]*InodeChange, error) {
269 changes := make([]*InodeChange, len(lines))
270
271 for i, line := range lines {
272 c, err := parseInodeChange(line)
273 if err != nil {
274 return nil, fmt.Errorf("failed to parse line %d of zfs diff: %w, got: '%s'", i, err, line)
275 }
276 changes[i] = c
277 }
278 return changes, nil
279 }
280
281 func listByType(t, filter string) ([]*Dataset, error) {
282 args := []string{"list", "-rHp", "-t", t, "-o", dsPropListOptions}
283
284 if filter != "" {
285 args = append(args, filter)
286 }
287 out, err := zfsOutput(args...)
288 if err != nil {
289 return nil, err
290 }
291
292 var datasets []*Dataset
293
294 name := ""
295 var ds *Dataset
296 for _, line := range out {
297 if name != line[0] {
298 name = line[0]
299 ds = &Dataset{Name: name}
300 datasets = append(datasets, ds)
301 }
302 if err := ds.parseLine(line); err != nil {
303 return nil, err
304 }
305 }
306
307 return datasets, nil
308 }
309
310 func propsSlice(properties map[string]string) []string {
311 args := make([]string, 0, len(properties)*3)
312 for k, v := range properties {
313 args = append(args, "-o")
314 args = append(args, fmt.Sprintf("%s=%s", k, v))
315 }
316 return args
317 }
318
319 func (z *Zpool) parseLine(line []string) error {
320 prop := line[1]
321 val := line[2]
322
323 var err error
324
325 switch prop {
326 case "name":
327 setString(&z.Name, val)
328 case "health":
329 setString(&z.Health, val)
330 case "allocated":
331 err = setUint(&z.Allocated, val)
332 case "size":
333 err = setUint(&z.Size, val)
334 case "free":
335 err = setUint(&z.Free, val)
336 case "fragmentation":
337 // Trim trailing "%" before parsing uint
338 i := strings.Index(val, "%")
339 if i < 0 {
340 i = len(val)
341 }
342 err = setUint(&z.Fragmentation, val[:i])
343 case "readonly":
344 z.ReadOnly = val == "on"
345 case "freeing":
346 err = setUint(&z.Freeing, val)
347 case "leaked":
348 err = setUint(&z.Leaked, val)
349 case "dedupratio":
350 // Trim trailing "x" before parsing float64
351 z.DedupRatio, err = strconv.ParseFloat(val[:len(val)-1], 64)
352 }
353 return err
354 }