-
Notifications
You must be signed in to change notification settings - Fork 115
/
parted_partitioner.go
343 lines (280 loc) · 10.5 KB
/
parted_partitioner.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package disk
import (
"fmt"
"regexp"
"strconv"
"strings"
"code.cloudfoundry.org/clock"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
boshretry "github.com/cloudfoundry/bosh-utils/retrystrategy"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
const (
partitionNamePrefix = "bosh-partition"
deltaSize = 100
)
type partedPartitioner struct {
logger boshlog.Logger
cmdRunner boshsys.CmdRunner
logTag string
timeService clock.Clock
}
func NewPartedPartitioner(logger boshlog.Logger, cmdRunner boshsys.CmdRunner, timeService clock.Clock) Partitioner {
return partedPartitioner{
logger: logger,
cmdRunner: cmdRunner,
logTag: "PartedPartitioner",
timeService: timeService,
}
}
func (p partedPartitioner) Partition(devicePath string, desiredPartitions []Partition) error {
existingPartitions, deviceFullSizeInBytes, err := p.getPartitions(devicePath)
if err != nil {
return bosherr.WrapErrorf(err, "Getting existing partitions of `%s'", devicePath)
}
if p.partitionsMatch(existingPartitions, desiredPartitions, deviceFullSizeInBytes) {
return nil
}
if p.areAnyExistingPartitionsCreatedByBosh(existingPartitions) {
return bosherr.Errorf("'%s' contains a partition created by bosh. No partitioning is allowed.", devicePath)
}
if err = p.createEachPartition(desiredPartitions, deviceFullSizeInBytes, devicePath); err != nil {
return err
}
if strings.Contains(devicePath, "/dev/mapper/") {
if err = p.createMapperPartition(devicePath); err != nil {
return err
}
}
return nil
}
func (p partedPartitioner) GetDeviceSizeInBytes(devicePath string) (uint64, error) {
stdout, _, _, err := p.cmdRunner.RunCommand("lsblk", "--nodeps", "-nb", "-o", "SIZE", devicePath)
if err != nil {
return 0, bosherr.WrapErrorf(err, "Getting block device size of '%s'", devicePath)
}
deviceSize, err := strconv.Atoi(strings.Trim(stdout, "\n"))
if err != nil {
return 0, bosherr.WrapErrorf(err, "Converting block device size of '%s'", devicePath)
}
return uint64(deviceSize), nil
}
func (p partedPartitioner) partitionsMatch(existingPartitions []existingPartition, desiredPartitions []Partition, deviceSizeInBytes uint64) bool {
if len(existingPartitions) < len(desiredPartitions) {
return false
}
remainingDiskSpace := deviceSizeInBytes
for index, partition := range desiredPartitions {
if index == len(desiredPartitions)-1 && partition.SizeInBytes == 0 {
partition.SizeInBytes = remainingDiskSpace
}
existingPartition := existingPartitions[index]
if existingPartition.Type != partition.Type {
return false
} else if !withinDelta(partition.SizeInBytes, existingPartition.SizeInBytes, p.convertFromMbToBytes(deltaSize)) {
return false
}
remainingDiskSpace = remainingDiskSpace - partition.SizeInBytes
}
return true
}
func (p partedPartitioner) areAnyExistingPartitionsCreatedByBosh(existingPartitions []existingPartition) bool {
for _, partition := range existingPartitions {
if strings.HasPrefix(partition.Name, partitionNamePrefix) {
return true
}
}
return false
}
// For reference on format of outputs: http://lists.alioth.debian.org/pipermail/parted-devel/2006-December/000573.html
func (p partedPartitioner) getPartitions(devicePath string) (partitions []existingPartition, deviceFullSizeInBytes uint64, err error) {
stdout, _, _, err := p.runPartedPrint(devicePath)
if err != nil {
return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Running parted print")
}
allLines := strings.Split(stdout, "\n")
if len(allLines) < 2 {
return partitions, deviceFullSizeInBytes, bosherr.Errorf("Parsing existing partitions")
}
deviceInfo := strings.Split(allLines[1], ":")
deviceFullSizeInBytes, err = strconv.ParseUint(strings.TrimRight(deviceInfo[1], "B"), 10, 64)
if err != nil {
return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing device size")
}
partitionLines := allLines[2 : len(allLines)-1]
for _, partitionLine := range partitionLines {
// ignore PReP partition on ppc64le
if strings.Contains(partitionLine, "prep") {
continue
}
partitionInfo := strings.Split(partitionLine, ":")
partitionIndex, err := strconv.Atoi(partitionInfo[0])
if err != nil {
return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing existing partitions")
}
partitionStartInBytes, err := strconv.Atoi(strings.TrimRight(partitionInfo[1], "B"))
if err != nil {
return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing existing partitions")
}
partitionEndInBytes, err := strconv.Atoi(strings.TrimRight(partitionInfo[2], "B"))
if err != nil {
return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing existing partitions")
}
partitionSizeInBytes, err := strconv.Atoi(strings.TrimRight(partitionInfo[3], "B"))
if err != nil {
return partitions, deviceFullSizeInBytes, bosherr.WrapErrorf(err, "Parsing existing partitions")
}
partitionType := PartitionTypeUnknown
if partitionInfo[4] == "ext4" || partitionInfo[4] == "xfs" {
partitionType = PartitionTypeLinux
} else if partitionInfo[4] == "linux-swap(v1)" {
partitionType = PartitionTypeSwap
}
partitionName := partitionInfo[5]
partitions = append(
partitions,
existingPartition{
Index: partitionIndex,
SizeInBytes: uint64(partitionSizeInBytes),
StartInBytes: uint64(partitionStartInBytes),
EndInBytes: uint64(partitionEndInBytes),
Type: partitionType,
Name: partitionName,
},
)
}
return partitions, deviceFullSizeInBytes, nil
}
func (p partedPartitioner) convertFromBytesToMb(sizeInBytes uint64) uint64 {
return sizeInBytes / (1024 * 1024)
}
func (p partedPartitioner) convertFromMbToBytes(sizeInMb uint64) uint64 {
return sizeInMb * 1024 * 1024
}
func (p partedPartitioner) convertFromKbToBytes(sizeInKb uint64) uint64 {
return sizeInKb * 1024
}
func (p partedPartitioner) runPartedPrint(devicePath string) (stdout, stderr string, exitStatus int, err error) {
stdout, stderr, exitStatus, err = p.cmdRunner.RunCommand("parted", "-m", devicePath, "unit", "B", "print")
// If the error is not having a partition table, create one
if strings.Contains(fmt.Sprintf("%s\n%s", stdout, stderr), "unrecognised disk label") {
stdout, stderr, exitStatus, err = p.getPartitionTable(devicePath)
if err != nil {
return stdout, stderr, exitStatus, bosherr.WrapErrorf(err, "Parted making label")
}
return p.cmdRunner.RunCommand("parted", "-m", devicePath, "unit", "B", "print")
}
return stdout, stderr, exitStatus, err
}
func (p partedPartitioner) getPartitionTable(devicePath string) (stdout, stderr string, exitStatus int, err error) {
return p.cmdRunner.RunCommand(
"parted",
"-s",
devicePath,
"mklabel",
"gpt",
)
}
func (p partedPartitioner) roundUp(numToRound, multiple uint64) uint64 {
if multiple == 0 {
return numToRound
}
remainder := numToRound % multiple
if remainder == 0 {
return numToRound
}
return numToRound + multiple - remainder
}
func (p partedPartitioner) roundDown(numToRound, multiple uint64) uint64 {
if multiple == 0 {
return numToRound
}
remainder := numToRound % multiple
if remainder == 0 {
return numToRound
}
return numToRound - remainder
}
func (p partedPartitioner) createEachPartition(partitions []Partition, deviceFullSizeInBytes uint64, devicePath string) error {
partitionStart := uint64(1048576)
alignmentInBytes := uint64(1048576)
for index, partition := range partitions {
var partitionEnd uint64
if partition.SizeInBytes == 0 {
partitionEnd = deviceFullSizeInBytes - 1
} else {
partitionEnd = partitionStart + partition.SizeInBytes
if partitionEnd >= deviceFullSizeInBytes {
partitionEnd = deviceFullSizeInBytes - 1
p.logger.Info(p.logTag, "Partition %d would be larger than remaining space. Reducing size to %dB", index, partitionEnd-partitionStart)
}
}
partitionEnd = p.roundDown(partitionEnd, alignmentInBytes) - 1
partitionRetryable := boshretry.NewRetryable(func() (bool, error) {
_, _, _, err := p.cmdRunner.RunCommand(
"parted",
"-s",
devicePath,
"unit",
"B",
"mkpart",
fmt.Sprintf("%s-%d", partitionNamePrefix, index),
fmt.Sprintf("%d", partitionStart),
fmt.Sprintf("%d", partitionEnd),
)
if err != nil {
p.logger.Error(p.logTag, "Failed with an error: %s", err)
//TODO: double check the output here. Does it make sense?
return true, bosherr.WrapError(err, "Creating partition using parted")
}
_, _, _, err = p.cmdRunner.RunCommand("partprobe", devicePath)
if err != nil {
p.logger.Error(p.logTag, "Failed to probe for newly created parition: %s", err)
return true, bosherr.WrapError(err, "Creating partition using parted")
}
p.cmdRunner.RunCommand("udevadm", "settle")
p.logger.Info(p.logTag, "Successfully created partition %d on %s", index, devicePath)
return false, nil
})
partitionRetryStrategy := NewPartitionStrategy(partitionRetryable, p.timeService, p.logger)
err := partitionRetryStrategy.Try()
if err != nil {
return bosherr.WrapErrorf(err, "Partitioning disk `%s'", devicePath)
}
partitionStart = p.roundUp(partitionEnd+1, alignmentInBytes)
}
return nil
}
func (p partedPartitioner) createMapperPartition(devicePath string) error {
_, _, _, err := p.cmdRunner.RunCommand("/etc/init.d/open-iscsi", "restart")
if err != nil {
return bosherr.WrapError(err, "Shelling out to restart open-iscsi")
}
_, _, _, err = p.cmdRunner.RunCommand("/etc/init.d/multipath-tools", "restart")
if err != nil {
return bosherr.WrapError(err, "Restarting multipath after restarting open-iscsi")
}
detectPartitionRetryable := boshretry.NewRetryable(func() (bool, error) {
output, _, _, err := p.cmdRunner.RunCommand("dmsetup", "ls")
if err != nil {
return true, bosherr.WrapError(err, "Shelling out to dmsetup ls")
}
if strings.Contains(output, "No devices found") {
return true, bosherr.Errorf("No devices found")
}
device := strings.TrimPrefix(devicePath, "/dev/mapper/")
lines := strings.Split(strings.Trim(output, "\n"), "\n")
for i := 0; i < len(lines); i++ {
if match, _ := regexp.MatchString("-part1", lines[i]); match {
if strings.Contains(lines[i], device) {
p.logger.Info(p.logTag, "Succeeded in detecting partition %s", devicePath+"-part1")
return false, nil
}
}
}
return true, bosherr.Errorf("Partition %s does not show up", devicePath+"-part1")
})
detectPartitionRetryStrategy := NewPartitionStrategy(detectPartitionRetryable, p.timeService, p.logger)
return detectPartitionRetryStrategy.Try()
}