This repository was archived by the owner on Dec 10, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathdisk.go
More file actions
131 lines (105 loc) · 2.43 KB
/
Copy pathdisk.go
File metadata and controls
131 lines (105 loc) · 2.43 KB
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
package main
import (
"context"
"fmt"
"log"
"strings"
"time"
)
type Disk struct {
Name string
Label string
UUID string
Type string
FileSystem string
}
func FindTargetDiskWithContext(ctx context.Context, label string) (Disk, error) {
for {
disk := FindTargetDisk(label)
// we found the disk
if disk.Name != "" {
return disk, nil
}
// wait for the ebs to be ready
log.Printf("Waiting for EBS to be ready...")
select {
case <-ctx.Done():
return disk, ctx.Err()
case <-time.After(5 * time.Second):
// nothing
}
}
}
func FindTargetDisk(label string) Disk {
disks, _ := ListAllDisks()
// fist look for the disk with the right label
if label != "" {
for _, disk := range disks {
if disk.Label == label {
return disk
}
}
}
// then try to look at the first unformatted disk
for _, disk := range disks {
if disk.FileSystem == "data" {
return disk
}
}
return Disk{}
}
func ListAllDisks() ([]Disk, error) {
stdout, _, _ := cmd("lsblk", "-d", "-n", "-r", "-o", "NAME")
lines := strings.Split(strings.TrimSpace(stdout), "\n")
disks := make([]Disk, len(lines))
for i, name := range lines {
disks[i] = GetDiskInfo(name)
}
return disks, nil
}
func GetDiskInfo(name string) Disk {
// clear blockcache
cmd("blkid", "-g")
deviceName := fmt.Sprintf("/dev/%s", name)
stdout, _, _ := cmd("blkid", deviceName, "-o", "export")
disk := Disk{
Name: name,
}
lines := strings.Split(strings.TrimSpace(stdout), "\n")
for _, line := range lines {
bits := strings.Split(line, "=")
if len(bits) < 2 {
continue
}
switch bits[0] {
case "LABEL":
disk.Label = bits[1]
case "UUID":
disk.UUID = bits[1]
case "TYPE":
disk.Type = bits[1]
}
}
// get file system on disk
stdout, _, _ = cmd("file", "-s", deviceName)
lines = strings.SplitN(strings.TrimSpace(stdout), ": ", 2)
disk.FileSystem = lines[1]
return disk
}
func FormatDisk(name string, format string, label string) error {
log.Printf("Formatting disk %s to %s", name, format)
deviceName := fmt.Sprintf("/dev/%s", name)
stdout, stderr, err := cmd("mkfs", "-t", format, deviceName)
if err != nil {
log.Printf("Format command error: %v %v", stdout, stderr)
return err
}
if label != "" {
log.Printf("Setting device label to %s", label)
stdout, stderr, err = cmd("e2label", deviceName, label)
}
if err != nil {
log.Printf("Label command error: %v %v", stdout, stderr)
}
return err
}