Statistics
| Branch: | Tag: | Revision:

root / lib / bdev.py @ 6b93ec9d

History | View | Annotate | Download (54.1 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Block device abstraction"""
23

    
24
import re
25
import time
26
import errno
27
import pyparsing as pyp
28
import os
29
import logging
30

    
31
from ganeti import utils
32
from ganeti import errors
33
from ganeti import constants
34

    
35

    
36
class BlockDev(object):
37
  """Block device abstract class.
38

39
  A block device can be in the following states:
40
    - not existing on the system, and by `Create()` it goes into:
41
    - existing but not setup/not active, and by `Assemble()` goes into:
42
    - active read-write and by `Open()` it goes into
43
    - online (=used, or ready for use)
44

45
  A device can also be online but read-only, however we are not using
46
  the readonly state (LV has it, if needed in the future) and we are
47
  usually looking at this like at a stack, so it's easier to
48
  conceptualise the transition from not-existing to online and back
49
  like a linear one.
50

51
  The many different states of the device are due to the fact that we
52
  need to cover many device types:
53
    - logical volumes are created, lvchange -a y $lv, and used
54
    - drbd devices are attached to a local disk/remote peer and made primary
55

56
  A block device is identified by three items:
57
    - the /dev path of the device (dynamic)
58
    - a unique ID of the device (static)
59
    - it's major/minor pair (dynamic)
60

61
  Not all devices implement both the first two as distinct items. LVM
62
  logical volumes have their unique ID (the pair volume group, logical
63
  volume name) in a 1-to-1 relation to the dev path. For DRBD devices,
64
  the /dev path is again dynamic and the unique id is the pair (host1,
65
  dev1), (host2, dev2).
66

67
  You can get to a device in two ways:
68
    - creating the (real) device, which returns you
69
      an attached instance (lvcreate)
70
    - attaching of a python instance to an existing (real) device
71

72
  The second point, the attachement to a device, is different
73
  depending on whether the device is assembled or not. At init() time,
74
  we search for a device with the same unique_id as us. If found,
75
  good. It also means that the device is already assembled. If not,
76
  after assembly we'll have our correct major/minor.
77

78
  """
79
  def __init__(self, unique_id, children):
80
    self._children = children
81
    self.dev_path = None
82
    self.unique_id = unique_id
83
    self.major = None
84
    self.minor = None
85
    self.attached = False
86

    
87
  def Assemble(self):
88
    """Assemble the device from its components.
89

90
    Implementations of this method by child classes must ensure that:
91
      - after the device has been assembled, it knows its major/minor
92
        numbers; this allows other devices (usually parents) to probe
93
        correctly for their children
94
      - calling this method on an existing, in-use device is safe
95
      - if the device is already configured (and in an OK state),
96
        this method is idempotent
97

98
    """
99
    return True
100

    
101
  def Attach(self):
102
    """Find a device which matches our config and attach to it.
103

104
    """
105
    raise NotImplementedError
106

    
107
  def Close(self):
108
    """Notifies that the device will no longer be used for I/O.
109

110
    """
111
    raise NotImplementedError
112

    
113
  @classmethod
114
  def Create(cls, unique_id, children, size):
115
    """Create the device.
116

117
    If the device cannot be created, it will return None
118
    instead. Error messages go to the logging system.
119

120
    Note that for some devices, the unique_id is used, and for other,
121
    the children. The idea is that these two, taken together, are
122
    enough for both creation and assembly (later).
123

124
    """
125
    raise NotImplementedError
126

    
127
  def Remove(self):
128
    """Remove this device.
129

130
    This makes sense only for some of the device types: LV and file
131
    storeage. Also note that if the device can't attach, the removal
132
    can't be completed.
133

134
    """
135
    raise NotImplementedError
136

    
137
  def Rename(self, new_id):
138
    """Rename this device.
139

140
    This may or may not make sense for a given device type.
141

142
    """
143
    raise NotImplementedError
144

    
145
  def Open(self, force=False):
146
    """Make the device ready for use.
147

148
    This makes the device ready for I/O. For now, just the DRBD
149
    devices need this.
150

151
    The force parameter signifies that if the device has any kind of
152
    --force thing, it should be used, we know what we are doing.
153

154
    """
155
    raise NotImplementedError
156

    
157
  def Shutdown(self):
158
    """Shut down the device, freeing its children.
159

160
    This undoes the `Assemble()` work, except for the child
161
    assembling; as such, the children on the device are still
162
    assembled after this call.
163

164
    """
165
    raise NotImplementedError
166

    
167
  def SetSyncSpeed(self, speed):
168
    """Adjust the sync speed of the mirror.
169

170
    In case this is not a mirroring device, this is no-op.
171

172
    """
173
    result = True
174
    if self._children:
175
      for child in self._children:
176
        result = result and child.SetSyncSpeed(speed)
177
    return result
178

    
179
  def GetSyncStatus(self):
180
    """Returns the sync status of the device.
181

182
    If this device is a mirroring device, this function returns the
183
    status of the mirror.
184

185
    If sync_percent is None, it means the device is not syncing.
186

187
    If estimated_time is None, it means we can't estimate
188
    the time needed, otherwise it's the time left in seconds.
189

190
    If is_degraded is True, it means the device is missing
191
    redundancy. This is usually a sign that something went wrong in
192
    the device setup, if sync_percent is None.
193

194
    The ldisk parameter represents the degradation of the local
195
    data. This is only valid for some devices, the rest will always
196
    return False (not degraded).
197

198
    @rtype: tuple
199
    @return: (sync_percent, estimated_time, is_degraded, ldisk)
200

201
    """
202
    return None, None, False, False
203

    
204

    
205
  def CombinedSyncStatus(self):
206
    """Calculate the mirror status recursively for our children.
207

208
    The return value is the same as for `GetSyncStatus()` except the
209
    minimum percent and maximum time are calculated across our
210
    children.
211

212
    """
213
    min_percent, max_time, is_degraded, ldisk = self.GetSyncStatus()
214
    if self._children:
215
      for child in self._children:
216
        c_percent, c_time, c_degraded, c_ldisk = child.GetSyncStatus()
217
        if min_percent is None:
218
          min_percent = c_percent
219
        elif c_percent is not None:
220
          min_percent = min(min_percent, c_percent)
221
        if max_time is None:
222
          max_time = c_time
223
        elif c_time is not None:
224
          max_time = max(max_time, c_time)
225
        is_degraded = is_degraded or c_degraded
226
        ldisk = ldisk or c_ldisk
227
    return min_percent, max_time, is_degraded, ldisk
228

    
229

    
230
  def SetInfo(self, text):
231
    """Update metadata with info text.
232

233
    Only supported for some device types.
234

235
    """
236
    for child in self._children:
237
      child.SetInfo(text)
238

    
239
  def Grow(self, amount):
240
    """Grow the block device.
241

242
    @param amount: the amount (in mebibytes) to grow with
243

244
    """
245
    raise NotImplementedError
246

    
247
  def __repr__(self):
248
    return ("<%s: unique_id: %s, children: %s, %s:%s, %s>" %
249
            (self.__class__, self.unique_id, self._children,
250
             self.major, self.minor, self.dev_path))
251

    
252

    
253
class LogicalVolume(BlockDev):
254
  """Logical Volume block device.
255

256
  """
257
  def __init__(self, unique_id, children):
258
    """Attaches to a LV device.
259

260
    The unique_id is a tuple (vg_name, lv_name)
261

262
    """
263
    super(LogicalVolume, self).__init__(unique_id, children)
264
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 2:
265
      raise ValueError("Invalid configuration data %s" % str(unique_id))
266
    self._vg_name, self._lv_name = unique_id
267
    self.dev_path = "/dev/%s/%s" % (self._vg_name, self._lv_name)
268
    self._degraded = True
269
    self.major = self.minor = None
270
    self.Attach()
271

    
272
  @classmethod
273
  def Create(cls, unique_id, children, size):
274
    """Create a new logical volume.
275

276
    """
277
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 2:
278
      raise ValueError("Invalid configuration data %s" % str(unique_id))
279
    vg_name, lv_name = unique_id
280
    pvs_info = cls.GetPVInfo(vg_name)
281
    if not pvs_info:
282
      raise errors.BlockDeviceError("Can't compute PV info for vg %s" %
283
                                    vg_name)
284
    pvs_info.sort()
285
    pvs_info.reverse()
286

    
287
    pvlist = [ pv[1] for pv in pvs_info ]
288
    free_size = sum([ pv[0] for pv in pvs_info ])
289

    
290
    # The size constraint should have been checked from the master before
291
    # calling the create function.
292
    if free_size < size:
293
      raise errors.BlockDeviceError("Not enough free space: required %s,"
294
                                    " available %s" % (size, free_size))
295
    result = utils.RunCmd(["lvcreate", "-L%dm" % size, "-n%s" % lv_name,
296
                           vg_name] + pvlist)
297
    if result.failed:
298
      raise errors.BlockDeviceError("%s - %s" % (result.fail_reason,
299
                                                result.output))
300
    return LogicalVolume(unique_id, children)
301

    
302
  @staticmethod
303
  def GetPVInfo(vg_name):
304
    """Get the free space info for PVs in a volume group.
305

306
    @param vg_name: the volume group name
307

308
    @rtype: list
309
    @return: list of tuples (free_space, name) with free_space in mebibytes
310

311
    """
312
    command = ["pvs", "--noheadings", "--nosuffix", "--units=m",
313
               "-opv_name,vg_name,pv_free,pv_attr", "--unbuffered",
314
               "--separator=:"]
315
    result = utils.RunCmd(command)
316
    if result.failed:
317
      logging.error("Can't get the PV information: %s - %s",
318
                    result.fail_reason, result.output)
319
      return None
320
    data = []
321
    for line in result.stdout.splitlines():
322
      fields = line.strip().split(':')
323
      if len(fields) != 4:
324
        logging.error("Can't parse pvs output: line '%s'", line)
325
        return None
326
      # skip over pvs from another vg or ones which are not allocatable
327
      if fields[1] != vg_name or fields[3][0] != 'a':
328
        continue
329
      data.append((float(fields[2]), fields[0]))
330

    
331
    return data
332

    
333
  def Remove(self):
334
    """Remove this logical volume.
335

336
    """
337
    if not self.minor and not self.Attach():
338
      # the LV does not exist
339
      return True
340
    result = utils.RunCmd(["lvremove", "-f", "%s/%s" %
341
                           (self._vg_name, self._lv_name)])
342
    if result.failed:
343
      logging.error("Can't lvremove: %s - %s",
344
                    result.fail_reason, result.output)
345

    
346
    return not result.failed
347

    
348
  def Rename(self, new_id):
349
    """Rename this logical volume.
350

351
    """
352
    if not isinstance(new_id, (tuple, list)) or len(new_id) != 2:
353
      raise errors.ProgrammerError("Invalid new logical id '%s'" % new_id)
354
    new_vg, new_name = new_id
355
    if new_vg != self._vg_name:
356
      raise errors.ProgrammerError("Can't move a logical volume across"
357
                                   " volume groups (from %s to to %s)" %
358
                                   (self._vg_name, new_vg))
359
    result = utils.RunCmd(["lvrename", new_vg, self._lv_name, new_name])
360
    if result.failed:
361
      raise errors.BlockDeviceError("Failed to rename the logical volume: %s" %
362
                                    result.output)
363
    self._lv_name = new_name
364
    self.dev_path = "/dev/%s/%s" % (self._vg_name, self._lv_name)
365

    
366
  def Attach(self):
367
    """Attach to an existing LV.
368

369
    This method will try to see if an existing and active LV exists
370
    which matches our name. If so, its major/minor will be
371
    recorded.
372

373
    """
374
    self.attached = False
375
    result = utils.RunCmd(["lvs", "--noheadings", "--separator=,",
376
                           "-olv_attr,lv_kernel_major,lv_kernel_minor",
377
                           self.dev_path])
378
    if result.failed:
379
      logging.error("Can't find LV %s: %s, %s",
380
                    self.dev_path, result.fail_reason, result.output)
381
      return False
382
    out = result.stdout.strip().rstrip(',')
383
    out = out.split(",")
384
    if len(out) != 3:
385
      logging.error("Can't parse LVS output, len(%s) != 3", str(out))
386
      return False
387

    
388
    status, major, minor = out[:3]
389
    if len(status) != 6:
390
      logging.error("lvs lv_attr is not 6 characters (%s)", status)
391
      return False
392

    
393
    try:
394
      major = int(major)
395
      minor = int(minor)
396
    except ValueError, err:
397
      logging.error("lvs major/minor cannot be parsed: %s", str(err))
398

    
399
    self.major = major
400
    self.minor = minor
401
    self._degraded = status[0] == 'v' # virtual volume, i.e. doesn't backing
402
                                      # storage
403
    self.attached = True
404
    return True
405

    
406
  def Assemble(self):
407
    """Assemble the device.
408

409
    We alway run `lvchange -ay` on the LV to ensure it's active before
410
    use, as there were cases when xenvg was not active after boot
411
    (also possibly after disk issues).
412

413
    """
414
    result = utils.RunCmd(["lvchange", "-ay", self.dev_path])
415
    if result.failed:
416
      logging.error("Can't activate lv %s: %s", self.dev_path, result.output)
417
      return False
418
    return self.Attach()
419

    
420
  def Shutdown(self):
421
    """Shutdown the device.
422

423
    This is a no-op for the LV device type, as we don't deactivate the
424
    volumes on shutdown.
425

426
    """
427
    return True
428

    
429
  def GetSyncStatus(self):
430
    """Returns the sync status of the device.
431

432
    If this device is a mirroring device, this function returns the
433
    status of the mirror.
434

435
    For logical volumes, sync_percent and estimated_time are always
436
    None (no recovery in progress, as we don't handle the mirrored LV
437
    case). The is_degraded parameter is the inverse of the ldisk
438
    parameter.
439

440
    For the ldisk parameter, we check if the logical volume has the
441
    'virtual' type, which means it's not backed by existing storage
442
    anymore (read from it return I/O error). This happens after a
443
    physical disk failure and subsequent 'vgreduce --removemissing' on
444
    the volume group.
445

446
    The status was already read in Attach, so we just return it.
447

448
    @rtype: tuple
449
    @return: (sync_percent, estimated_time, is_degraded, ldisk)
450

451
    """
452
    return None, None, self._degraded, self._degraded
453

    
454
  def Open(self, force=False):
455
    """Make the device ready for I/O.
456

457
    This is a no-op for the LV device type.
458

459
    """
460
    pass
461

    
462
  def Close(self):
463
    """Notifies that the device will no longer be used for I/O.
464

465
    This is a no-op for the LV device type.
466

467
    """
468
    pass
469

    
470
  def Snapshot(self, size):
471
    """Create a snapshot copy of an lvm block device.
472

473
    """
474
    snap_name = self._lv_name + ".snap"
475

    
476
    # remove existing snapshot if found
477
    snap = LogicalVolume((self._vg_name, snap_name), None)
478
    snap.Remove()
479

    
480
    pvs_info = self.GetPVInfo(self._vg_name)
481
    if not pvs_info:
482
      raise errors.BlockDeviceError("Can't compute PV info for vg %s" %
483
                                    self._vg_name)
484
    pvs_info.sort()
485
    pvs_info.reverse()
486
    free_size, pv_name = pvs_info[0]
487
    if free_size < size:
488
      raise errors.BlockDeviceError("Not enough free space: required %s,"
489
                                    " available %s" % (size, free_size))
490

    
491
    result = utils.RunCmd(["lvcreate", "-L%dm" % size, "-s",
492
                           "-n%s" % snap_name, self.dev_path])
493
    if result.failed:
494
      raise errors.BlockDeviceError("command: %s error: %s - %s" %
495
                                    (result.cmd, result.fail_reason,
496
                                     result.output))
497

    
498
    return snap_name
499

    
500
  def SetInfo(self, text):
501
    """Update metadata with info text.
502

503
    """
504
    BlockDev.SetInfo(self, text)
505

    
506
    # Replace invalid characters
507
    text = re.sub('^[^A-Za-z0-9_+.]', '_', text)
508
    text = re.sub('[^-A-Za-z0-9_+.]', '_', text)
509

    
510
    # Only up to 128 characters are allowed
511
    text = text[:128]
512

    
513
    result = utils.RunCmd(["lvchange", "--addtag", text,
514
                           self.dev_path])
515
    if result.failed:
516
      raise errors.BlockDeviceError("Command: %s error: %s - %s" %
517
                                    (result.cmd, result.fail_reason,
518
                                     result.output))
519
  def Grow(self, amount):
520
    """Grow the logical volume.
521

522
    """
523
    # we try multiple algorithms since the 'best' ones might not have
524
    # space available in the right place, but later ones might (since
525
    # they have less constraints); also note that only recent LVM
526
    # supports 'cling'
527
    for alloc_policy in "contiguous", "cling", "normal":
528
      result = utils.RunCmd(["lvextend", "--alloc", alloc_policy,
529
                             "-L", "+%dm" % amount, self.dev_path])
530
      if not result.failed:
531
        return
532
    raise errors.BlockDeviceError("Can't grow LV %s: %s" %
533
                                  (self.dev_path, result.output))
534

    
535

    
536
class DRBD8Status(object):
537
  """A DRBD status representation class.
538

539
  Note that this doesn't support unconfigured devices (cs:Unconfigured).
540

541
  """
542
  LINE_RE = re.compile(r"\s*[0-9]+:\s*cs:(\S+)\s+st:([^/]+)/(\S+)"
543
                       "\s+ds:([^/]+)/(\S+)\s+.*$")
544
  SYNC_RE = re.compile(r"^.*\ssync'ed:\s*([0-9.]+)%.*"
545
                       "\sfinish: ([0-9]+):([0-9]+):([0-9]+)\s.*$")
546

    
547
  def __init__(self, procline):
548
    m = self.LINE_RE.match(procline)
549
    if not m:
550
      raise errors.BlockDeviceError("Can't parse input data '%s'" % procline)
551
    self.cstatus = m.group(1)
552
    self.lrole = m.group(2)
553
    self.rrole = m.group(3)
554
    self.ldisk = m.group(4)
555
    self.rdisk = m.group(5)
556

    
557
    self.is_standalone = self.cstatus == "StandAlone"
558
    self.is_wfconn = self.cstatus == "WFConnection"
559
    self.is_connected = self.cstatus == "Connected"
560
    self.is_primary = self.lrole == "Primary"
561
    self.is_secondary = self.lrole == "Secondary"
562
    self.peer_primary = self.rrole == "Primary"
563
    self.peer_secondary = self.rrole == "Secondary"
564
    self.both_primary = self.is_primary and self.peer_primary
565
    self.both_secondary = self.is_secondary and self.peer_secondary
566

    
567
    self.is_diskless = self.ldisk == "Diskless"
568
    self.is_disk_uptodate = self.ldisk == "UpToDate"
569

    
570
    self.is_in_resync = self.cstatus in ('SyncSource', 'SyncTarget')
571

    
572
    m = self.SYNC_RE.match(procline)
573
    if m:
574
      self.sync_percent = float(m.group(1))
575
      hours = int(m.group(2))
576
      minutes = int(m.group(3))
577
      seconds = int(m.group(4))
578
      self.est_time = hours * 3600 + minutes * 60 + seconds
579
    else:
580
      self.sync_percent = None
581
      self.est_time = None
582

    
583
    self.is_sync_target = self.peer_sync_source = self.cstatus == "SyncTarget"
584
    self.peer_sync_target = self.is_sync_source = self.cstatus == "SyncSource"
585
    self.is_resync = self.is_sync_target or self.is_sync_source
586

    
587

    
588
class BaseDRBD(BlockDev):
589
  """Base DRBD class.
590

591
  This class contains a few bits of common functionality between the
592
  0.7 and 8.x versions of DRBD.
593

594
  """
595
  _VERSION_RE = re.compile(r"^version: (\d+)\.(\d+)\.(\d+)"
596
                           r" \(api:(\d+)/proto:(\d+)(?:-(\d+))?\)")
597

    
598
  _DRBD_MAJOR = 147
599
  _ST_UNCONFIGURED = "Unconfigured"
600
  _ST_WFCONNECTION = "WFConnection"
601
  _ST_CONNECTED = "Connected"
602

    
603
  _STATUS_FILE = "/proc/drbd"
604

    
605
  @staticmethod
606
  def _GetProcData(filename=_STATUS_FILE):
607
    """Return data from /proc/drbd.
608

609
    """
610
    stat = open(filename, "r")
611
    try:
612
      data = stat.read().splitlines()
613
    finally:
614
      stat.close()
615
    if not data:
616
      raise errors.BlockDeviceError("Can't read any data from %s" % filename)
617
    return data
618

    
619
  @staticmethod
620
  def _MassageProcData(data):
621
    """Transform the output of _GetProdData into a nicer form.
622

623
    @return: a dictionary of minor: joined lines from /proc/drbd
624
        for that minor
625

626
    """
627
    lmatch = re.compile("^ *([0-9]+):.*$")
628
    results = {}
629
    old_minor = old_line = None
630
    for line in data:
631
      lresult = lmatch.match(line)
632
      if lresult is not None:
633
        if old_minor is not None:
634
          results[old_minor] = old_line
635
        old_minor = int(lresult.group(1))
636
        old_line = line
637
      else:
638
        if old_minor is not None:
639
          old_line += " " + line.strip()
640
    # add last line
641
    if old_minor is not None:
642
      results[old_minor] = old_line
643
    return results
644

    
645
  @classmethod
646
  def _GetVersion(cls):
647
    """Return the DRBD version.
648

649
    This will return a dict with keys:
650
      - k_major
651
      - k_minor
652
      - k_point
653
      - api
654
      - proto
655
      - proto2 (only on drbd > 8.2.X)
656

657
    """
658
    proc_data = cls._GetProcData()
659
    first_line = proc_data[0].strip()
660
    version = cls._VERSION_RE.match(first_line)
661
    if not version:
662
      raise errors.BlockDeviceError("Can't parse DRBD version from '%s'" %
663
                                    first_line)
664

    
665
    values = version.groups()
666
    retval = {'k_major': int(values[0]),
667
              'k_minor': int(values[1]),
668
              'k_point': int(values[2]),
669
              'api': int(values[3]),
670
              'proto': int(values[4]),
671
             }
672
    if values[5] is not None:
673
      retval['proto2'] = values[5]
674

    
675
    return retval
676

    
677
  @staticmethod
678
  def _DevPath(minor):
679
    """Return the path to a drbd device for a given minor.
680

681
    """
682
    return "/dev/drbd%d" % minor
683

    
684
  @classmethod
685
  def _GetUsedDevs(cls):
686
    """Compute the list of used DRBD devices.
687

688
    """
689
    data = cls._GetProcData()
690

    
691
    used_devs = {}
692
    valid_line = re.compile("^ *([0-9]+): cs:([^ ]+).*$")
693
    for line in data:
694
      match = valid_line.match(line)
695
      if not match:
696
        continue
697
      minor = int(match.group(1))
698
      state = match.group(2)
699
      if state == cls._ST_UNCONFIGURED:
700
        continue
701
      used_devs[minor] = state, line
702

    
703
    return used_devs
704

    
705
  def _SetFromMinor(self, minor):
706
    """Set our parameters based on the given minor.
707

708
    This sets our minor variable and our dev_path.
709

710
    """
711
    if minor is None:
712
      self.minor = self.dev_path = None
713
      self.attached = False
714
    else:
715
      self.minor = minor
716
      self.dev_path = self._DevPath(minor)
717
      self.attached = True
718

    
719
  @staticmethod
720
  def _CheckMetaSize(meta_device):
721
    """Check if the given meta device looks like a valid one.
722

723
    This currently only check the size, which must be around
724
    128MiB.
725

726
    """
727
    result = utils.RunCmd(["blockdev", "--getsize", meta_device])
728
    if result.failed:
729
      logging.error("Failed to get device size: %s - %s",
730
                    result.fail_reason, result.output)
731
      return False
732
    try:
733
      sectors = int(result.stdout)
734
    except ValueError:
735
      logging.error("Invalid output from blockdev: '%s'", result.stdout)
736
      return False
737
    bytes = sectors * 512
738
    if bytes < 128 * 1024 * 1024: # less than 128MiB
739
      logging.error("Meta device too small (%.2fMib)", (bytes / 1024 / 1024))
740
      return False
741
    if bytes > (128 + 32) * 1024 * 1024: # account for an extra (big) PE on LVM
742
      logging.error("Meta device too big (%.2fMiB)", (bytes / 1024 / 1024))
743
      return False
744
    return True
745

    
746
  def Rename(self, new_id):
747
    """Rename a device.
748

749
    This is not supported for drbd devices.
750

751
    """
752
    raise errors.ProgrammerError("Can't rename a drbd device")
753

    
754

    
755
class DRBD8(BaseDRBD):
756
  """DRBD v8.x block device.
757

758
  This implements the local host part of the DRBD device, i.e. it
759
  doesn't do anything to the supposed peer. If you need a fully
760
  connected DRBD pair, you need to use this class on both hosts.
761

762
  The unique_id for the drbd device is the (local_ip, local_port,
763
  remote_ip, remote_port) tuple, and it must have two children: the
764
  data device and the meta_device. The meta device is checked for
765
  valid size and is zeroed on create.
766

767
  """
768
  _MAX_MINORS = 255
769
  _PARSE_SHOW = None
770

    
771
  # timeout constants
772
  _NET_RECONFIG_TIMEOUT = 60
773

    
774
  def __init__(self, unique_id, children):
775
    if children and children.count(None) > 0:
776
      children = []
777
    super(DRBD8, self).__init__(unique_id, children)
778
    self.major = self._DRBD_MAJOR
779
    version = self._GetVersion()
780
    if version['k_major'] != 8 :
781
      raise errors.BlockDeviceError("Mismatch in DRBD kernel version and"
782
                                    " requested ganeti usage: kernel is"
783
                                    " %s.%s, ganeti wants 8.x" %
784
                                    (version['k_major'], version['k_minor']))
785

    
786
    if len(children) not in (0, 2):
787
      raise ValueError("Invalid configuration data %s" % str(children))
788
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 6:
789
      raise ValueError("Invalid configuration data %s" % str(unique_id))
790
    (self._lhost, self._lport,
791
     self._rhost, self._rport,
792
     self._aminor, self._secret) = unique_id
793
    if (self._lhost is not None and self._lhost == self._rhost and
794
        self._lport == self._rport):
795
      raise ValueError("Invalid configuration data, same local/remote %s" %
796
                       (unique_id,))
797
    self.Attach()
798

    
799
  @classmethod
800
  def _InitMeta(cls, minor, dev_path):
801
    """Initialize a meta device.
802

803
    This will not work if the given minor is in use.
804

805
    """
806
    result = utils.RunCmd(["drbdmeta", "--force", cls._DevPath(minor),
807
                           "v08", dev_path, "0", "create-md"])
808
    if result.failed:
809
      raise errors.BlockDeviceError("Can't initialize meta device: %s" %
810
                                    result.output)
811

    
812
  @classmethod
813
  def _FindUnusedMinor(cls):
814
    """Find an unused DRBD device.
815

816
    This is specific to 8.x as the minors are allocated dynamically,
817
    so non-existing numbers up to a max minor count are actually free.
818

819
    """
820
    data = cls._GetProcData()
821

    
822
    unused_line = re.compile("^ *([0-9]+): cs:Unconfigured$")
823
    used_line = re.compile("^ *([0-9]+): cs:")
824
    highest = None
825
    for line in data:
826
      match = unused_line.match(line)
827
      if match:
828
        return int(match.group(1))
829
      match = used_line.match(line)
830
      if match:
831
        minor = int(match.group(1))
832
        highest = max(highest, minor)
833
    if highest is None: # there are no minors in use at all
834
      return 0
835
    if highest >= cls._MAX_MINORS:
836
      logging.error("Error: no free drbd minors!")
837
      raise errors.BlockDeviceError("Can't find a free DRBD minor")
838
    return highest + 1
839

    
840
  @classmethod
841
  def _IsValidMeta(cls, meta_device):
842
    """Check if the given meta device looks like a valid one.
843

844
    """
845
    minor = cls._FindUnusedMinor()
846
    minor_path = cls._DevPath(minor)
847
    result = utils.RunCmd(["drbdmeta", minor_path,
848
                           "v08", meta_device, "0",
849
                           "dstate"])
850
    if result.failed:
851
      logging.error("Invalid meta device %s: %s", meta_device, result.output)
852
      return False
853
    return True
854

    
855
  @classmethod
856
  def _GetShowParser(cls):
857
    """Return a parser for `drbd show` output.
858

859
    This will either create or return an already-create parser for the
860
    output of the command `drbd show`.
861

862
    """
863
    if cls._PARSE_SHOW is not None:
864
      return cls._PARSE_SHOW
865

    
866
    # pyparsing setup
867
    lbrace = pyp.Literal("{").suppress()
868
    rbrace = pyp.Literal("}").suppress()
869
    semi = pyp.Literal(";").suppress()
870
    # this also converts the value to an int
871
    number = pyp.Word(pyp.nums).setParseAction(lambda s, l, t: int(t[0]))
872

    
873
    comment = pyp.Literal ("#") + pyp.Optional(pyp.restOfLine)
874
    defa = pyp.Literal("_is_default").suppress()
875
    dbl_quote = pyp.Literal('"').suppress()
876

    
877
    keyword = pyp.Word(pyp.alphanums + '-')
878

    
879
    # value types
880
    value = pyp.Word(pyp.alphanums + '_-/.:')
881
    quoted = dbl_quote + pyp.CharsNotIn('"') + dbl_quote
882
    addr_port = (pyp.Word(pyp.nums + '.') + pyp.Literal(':').suppress() +
883
                 number)
884
    # meta device, extended syntax
885
    meta_value = ((value ^ quoted) + pyp.Literal('[').suppress() +
886
                  number + pyp.Word(']').suppress())
887

    
888
    # a statement
889
    stmt = (~rbrace + keyword + ~lbrace +
890
            pyp.Optional(addr_port ^ value ^ quoted ^ meta_value) +
891
            pyp.Optional(defa) + semi +
892
            pyp.Optional(pyp.restOfLine).suppress())
893

    
894
    # an entire section
895
    section_name = pyp.Word(pyp.alphas + '_')
896
    section = section_name + lbrace + pyp.ZeroOrMore(pyp.Group(stmt)) + rbrace
897

    
898
    bnf = pyp.ZeroOrMore(pyp.Group(section ^ stmt))
899
    bnf.ignore(comment)
900

    
901
    cls._PARSE_SHOW = bnf
902

    
903
    return bnf
904

    
905
  @classmethod
906
  def _GetShowData(cls, minor):
907
    """Return the `drbdsetup show` data for a minor.
908

909
    """
910
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "show"])
911
    if result.failed:
912
      logging.error("Can't display the drbd config: %s - %s",
913
                    result.fail_reason, result.output)
914
      return None
915
    return result.stdout
916

    
917
  @classmethod
918
  def _GetDevInfo(cls, out):
919
    """Parse details about a given DRBD minor.
920

921
    This return, if available, the local backing device (as a path)
922
    and the local and remote (ip, port) information from a string
923
    containing the output of the `drbdsetup show` command as returned
924
    by _GetShowData.
925

926
    """
927
    data = {}
928
    if not out:
929
      return data
930

    
931
    bnf = cls._GetShowParser()
932
    # run pyparse
933

    
934
    try:
935
      results = bnf.parseString(out)
936
    except pyp.ParseException, err:
937
      raise errors.BlockDeviceError("Can't parse drbdsetup show output: %s" %
938
                                    str(err))
939

    
940
    # and massage the results into our desired format
941
    for section in results:
942
      sname = section[0]
943
      if sname == "_this_host":
944
        for lst in section[1:]:
945
          if lst[0] == "disk":
946
            data["local_dev"] = lst[1]
947
          elif lst[0] == "meta-disk":
948
            data["meta_dev"] = lst[1]
949
            data["meta_index"] = lst[2]
950
          elif lst[0] == "address":
951
            data["local_addr"] = tuple(lst[1:])
952
      elif sname == "_remote_host":
953
        for lst in section[1:]:
954
          if lst[0] == "address":
955
            data["remote_addr"] = tuple(lst[1:])
956
    return data
957

    
958
  def _MatchesLocal(self, info):
959
    """Test if our local config matches with an existing device.
960

961
    The parameter should be as returned from `_GetDevInfo()`. This
962
    method tests if our local backing device is the same as the one in
963
    the info parameter, in effect testing if we look like the given
964
    device.
965

966
    """
967
    if self._children:
968
      backend, meta = self._children
969
    else:
970
      backend = meta = None
971

    
972
    if backend is not None:
973
      retval = ("local_dev" in info and info["local_dev"] == backend.dev_path)
974
    else:
975
      retval = ("local_dev" not in info)
976

    
977
    if meta is not None:
978
      retval = retval and ("meta_dev" in info and
979
                           info["meta_dev"] == meta.dev_path)
980
      retval = retval and ("meta_index" in info and
981
                           info["meta_index"] == 0)
982
    else:
983
      retval = retval and ("meta_dev" not in info and
984
                           "meta_index" not in info)
985
    return retval
986

    
987
  def _MatchesNet(self, info):
988
    """Test if our network config matches with an existing device.
989

990
    The parameter should be as returned from `_GetDevInfo()`. This
991
    method tests if our network configuration is the same as the one
992
    in the info parameter, in effect testing if we look like the given
993
    device.
994

995
    """
996
    if (((self._lhost is None and not ("local_addr" in info)) and
997
         (self._rhost is None and not ("remote_addr" in info)))):
998
      return True
999

    
1000
    if self._lhost is None:
1001
      return False
1002

    
1003
    if not ("local_addr" in info and
1004
            "remote_addr" in info):
1005
      return False
1006

    
1007
    retval = (info["local_addr"] == (self._lhost, self._lport))
1008
    retval = (retval and
1009
              info["remote_addr"] == (self._rhost, self._rport))
1010
    return retval
1011

    
1012
  @classmethod
1013
  def _AssembleLocal(cls, minor, backend, meta):
1014
    """Configure the local part of a DRBD device.
1015

1016
    This is the first thing that must be done on an unconfigured DRBD
1017
    device. And it must be done only once.
1018

1019
    """
1020
    if not cls._IsValidMeta(meta):
1021
      return False
1022
    args = ["drbdsetup", cls._DevPath(minor), "disk",
1023
            backend, meta, "0", "-e", "detach", "--create-device"]
1024
    result = utils.RunCmd(args)
1025
    if result.failed:
1026
      logging.error("Can't attach local disk: %s", result.output)
1027
    return not result.failed
1028

    
1029
  @classmethod
1030
  def _AssembleNet(cls, minor, net_info, protocol,
1031
                   dual_pri=False, hmac=None, secret=None):
1032
    """Configure the network part of the device.
1033

1034
    """
1035
    lhost, lport, rhost, rport = net_info
1036
    if None in net_info:
1037
      # we don't want network connection and actually want to make
1038
      # sure its shutdown
1039
      return cls._ShutdownNet(minor)
1040

    
1041
    # Workaround for a race condition. When DRBD is doing its dance to
1042
    # establish a connection with its peer, it also sends the
1043
    # synchronization speed over the wire. In some cases setting the
1044
    # sync speed only after setting up both sides can race with DRBD
1045
    # connecting, hence we set it here before telling DRBD anything
1046
    # about its peer.
1047
    cls._SetMinorSyncSpeed(minor, constants.SYNC_SPEED)
1048

    
1049
    args = ["drbdsetup", cls._DevPath(minor), "net",
1050
            "%s:%s" % (lhost, lport), "%s:%s" % (rhost, rport), protocol,
1051
            "-A", "discard-zero-changes",
1052
            "-B", "consensus",
1053
            "--create-device",
1054
            ]
1055
    if dual_pri:
1056
      args.append("-m")
1057
    if hmac and secret:
1058
      args.extend(["-a", hmac, "-x", secret])
1059
    result = utils.RunCmd(args)
1060
    if result.failed:
1061
      logging.error("Can't setup network for dbrd device: %s - %s",
1062
                    result.fail_reason, result.output)
1063
      return False
1064

    
1065
    timeout = time.time() + 10
1066
    ok = False
1067
    while time.time() < timeout:
1068
      info = cls._GetDevInfo(cls._GetShowData(minor))
1069
      if not "local_addr" in info or not "remote_addr" in info:
1070
        time.sleep(1)
1071
        continue
1072
      if (info["local_addr"] != (lhost, lport) or
1073
          info["remote_addr"] != (rhost, rport)):
1074
        time.sleep(1)
1075
        continue
1076
      ok = True
1077
      break
1078
    if not ok:
1079
      logging.error("Timeout while configuring network")
1080
      return False
1081
    return True
1082

    
1083
  def AddChildren(self, devices):
1084
    """Add a disk to the DRBD device.
1085

1086
    """
1087
    if self.minor is None:
1088
      raise errors.BlockDeviceError("Can't attach to dbrd8 during AddChildren")
1089
    if len(devices) != 2:
1090
      raise errors.BlockDeviceError("Need two devices for AddChildren")
1091
    info = self._GetDevInfo(self._GetShowData(self.minor))
1092
    if "local_dev" in info:
1093
      raise errors.BlockDeviceError("DRBD8 already attached to a local disk")
1094
    backend, meta = devices
1095
    if backend.dev_path is None or meta.dev_path is None:
1096
      raise errors.BlockDeviceError("Children not ready during AddChildren")
1097
    backend.Open()
1098
    meta.Open()
1099
    if not self._CheckMetaSize(meta.dev_path):
1100
      raise errors.BlockDeviceError("Invalid meta device size")
1101
    self._InitMeta(self._FindUnusedMinor(), meta.dev_path)
1102
    if not self._IsValidMeta(meta.dev_path):
1103
      raise errors.BlockDeviceError("Cannot initalize meta device")
1104

    
1105
    if not self._AssembleLocal(self.minor, backend.dev_path, meta.dev_path):
1106
      raise errors.BlockDeviceError("Can't attach to local storage")
1107
    self._children = devices
1108

    
1109
  def RemoveChildren(self, devices):
1110
    """Detach the drbd device from local storage.
1111

1112
    """
1113
    if self.minor is None:
1114
      raise errors.BlockDeviceError("Can't attach to drbd8 during"
1115
                                    " RemoveChildren")
1116
    # early return if we don't actually have backing storage
1117
    info = self._GetDevInfo(self._GetShowData(self.minor))
1118
    if "local_dev" not in info:
1119
      return
1120
    if len(self._children) != 2:
1121
      raise errors.BlockDeviceError("We don't have two children: %s" %
1122
                                    self._children)
1123
    if self._children.count(None) == 2: # we don't actually have children :)
1124
      logging.error("Requested detach while detached")
1125
      return
1126
    if len(devices) != 2:
1127
      raise errors.BlockDeviceError("We need two children in RemoveChildren")
1128
    for child, dev in zip(self._children, devices):
1129
      if dev != child.dev_path:
1130
        raise errors.BlockDeviceError("Mismatch in local storage"
1131
                                      " (%s != %s) in RemoveChildren" %
1132
                                      (dev, child.dev_path))
1133

    
1134
    if not self._ShutdownLocal(self.minor):
1135
      raise errors.BlockDeviceError("Can't detach from local storage")
1136
    self._children = []
1137

    
1138
  @classmethod
1139
  def _SetMinorSyncSpeed(cls, minor, kbytes):
1140
    """Set the speed of the DRBD syncer.
1141

1142
    This is the low-level implementation.
1143

1144
    @type minor: int
1145
    @param minor: the drbd minor whose settings we change
1146
    @type kbytes: int
1147
    @param kbytes: the speed in kbytes/second
1148
    @rtype: boolean
1149
    @return: the success of the operation
1150

1151
    """
1152
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "syncer",
1153
                           "-r", "%d" % kbytes, "--create-device"])
1154
    if result.failed:
1155
      logging.error("Can't change syncer rate: %s - %s",
1156
                    result.fail_reason, result.output)
1157
    return not result.failed
1158

    
1159
  def SetSyncSpeed(self, kbytes):
1160
    """Set the speed of the DRBD syncer.
1161

1162
    @type kbytes: int
1163
    @param kbytes: the speed in kbytes/second
1164
    @rtype: boolean
1165
    @return: the success of the operation
1166

1167
    """
1168
    if self.minor is None:
1169
      logging.info("Not attached during SetSyncSpeed")
1170
      return False
1171
    children_result = super(DRBD8, self).SetSyncSpeed(kbytes)
1172
    return self._SetMinorSyncSpeed(self.minor, kbytes) and children_result
1173

    
1174
  def GetProcStatus(self):
1175
    """Return device data from /proc.
1176

1177
    """
1178
    if self.minor is None:
1179
      raise errors.BlockDeviceError("GetStats() called while not attached")
1180
    proc_info = self._MassageProcData(self._GetProcData())
1181
    if self.minor not in proc_info:
1182
      raise errors.BlockDeviceError("Can't find myself in /proc (minor %d)" %
1183
                                    self.minor)
1184
    return DRBD8Status(proc_info[self.minor])
1185

    
1186
  def GetSyncStatus(self):
1187
    """Returns the sync status of the device.
1188

1189

1190
    If sync_percent is None, it means all is ok
1191
    If estimated_time is None, it means we can't esimate
1192
    the time needed, otherwise it's the time left in seconds.
1193

1194

1195
    We set the is_degraded parameter to True on two conditions:
1196
    network not connected or local disk missing.
1197

1198
    We compute the ldisk parameter based on wheter we have a local
1199
    disk or not.
1200

1201
    @rtype: tuple
1202
    @return: (sync_percent, estimated_time, is_degraded, ldisk)
1203

1204
    """
1205
    if self.minor is None and not self.Attach():
1206
      raise errors.BlockDeviceError("Can't attach to device in GetSyncStatus")
1207
    stats = self.GetProcStatus()
1208
    ldisk = not stats.is_disk_uptodate
1209
    is_degraded = not stats.is_connected
1210
    return stats.sync_percent, stats.est_time, is_degraded or ldisk, ldisk
1211

    
1212
  def Open(self, force=False):
1213
    """Make the local state primary.
1214

1215
    If the 'force' parameter is given, the '-o' option is passed to
1216
    drbdsetup. Since this is a potentially dangerous operation, the
1217
    force flag should be only given after creation, when it actually
1218
    is mandatory.
1219

1220
    """
1221
    if self.minor is None and not self.Attach():
1222
      logging.error("DRBD cannot attach to a device during open")
1223
      return False
1224
    cmd = ["drbdsetup", self.dev_path, "primary"]
1225
    if force:
1226
      cmd.append("-o")
1227
    result = utils.RunCmd(cmd)
1228
    if result.failed:
1229
      msg = ("Can't make drbd device primary: %s" % result.output)
1230
      logging.error(msg)
1231
      raise errors.BlockDeviceError(msg)
1232

    
1233
  def Close(self):
1234
    """Make the local state secondary.
1235

1236
    This will, of course, fail if the device is in use.
1237

1238
    """
1239
    if self.minor is None and not self.Attach():
1240
      logging.info("Instance not attached to a device")
1241
      raise errors.BlockDeviceError("Can't find device")
1242
    result = utils.RunCmd(["drbdsetup", self.dev_path, "secondary"])
1243
    if result.failed:
1244
      msg = ("Can't switch drbd device to"
1245
             " secondary: %s" % result.output)
1246
      logging.error(msg)
1247
      raise errors.BlockDeviceError(msg)
1248

    
1249
  def DisconnectNet(self):
1250
    """Removes network configuration.
1251

1252
    This method shutdowns the network side of the device.
1253

1254
    The method will wait up to a hardcoded timeout for the device to
1255
    go into standalone after the 'disconnect' command before
1256
    re-configuring it, as sometimes it takes a while for the
1257
    disconnect to actually propagate and thus we might issue a 'net'
1258
    command while the device is still connected. If the device will
1259
    still be attached to the network and we time out, we raise an
1260
    exception.
1261

1262
    """
1263
    if self.minor is None:
1264
      raise errors.BlockDeviceError("DRBD disk not attached in re-attach net")
1265

    
1266
    if None in (self._lhost, self._lport, self._rhost, self._rport):
1267
      raise errors.BlockDeviceError("DRBD disk missing network info in"
1268
                                    " DisconnectNet()")
1269

    
1270
    ever_disconnected = self._ShutdownNet(self.minor)
1271
    timeout_limit = time.time() + self._NET_RECONFIG_TIMEOUT
1272
    sleep_time = 0.100 # we start the retry time at 100 miliseconds
1273
    while time.time() < timeout_limit:
1274
      status = self.GetProcStatus()
1275
      if status.is_standalone:
1276
        break
1277
      # retry the disconnect, it seems possible that due to a
1278
      # well-time disconnect on the peer, my disconnect command might
1279
      # be ingored and forgotten
1280
      ever_disconnected = self._ShutdownNet(self.minor) or ever_disconnected
1281
      time.sleep(sleep_time)
1282
      sleep_time = min(2, sleep_time * 1.5)
1283

    
1284
    if not status.is_standalone:
1285
      if ever_disconnected:
1286
        msg = ("Device did not react to the"
1287
               " 'disconnect' command in a timely manner")
1288
      else:
1289
        msg = ("Can't shutdown network, even after multiple retries")
1290
      raise errors.BlockDeviceError(msg)
1291

    
1292
    reconfig_time = time.time() - timeout_limit + self._NET_RECONFIG_TIMEOUT
1293
    if reconfig_time > 15: # hardcoded alert limit
1294
      logging.debug("DRBD8.DisconnectNet: detach took %.3f seconds",
1295
                    reconfig_time)
1296

    
1297
  def AttachNet(self, multimaster):
1298
    """Reconnects the network.
1299

1300
    This method connects the network side of the device with a
1301
    specified multi-master flag. The device needs to be 'Standalone'
1302
    but have valid network configuration data.
1303

1304
    Args:
1305
      - multimaster: init the network in dual-primary mode
1306

1307
    """
1308
    if self.minor is None:
1309
      raise errors.BlockDeviceError("DRBD disk not attached in AttachNet")
1310

    
1311
    if None in (self._lhost, self._lport, self._rhost, self._rport):
1312
      raise errors.BlockDeviceError("DRBD disk missing network info in"
1313
                                    " AttachNet()")
1314

    
1315
    status = self.GetProcStatus()
1316

    
1317
    if not status.is_standalone:
1318
      raise errors.BlockDeviceError("Device is not standalone in AttachNet")
1319

    
1320
    return self._AssembleNet(self.minor,
1321
                             (self._lhost, self._lport,
1322
                              self._rhost, self._rport),
1323
                             "C", dual_pri=multimaster)
1324

    
1325
  def Attach(self):
1326
    """Check if our minor is configured.
1327

1328
    This doesn't do any device configurations - it only checks if the
1329
    minor is in a state different from Unconfigured.
1330

1331
    Note that this function will not change the state of the system in
1332
    any way (except in case of side-effects caused by reading from
1333
    /proc).
1334

1335
    """
1336
    used_devs = self._GetUsedDevs()
1337
    if self._aminor in used_devs:
1338
      minor = self._aminor
1339
    else:
1340
      minor = None
1341

    
1342
    self._SetFromMinor(minor)
1343
    return minor is not None
1344

    
1345
  def Assemble(self):
1346
    """Assemble the drbd.
1347

1348
    Method:
1349
      - if we have a configured device, we try to ensure that it matches
1350
        our config
1351
      - if not, we create it from zero
1352

1353
    """
1354
    result = super(DRBD8, self).Assemble()
1355
    if not result:
1356
      return result
1357

    
1358
    self.Attach()
1359
    if self.minor is None:
1360
      # local device completely unconfigured
1361
      return self._FastAssemble()
1362
    else:
1363
      # we have to recheck the local and network status and try to fix
1364
      # the device
1365
      return self._SlowAssemble()
1366

    
1367
  def _SlowAssemble(self):
1368
    """Assembles the DRBD device from a (partially) configured device.
1369

1370
    In case of partially attached (local device matches but no network
1371
    setup), we perform the network attach. If successful, we re-test
1372
    the attach if can return success.
1373

1374
    """
1375
    for minor in (self._aminor,):
1376
      info = self._GetDevInfo(self._GetShowData(minor))
1377
      match_l = self._MatchesLocal(info)
1378
      match_r = self._MatchesNet(info)
1379
      if match_l and match_r:
1380
        break
1381
      if match_l and not match_r and "local_addr" not in info:
1382
        res_r = self._AssembleNet(minor,
1383
                                  (self._lhost, self._lport,
1384
                                   self._rhost, self._rport),
1385
                                  constants.DRBD_NET_PROTOCOL,
1386
                                  hmac=constants.DRBD_HMAC_ALG,
1387
                                  secret=self._secret
1388
                                  )
1389
        if res_r:
1390
          if self._MatchesNet(self._GetDevInfo(self._GetShowData(minor))):
1391
            break
1392
      # the weakest case: we find something that is only net attached
1393
      # even though we were passed some children at init time
1394
      if match_r and "local_dev" not in info:
1395
        break
1396

    
1397
      # this case must be considered only if we actually have local
1398
      # storage, i.e. not in diskless mode, because all diskless
1399
      # devices are equal from the point of view of local
1400
      # configuration
1401
      if (match_l and "local_dev" in info and
1402
          not match_r and "local_addr" in info):
1403
        # strange case - the device network part points to somewhere
1404
        # else, even though its local storage is ours; as we own the
1405
        # drbd space, we try to disconnect from the remote peer and
1406
        # reconnect to our correct one
1407
        if not self._ShutdownNet(minor):
1408
          raise errors.BlockDeviceError("Device has correct local storage,"
1409
                                        " wrong remote peer and is unable to"
1410
                                        " disconnect in order to attach to"
1411
                                        " the correct peer")
1412
        # note: _AssembleNet also handles the case when we don't want
1413
        # local storage (i.e. one or more of the _[lr](host|port) is
1414
        # None)
1415
        if (self._AssembleNet(minor, (self._lhost, self._lport,
1416
                                      self._rhost, self._rport),
1417
                              constants.DRBD_NET_PROTOCOL,
1418
                              hmac=constants.DRBD_HMAC_ALG,
1419
                              secret=self._secret) and
1420
            self._MatchesNet(self._GetDevInfo(self._GetShowData(minor)))):
1421
          break
1422

    
1423
    else:
1424
      minor = None
1425

    
1426
    self._SetFromMinor(minor)
1427
    return minor is not None
1428

    
1429
  def _FastAssemble(self):
1430
    """Assemble the drbd device from zero.
1431

1432
    This is run when in Assemble we detect our minor is unused.
1433

1434
    """
1435
    # TODO: maybe completely tear-down the minor (drbdsetup ... down)
1436
    # before attaching our own?
1437
    minor = self._aminor
1438
    need_localdev_teardown = False
1439
    if self._children and self._children[0] and self._children[1]:
1440
      result = self._AssembleLocal(minor, self._children[0].dev_path,
1441
                                   self._children[1].dev_path)
1442
      if not result:
1443
        return False
1444
      need_localdev_teardown = True
1445
    if self._lhost and self._lport and self._rhost and self._rport:
1446
      result = self._AssembleNet(minor,
1447
                                 (self._lhost, self._lport,
1448
                                  self._rhost, self._rport),
1449
                                 constants.DRBD_NET_PROTOCOL,
1450
                                 hmac=constants.DRBD_HMAC_ALG,
1451
                                 secret=self._secret)
1452
      if not result:
1453
        if need_localdev_teardown:
1454
          # we will ignore failures from this
1455
          logging.error("net setup failed, tearing down local device")
1456
          self._ShutdownAll(minor)
1457
        return False
1458
    self._SetFromMinor(minor)
1459
    return True
1460

    
1461
  @classmethod
1462
  def _ShutdownLocal(cls, minor):
1463
    """Detach from the local device.
1464

1465
    I/Os will continue to be served from the remote device. If we
1466
    don't have a remote device, this operation will fail.
1467

1468
    """
1469
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "detach"])
1470
    if result.failed:
1471
      logging.error("Can't detach local device: %s", result.output)
1472
    return not result.failed
1473

    
1474
  @classmethod
1475
  def _ShutdownNet(cls, minor):
1476
    """Disconnect from the remote peer.
1477

1478
    This fails if we don't have a local device.
1479

1480
    """
1481
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "disconnect"])
1482
    if result.failed:
1483
      logging.error("Can't shutdown network: %s", result.output)
1484
    return not result.failed
1485

    
1486
  @classmethod
1487
  def _ShutdownAll(cls, minor):
1488
    """Deactivate the device.
1489

1490
    This will, of course, fail if the device is in use.
1491

1492
    """
1493
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "down"])
1494
    if result.failed:
1495
      logging.error("Can't shutdown drbd device: %s", result.output)
1496
    return not result.failed
1497

    
1498
  def Shutdown(self):
1499
    """Shutdown the DRBD device.
1500

1501
    """
1502
    if self.minor is None and not self.Attach():
1503
      logging.info("DRBD device not attached to a device during Shutdown")
1504
      return True
1505
    if not self._ShutdownAll(self.minor):
1506
      return False
1507
    self.minor = None
1508
    self.dev_path = None
1509
    return True
1510

    
1511
  def Remove(self):
1512
    """Stub remove for DRBD devices.
1513

1514
    """
1515
    return self.Shutdown()
1516

    
1517
  @classmethod
1518
  def Create(cls, unique_id, children, size):
1519
    """Create a new DRBD8 device.
1520

1521
    Since DRBD devices are not created per se, just assembled, this
1522
    function only initializes the metadata.
1523

1524
    """
1525
    if len(children) != 2:
1526
      raise errors.ProgrammerError("Invalid setup for the drbd device")
1527
    meta = children[1]
1528
    meta.Assemble()
1529
    if not meta.Attach():
1530
      raise errors.BlockDeviceError("Can't attach to meta device")
1531
    if not cls._CheckMetaSize(meta.dev_path):
1532
      raise errors.BlockDeviceError("Invalid meta device size")
1533
    cls._InitMeta(cls._FindUnusedMinor(), meta.dev_path)
1534
    if not cls._IsValidMeta(meta.dev_path):
1535
      raise errors.BlockDeviceError("Cannot initalize meta device")
1536
    return cls(unique_id, children)
1537

    
1538
  def Grow(self, amount):
1539
    """Resize the DRBD device and its backing storage.
1540

1541
    """
1542
    if self.minor is None:
1543
      raise errors.ProgrammerError("drbd8: Grow called while not attached")
1544
    if len(self._children) != 2 or None in self._children:
1545
      raise errors.BlockDeviceError("Cannot grow diskless DRBD8 device")
1546
    self._children[0].Grow(amount)
1547
    result = utils.RunCmd(["drbdsetup", self.dev_path, "resize"])
1548
    if result.failed:
1549
      raise errors.BlockDeviceError("resize failed for %s: %s" %
1550
                                    (self.dev_path, result.output))
1551
    return
1552

    
1553

    
1554
class FileStorage(BlockDev):
1555
  """File device.
1556

1557
  This class represents the a file storage backend device.
1558

1559
  The unique_id for the file device is a (file_driver, file_path) tuple.
1560

1561
  """
1562
  def __init__(self, unique_id, children):
1563
    """Initalizes a file device backend.
1564

1565
    """
1566
    if children:
1567
      raise errors.BlockDeviceError("Invalid setup for file device")
1568
    super(FileStorage, self).__init__(unique_id, children)
1569
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 2:
1570
      raise ValueError("Invalid configuration data %s" % str(unique_id))
1571
    self.driver = unique_id[0]
1572
    self.dev_path = unique_id[1]
1573
    self.Attach()
1574

    
1575
  def Assemble(self):
1576
    """Assemble the device.
1577

1578
    Checks whether the file device exists, raises BlockDeviceError otherwise.
1579

1580
    """
1581
    if not os.path.exists(self.dev_path):
1582
      raise errors.BlockDeviceError("File device '%s' does not exist." %
1583
                                    self.dev_path)
1584
    return True
1585

    
1586
  def Shutdown(self):
1587
    """Shutdown the device.
1588

1589
    This is a no-op for the file type, as we don't deacivate
1590
    the file on shutdown.
1591

1592
    """
1593
    return True
1594

    
1595
  def Open(self, force=False):
1596
    """Make the device ready for I/O.
1597

1598
    This is a no-op for the file type.
1599

1600
    """
1601
    pass
1602

    
1603
  def Close(self):
1604
    """Notifies that the device will no longer be used for I/O.
1605

1606
    This is a no-op for the file type.
1607

1608
    """
1609
    pass
1610

    
1611
  def Remove(self):
1612
    """Remove the file backing the block device.
1613

1614
    @rtype: boolean
1615
    @return: True if the removal was successful
1616

1617
    """
1618
    if not os.path.exists(self.dev_path):
1619
      return True
1620
    try:
1621
      os.remove(self.dev_path)
1622
      return True
1623
    except OSError, err:
1624
      logging.error("Can't remove file '%s': %s", self.dev_path, err)
1625
      return False
1626

    
1627
  def Attach(self):
1628
    """Attach to an existing file.
1629

1630
    Check if this file already exists.
1631

1632
    @rtype: boolean
1633
    @return: True if file exists
1634

1635
    """
1636
    self.attached = os.path.exists(self.dev_path)
1637
    return self.attached
1638

    
1639
  @classmethod
1640
  def Create(cls, unique_id, children, size):
1641
    """Create a new file.
1642

1643
    @param size: the size of file in MiB
1644

1645
    @rtype: L{bdev.FileStorage}
1646
    @return: an instance of FileStorage
1647

1648
    """
1649
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 2:
1650
      raise ValueError("Invalid configuration data %s" % str(unique_id))
1651
    dev_path = unique_id[1]
1652
    try:
1653
      f = open(dev_path, 'w')
1654
    except IOError, err:
1655
      raise errors.BlockDeviceError("Could not create '%'" % err)
1656
    else:
1657
      f.truncate(size * 1024 * 1024)
1658
      f.close()
1659

    
1660
    return FileStorage(unique_id, children)
1661

    
1662

    
1663
DEV_MAP = {
1664
  constants.LD_LV: LogicalVolume,
1665
  constants.LD_DRBD8: DRBD8,
1666
  constants.LD_FILE: FileStorage,
1667
  }
1668

    
1669

    
1670
def FindDevice(dev_type, unique_id, children):
1671
  """Search for an existing, assembled device.
1672

1673
  This will succeed only if the device exists and is assembled, but it
1674
  does not do any actions in order to activate the device.
1675

1676
  """
1677
  if dev_type not in DEV_MAP:
1678
    raise errors.ProgrammerError("Invalid block device type '%s'" % dev_type)
1679
  device = DEV_MAP[dev_type](unique_id, children)
1680
  if not device.attached:
1681
    return None
1682
  return device
1683

    
1684

    
1685
def Assemble(dev_type, unique_id, children):
1686
  """Try to attach or assemble an existing device.
1687

1688
  This will attach to assemble the device, as needed, to bring it
1689
  fully up. It must be safe to run on already-assembled devices.
1690

1691
  """
1692
  if dev_type not in DEV_MAP:
1693
    raise errors.ProgrammerError("Invalid block device type '%s'" % dev_type)
1694
  device = DEV_MAP[dev_type](unique_id, children)
1695
  if not device.Assemble():
1696
    raise errors.BlockDeviceError("Can't find a valid block device for"
1697
                                  " %s/%s/%s" %
1698
                                  (dev_type, unique_id, children))
1699
  return device
1700

    
1701

    
1702
def Create(dev_type, unique_id, children, size):
1703
  """Create a device.
1704

1705
  """
1706
  if dev_type not in DEV_MAP:
1707
    raise errors.ProgrammerError("Invalid block device type '%s'" % dev_type)
1708
  device = DEV_MAP[dev_type].Create(unique_id, children, size)
1709
  return device