Statistics
| Branch: | Tag: | Revision:

root / lib / bdev.py @ f96e3c4f

History | View | Annotate | Download (54.1 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 a8083063 Iustin Pop
"""Block device abstraction"""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
import re
25 a8083063 Iustin Pop
import time
26 a8083063 Iustin Pop
import errno
27 a2cfdea2 Iustin Pop
import pyparsing as pyp
28 6f695a2e Manuel Franceschini
import os
29 468c5f77 Iustin Pop
import logging
30 a8083063 Iustin Pop
31 a8083063 Iustin Pop
from ganeti import utils
32 a8083063 Iustin Pop
from ganeti import errors
33 fe96220b Iustin Pop
from ganeti import constants
34 a8083063 Iustin Pop
35 a8083063 Iustin Pop
36 a8083063 Iustin Pop
class BlockDev(object):
37 a8083063 Iustin Pop
  """Block device abstract class.
38 a8083063 Iustin Pop

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

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

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

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

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

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

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

78 a8083063 Iustin Pop
  """
79 a8083063 Iustin Pop
  def __init__(self, unique_id, children):
80 a8083063 Iustin Pop
    self._children = children
81 a8083063 Iustin Pop
    self.dev_path = None
82 a8083063 Iustin Pop
    self.unique_id = unique_id
83 a8083063 Iustin Pop
    self.major = None
84 a8083063 Iustin Pop
    self.minor = None
85 cb999543 Iustin Pop
    self.attached = False
86 a8083063 Iustin Pop
87 a8083063 Iustin Pop
  def Assemble(self):
88 a8083063 Iustin Pop
    """Assemble the device from its components.
89 a8083063 Iustin Pop

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

98 a8083063 Iustin Pop
    """
99 f87548b5 Iustin Pop
    return True
100 a8083063 Iustin Pop
101 a8083063 Iustin Pop
  def Attach(self):
102 a8083063 Iustin Pop
    """Find a device which matches our config and attach to it.
103 a8083063 Iustin Pop

104 a8083063 Iustin Pop
    """
105 a8083063 Iustin Pop
    raise NotImplementedError
106 a8083063 Iustin Pop
107 a8083063 Iustin Pop
  def Close(self):
108 a8083063 Iustin Pop
    """Notifies that the device will no longer be used for I/O.
109 a8083063 Iustin Pop

110 a8083063 Iustin Pop
    """
111 a8083063 Iustin Pop
    raise NotImplementedError
112 a8083063 Iustin Pop
113 a8083063 Iustin Pop
  @classmethod
114 a8083063 Iustin Pop
  def Create(cls, unique_id, children, size):
115 a8083063 Iustin Pop
    """Create the device.
116 a8083063 Iustin Pop

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

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

124 a8083063 Iustin Pop
    """
125 a8083063 Iustin Pop
    raise NotImplementedError
126 a8083063 Iustin Pop
127 a8083063 Iustin Pop
  def Remove(self):
128 a8083063 Iustin Pop
    """Remove this device.
129 a8083063 Iustin Pop

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

134 a8083063 Iustin Pop
    """
135 a8083063 Iustin Pop
    raise NotImplementedError
136 a8083063 Iustin Pop
137 f3e513ad Iustin Pop
  def Rename(self, new_id):
138 f3e513ad Iustin Pop
    """Rename this device.
139 f3e513ad Iustin Pop

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

142 f3e513ad Iustin Pop
    """
143 f3e513ad Iustin Pop
    raise NotImplementedError
144 f3e513ad Iustin Pop
145 a8083063 Iustin Pop
  def Open(self, force=False):
146 a8083063 Iustin Pop
    """Make the device ready for use.
147 a8083063 Iustin Pop

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

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

154 a8083063 Iustin Pop
    """
155 a8083063 Iustin Pop
    raise NotImplementedError
156 a8083063 Iustin Pop
157 a8083063 Iustin Pop
  def Shutdown(self):
158 a8083063 Iustin Pop
    """Shut down the device, freeing its children.
159 a8083063 Iustin Pop

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

164 a8083063 Iustin Pop
    """
165 a8083063 Iustin Pop
    raise NotImplementedError
166 a8083063 Iustin Pop
167 a8083063 Iustin Pop
  def SetSyncSpeed(self, speed):
168 a8083063 Iustin Pop
    """Adjust the sync speed of the mirror.
169 a8083063 Iustin Pop

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

172 a8083063 Iustin Pop
    """
173 a8083063 Iustin Pop
    result = True
174 a8083063 Iustin Pop
    if self._children:
175 a8083063 Iustin Pop
      for child in self._children:
176 a8083063 Iustin Pop
        result = result and child.SetSyncSpeed(speed)
177 a8083063 Iustin Pop
    return result
178 a8083063 Iustin Pop
179 a8083063 Iustin Pop
  def GetSyncStatus(self):
180 a8083063 Iustin Pop
    """Returns the sync status of the device.
181 a8083063 Iustin Pop

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

185 0834c866 Iustin Pop
    If sync_percent is None, it means the device is not syncing.
186 a8083063 Iustin Pop

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

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

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

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

201 a8083063 Iustin Pop
    """
202 0834c866 Iustin Pop
    return None, None, False, False
203 a8083063 Iustin Pop
204 a8083063 Iustin Pop
205 a8083063 Iustin Pop
  def CombinedSyncStatus(self):
206 a8083063 Iustin Pop
    """Calculate the mirror status recursively for our children.
207 a8083063 Iustin Pop

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

212 a8083063 Iustin Pop
    """
213 0834c866 Iustin Pop
    min_percent, max_time, is_degraded, ldisk = self.GetSyncStatus()
214 a8083063 Iustin Pop
    if self._children:
215 a8083063 Iustin Pop
      for child in self._children:
216 0834c866 Iustin Pop
        c_percent, c_time, c_degraded, c_ldisk = child.GetSyncStatus()
217 a8083063 Iustin Pop
        if min_percent is None:
218 a8083063 Iustin Pop
          min_percent = c_percent
219 a8083063 Iustin Pop
        elif c_percent is not None:
220 a8083063 Iustin Pop
          min_percent = min(min_percent, c_percent)
221 a8083063 Iustin Pop
        if max_time is None:
222 a8083063 Iustin Pop
          max_time = c_time
223 a8083063 Iustin Pop
        elif c_time is not None:
224 a8083063 Iustin Pop
          max_time = max(max_time, c_time)
225 a8083063 Iustin Pop
        is_degraded = is_degraded or c_degraded
226 0834c866 Iustin Pop
        ldisk = ldisk or c_ldisk
227 0834c866 Iustin Pop
    return min_percent, max_time, is_degraded, ldisk
228 a8083063 Iustin Pop
229 a8083063 Iustin Pop
230 a0c3fea1 Michael Hanselmann
  def SetInfo(self, text):
231 a0c3fea1 Michael Hanselmann
    """Update metadata with info text.
232 a0c3fea1 Michael Hanselmann

233 a0c3fea1 Michael Hanselmann
    Only supported for some device types.
234 a0c3fea1 Michael Hanselmann

235 a0c3fea1 Michael Hanselmann
    """
236 a0c3fea1 Michael Hanselmann
    for child in self._children:
237 a0c3fea1 Michael Hanselmann
      child.SetInfo(text)
238 a0c3fea1 Michael Hanselmann
239 1005d816 Iustin Pop
  def Grow(self, amount):
240 1005d816 Iustin Pop
    """Grow the block device.
241 1005d816 Iustin Pop

242 c41eea6e Iustin Pop
    @param amount: the amount (in mebibytes) to grow with
243 1005d816 Iustin Pop

244 1005d816 Iustin Pop
    """
245 1005d816 Iustin Pop
    raise NotImplementedError
246 a0c3fea1 Michael Hanselmann
247 a8083063 Iustin Pop
  def __repr__(self):
248 a8083063 Iustin Pop
    return ("<%s: unique_id: %s, children: %s, %s:%s, %s>" %
249 a8083063 Iustin Pop
            (self.__class__, self.unique_id, self._children,
250 a8083063 Iustin Pop
             self.major, self.minor, self.dev_path))
251 a8083063 Iustin Pop
252 a8083063 Iustin Pop
253 a8083063 Iustin Pop
class LogicalVolume(BlockDev):
254 a8083063 Iustin Pop
  """Logical Volume block device.
255 a8083063 Iustin Pop

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

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

262 a8083063 Iustin Pop
    """
263 a8083063 Iustin Pop
    super(LogicalVolume, self).__init__(unique_id, children)
264 a8083063 Iustin Pop
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 2:
265 a8083063 Iustin Pop
      raise ValueError("Invalid configuration data %s" % str(unique_id))
266 a8083063 Iustin Pop
    self._vg_name, self._lv_name = unique_id
267 a8083063 Iustin Pop
    self.dev_path = "/dev/%s/%s" % (self._vg_name, self._lv_name)
268 99e8295c Iustin Pop
    self._degraded = True
269 99e8295c Iustin Pop
    self.major = self.minor = None
270 a8083063 Iustin Pop
    self.Attach()
271 a8083063 Iustin Pop
272 a8083063 Iustin Pop
  @classmethod
273 a8083063 Iustin Pop
  def Create(cls, unique_id, children, size):
274 a8083063 Iustin Pop
    """Create a new logical volume.
275 a8083063 Iustin Pop

276 a8083063 Iustin Pop
    """
277 a8083063 Iustin Pop
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 2:
278 a8083063 Iustin Pop
      raise ValueError("Invalid configuration data %s" % str(unique_id))
279 a8083063 Iustin Pop
    vg_name, lv_name = unique_id
280 a8083063 Iustin Pop
    pvs_info = cls.GetPVInfo(vg_name)
281 a8083063 Iustin Pop
    if not pvs_info:
282 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't compute PV info for vg %s" %
283 3ecf6786 Iustin Pop
                                    vg_name)
284 a8083063 Iustin Pop
    pvs_info.sort()
285 a8083063 Iustin Pop
    pvs_info.reverse()
286 5b7b5d49 Guido Trotter
287 5b7b5d49 Guido Trotter
    pvlist = [ pv[1] for pv in pvs_info ]
288 5b7b5d49 Guido Trotter
    free_size = sum([ pv[0] for pv in pvs_info ])
289 5b7b5d49 Guido Trotter
290 5b7b5d49 Guido Trotter
    # The size constraint should have been checked from the master before
291 5b7b5d49 Guido Trotter
    # calling the create function.
292 a8083063 Iustin Pop
    if free_size < size:
293 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Not enough free space: required %s,"
294 3ecf6786 Iustin Pop
                                    " available %s" % (size, free_size))
295 a8083063 Iustin Pop
    result = utils.RunCmd(["lvcreate", "-L%dm" % size, "-n%s" % lv_name,
296 5b7b5d49 Guido Trotter
                           vg_name] + pvlist)
297 a8083063 Iustin Pop
    if result.failed:
298 6c896e2f Iustin Pop
      raise errors.BlockDeviceError("%s - %s" % (result.fail_reason,
299 6c896e2f Iustin Pop
                                                result.output))
300 a8083063 Iustin Pop
    return LogicalVolume(unique_id, children)
301 a8083063 Iustin Pop
302 a8083063 Iustin Pop
  @staticmethod
303 a8083063 Iustin Pop
  def GetPVInfo(vg_name):
304 a8083063 Iustin Pop
    """Get the free space info for PVs in a volume group.
305 a8083063 Iustin Pop

306 c41eea6e Iustin Pop
    @param vg_name: the volume group name
307 a8083063 Iustin Pop

308 c41eea6e Iustin Pop
    @rtype: list
309 c41eea6e Iustin Pop
    @return: list of tuples (free_space, name) with free_space in mebibytes
310 098c0958 Michael Hanselmann

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

336 a8083063 Iustin Pop
    """
337 a8083063 Iustin Pop
    if not self.minor and not self.Attach():
338 a8083063 Iustin Pop
      # the LV does not exist
339 a8083063 Iustin Pop
      return True
340 a8083063 Iustin Pop
    result = utils.RunCmd(["lvremove", "-f", "%s/%s" %
341 a8083063 Iustin Pop
                           (self._vg_name, self._lv_name)])
342 a8083063 Iustin Pop
    if result.failed:
343 468c5f77 Iustin Pop
      logging.error("Can't lvremove: %s - %s",
344 468c5f77 Iustin Pop
                    result.fail_reason, result.output)
345 a8083063 Iustin Pop
346 a8083063 Iustin Pop
    return not result.failed
347 a8083063 Iustin Pop
348 f3e513ad Iustin Pop
  def Rename(self, new_id):
349 f3e513ad Iustin Pop
    """Rename this logical volume.
350 f3e513ad Iustin Pop

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

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

373 a8083063 Iustin Pop
    """
374 cb999543 Iustin Pop
    self.attached = False
375 99e8295c Iustin Pop
    result = utils.RunCmd(["lvs", "--noheadings", "--separator=,",
376 99e8295c Iustin Pop
                           "-olv_attr,lv_kernel_major,lv_kernel_minor",
377 99e8295c Iustin Pop
                           self.dev_path])
378 a8083063 Iustin Pop
    if result.failed:
379 468c5f77 Iustin Pop
      logging.error("Can't find LV %s: %s, %s",
380 468c5f77 Iustin Pop
                    self.dev_path, result.fail_reason, result.output)
381 a8083063 Iustin Pop
      return False
382 99e8295c Iustin Pop
    out = result.stdout.strip().rstrip(',')
383 99e8295c Iustin Pop
    out = out.split(",")
384 99e8295c Iustin Pop
    if len(out) != 3:
385 468c5f77 Iustin Pop
      logging.error("Can't parse LVS output, len(%s) != 3", str(out))
386 99e8295c Iustin Pop
      return False
387 99e8295c Iustin Pop
388 99e8295c Iustin Pop
    status, major, minor = out[:3]
389 99e8295c Iustin Pop
    if len(status) != 6:
390 468c5f77 Iustin Pop
      logging.error("lvs lv_attr is not 6 characters (%s)", status)
391 99e8295c Iustin Pop
      return False
392 99e8295c Iustin Pop
393 99e8295c Iustin Pop
    try:
394 99e8295c Iustin Pop
      major = int(major)
395 99e8295c Iustin Pop
      minor = int(minor)
396 99e8295c Iustin Pop
    except ValueError, err:
397 468c5f77 Iustin Pop
      logging.error("lvs major/minor cannot be parsed: %s", str(err))
398 99e8295c Iustin Pop
399 99e8295c Iustin Pop
    self.major = major
400 99e8295c Iustin Pop
    self.minor = minor
401 99e8295c Iustin Pop
    self._degraded = status[0] == 'v' # virtual volume, i.e. doesn't backing
402 99e8295c Iustin Pop
                                      # storage
403 cb999543 Iustin Pop
    self.attached = True
404 99e8295c Iustin Pop
    return True
405 a8083063 Iustin Pop
406 a8083063 Iustin Pop
  def Assemble(self):
407 a8083063 Iustin Pop
    """Assemble the device.
408 a8083063 Iustin Pop

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

413 a8083063 Iustin Pop
    """
414 5574047a Iustin Pop
    result = utils.RunCmd(["lvchange", "-ay", self.dev_path])
415 5574047a Iustin Pop
    if result.failed:
416 468c5f77 Iustin Pop
      logging.error("Can't activate lv %s: %s", self.dev_path, result.output)
417 cb999543 Iustin Pop
      return False
418 cb999543 Iustin Pop
    return self.Attach()
419 a8083063 Iustin Pop
420 a8083063 Iustin Pop
  def Shutdown(self):
421 a8083063 Iustin Pop
    """Shutdown the device.
422 a8083063 Iustin Pop

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

426 a8083063 Iustin Pop
    """
427 a8083063 Iustin Pop
    return True
428 a8083063 Iustin Pop
429 9db6dbce Iustin Pop
  def GetSyncStatus(self):
430 9db6dbce Iustin Pop
    """Returns the sync status of the device.
431 9db6dbce Iustin Pop

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

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

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

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

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

451 9db6dbce Iustin Pop
    """
452 99e8295c Iustin Pop
    return None, None, self._degraded, self._degraded
453 9db6dbce Iustin Pop
454 a8083063 Iustin Pop
  def Open(self, force=False):
455 a8083063 Iustin Pop
    """Make the device ready for I/O.
456 a8083063 Iustin Pop

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

459 a8083063 Iustin Pop
    """
460 fdbd668d Iustin Pop
    pass
461 a8083063 Iustin Pop
462 a8083063 Iustin Pop
  def Close(self):
463 a8083063 Iustin Pop
    """Notifies that the device will no longer be used for I/O.
464 a8083063 Iustin Pop

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

467 a8083063 Iustin Pop
    """
468 fdbd668d Iustin Pop
    pass
469 a8083063 Iustin Pop
470 a8083063 Iustin Pop
  def Snapshot(self, size):
471 a8083063 Iustin Pop
    """Create a snapshot copy of an lvm block device.
472 a8083063 Iustin Pop

473 a8083063 Iustin Pop
    """
474 a8083063 Iustin Pop
    snap_name = self._lv_name + ".snap"
475 a8083063 Iustin Pop
476 a8083063 Iustin Pop
    # remove existing snapshot if found
477 a8083063 Iustin Pop
    snap = LogicalVolume((self._vg_name, snap_name), None)
478 a8083063 Iustin Pop
    snap.Remove()
479 a8083063 Iustin Pop
480 a8083063 Iustin Pop
    pvs_info = self.GetPVInfo(self._vg_name)
481 a8083063 Iustin Pop
    if not pvs_info:
482 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't compute PV info for vg %s" %
483 3ecf6786 Iustin Pop
                                    self._vg_name)
484 a8083063 Iustin Pop
    pvs_info.sort()
485 a8083063 Iustin Pop
    pvs_info.reverse()
486 a8083063 Iustin Pop
    free_size, pv_name = pvs_info[0]
487 a8083063 Iustin Pop
    if free_size < size:
488 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Not enough free space: required %s,"
489 3ecf6786 Iustin Pop
                                    " available %s" % (size, free_size))
490 a8083063 Iustin Pop
491 a8083063 Iustin Pop
    result = utils.RunCmd(["lvcreate", "-L%dm" % size, "-s",
492 a8083063 Iustin Pop
                           "-n%s" % snap_name, self.dev_path])
493 a8083063 Iustin Pop
    if result.failed:
494 6c896e2f Iustin Pop
      raise errors.BlockDeviceError("command: %s error: %s - %s" %
495 6c896e2f Iustin Pop
                                    (result.cmd, result.fail_reason,
496 6c896e2f Iustin Pop
                                     result.output))
497 a8083063 Iustin Pop
498 a8083063 Iustin Pop
    return snap_name
499 a8083063 Iustin Pop
500 a0c3fea1 Michael Hanselmann
  def SetInfo(self, text):
501 a0c3fea1 Michael Hanselmann
    """Update metadata with info text.
502 a0c3fea1 Michael Hanselmann

503 a0c3fea1 Michael Hanselmann
    """
504 a0c3fea1 Michael Hanselmann
    BlockDev.SetInfo(self, text)
505 a0c3fea1 Michael Hanselmann
506 a0c3fea1 Michael Hanselmann
    # Replace invalid characters
507 a0c3fea1 Michael Hanselmann
    text = re.sub('^[^A-Za-z0-9_+.]', '_', text)
508 a0c3fea1 Michael Hanselmann
    text = re.sub('[^-A-Za-z0-9_+.]', '_', text)
509 a0c3fea1 Michael Hanselmann
510 a0c3fea1 Michael Hanselmann
    # Only up to 128 characters are allowed
511 a0c3fea1 Michael Hanselmann
    text = text[:128]
512 a0c3fea1 Michael Hanselmann
513 a0c3fea1 Michael Hanselmann
    result = utils.RunCmd(["lvchange", "--addtag", text,
514 a0c3fea1 Michael Hanselmann
                           self.dev_path])
515 a0c3fea1 Michael Hanselmann
    if result.failed:
516 6c896e2f Iustin Pop
      raise errors.BlockDeviceError("Command: %s error: %s - %s" %
517 6c896e2f Iustin Pop
                                    (result.cmd, result.fail_reason,
518 6c896e2f Iustin Pop
                                     result.output))
519 1005d816 Iustin Pop
  def Grow(self, amount):
520 1005d816 Iustin Pop
    """Grow the logical volume.
521 1005d816 Iustin Pop

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

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

541 6b90c22e Iustin Pop
  """
542 6b90c22e Iustin Pop
  LINE_RE = re.compile(r"\s*[0-9]+:\s*cs:(\S+)\s+st:([^/]+)/(\S+)"
543 6b90c22e Iustin Pop
                       "\s+ds:([^/]+)/(\S+)\s+.*$")
544 6b90c22e Iustin Pop
  SYNC_RE = re.compile(r"^.*\ssync'ed:\s*([0-9.]+)%.*"
545 6b90c22e Iustin Pop
                       "\sfinish: ([0-9]+):([0-9]+):([0-9]+)\s.*$")
546 6b90c22e Iustin Pop
547 6b90c22e Iustin Pop
  def __init__(self, procline):
548 6b90c22e Iustin Pop
    m = self.LINE_RE.match(procline)
549 6b90c22e Iustin Pop
    if not m:
550 6b90c22e Iustin Pop
      raise errors.BlockDeviceError("Can't parse input data '%s'" % procline)
551 6b90c22e Iustin Pop
    self.cstatus = m.group(1)
552 6b90c22e Iustin Pop
    self.lrole = m.group(2)
553 6b90c22e Iustin Pop
    self.rrole = m.group(3)
554 6b90c22e Iustin Pop
    self.ldisk = m.group(4)
555 6b90c22e Iustin Pop
    self.rdisk = m.group(5)
556 6b90c22e Iustin Pop
557 6b90c22e Iustin Pop
    self.is_standalone = self.cstatus == "StandAlone"
558 6b90c22e Iustin Pop
    self.is_wfconn = self.cstatus == "WFConnection"
559 6b90c22e Iustin Pop
    self.is_connected = self.cstatus == "Connected"
560 6b90c22e Iustin Pop
    self.is_primary = self.lrole == "Primary"
561 6b90c22e Iustin Pop
    self.is_secondary = self.lrole == "Secondary"
562 6b90c22e Iustin Pop
    self.peer_primary = self.rrole == "Primary"
563 6b90c22e Iustin Pop
    self.peer_secondary = self.rrole == "Secondary"
564 6b90c22e Iustin Pop
    self.both_primary = self.is_primary and self.peer_primary
565 6b90c22e Iustin Pop
    self.both_secondary = self.is_secondary and self.peer_secondary
566 6b90c22e Iustin Pop
567 6b90c22e Iustin Pop
    self.is_diskless = self.ldisk == "Diskless"
568 6b90c22e Iustin Pop
    self.is_disk_uptodate = self.ldisk == "UpToDate"
569 6b90c22e Iustin Pop
570 6b90c22e Iustin Pop
    m = self.SYNC_RE.match(procline)
571 6b90c22e Iustin Pop
    if m:
572 6b90c22e Iustin Pop
      self.sync_percent = float(m.group(1))
573 6b90c22e Iustin Pop
      hours = int(m.group(2))
574 6b90c22e Iustin Pop
      minutes = int(m.group(3))
575 6b90c22e Iustin Pop
      seconds = int(m.group(4))
576 6b90c22e Iustin Pop
      self.est_time = hours * 3600 + minutes * 60 + seconds
577 6b90c22e Iustin Pop
    else:
578 6b90c22e Iustin Pop
      self.sync_percent = None
579 6b90c22e Iustin Pop
      self.est_time = None
580 6b90c22e Iustin Pop
581 6b90c22e Iustin Pop
    self.is_sync_target = self.peer_sync_source = self.cstatus == "SyncTarget"
582 6b90c22e Iustin Pop
    self.peer_sync_target = self.is_sync_source = self.cstatus == "SyncSource"
583 6b90c22e Iustin Pop
    self.is_resync = self.is_sync_target or self.is_sync_source
584 6b90c22e Iustin Pop
585 6b90c22e Iustin Pop
586 0f7f32d9 Iustin Pop
class BaseDRBD(BlockDev):
587 0f7f32d9 Iustin Pop
  """Base DRBD class.
588 a8083063 Iustin Pop

589 0f7f32d9 Iustin Pop
  This class contains a few bits of common functionality between the
590 0f7f32d9 Iustin Pop
  0.7 and 8.x versions of DRBD.
591 0f7f32d9 Iustin Pop

592 abdf0113 Iustin Pop
  """
593 abdf0113 Iustin Pop
  _VERSION_RE = re.compile(r"^version: (\d+)\.(\d+)\.(\d+)"
594 abdf0113 Iustin Pop
                           r" \(api:(\d+)/proto:(\d+)(?:-(\d+))?\)")
595 a8083063 Iustin Pop
596 abdf0113 Iustin Pop
  _DRBD_MAJOR = 147
597 abdf0113 Iustin Pop
  _ST_UNCONFIGURED = "Unconfigured"
598 abdf0113 Iustin Pop
  _ST_WFCONNECTION = "WFConnection"
599 abdf0113 Iustin Pop
  _ST_CONNECTED = "Connected"
600 a8083063 Iustin Pop
601 6b90c22e Iustin Pop
  _STATUS_FILE = "/proc/drbd"
602 6b90c22e Iustin Pop
603 abdf0113 Iustin Pop
  @staticmethod
604 6b90c22e Iustin Pop
  def _GetProcData(filename=_STATUS_FILE):
605 abdf0113 Iustin Pop
    """Return data from /proc/drbd.
606 a8083063 Iustin Pop

607 a8083063 Iustin Pop
    """
608 6b90c22e Iustin Pop
    stat = open(filename, "r")
609 abdf0113 Iustin Pop
    try:
610 abdf0113 Iustin Pop
      data = stat.read().splitlines()
611 abdf0113 Iustin Pop
    finally:
612 abdf0113 Iustin Pop
      stat.close()
613 abdf0113 Iustin Pop
    if not data:
614 6b90c22e Iustin Pop
      raise errors.BlockDeviceError("Can't read any data from %s" % filename)
615 abdf0113 Iustin Pop
    return data
616 a8083063 Iustin Pop
617 abdf0113 Iustin Pop
  @staticmethod
618 abdf0113 Iustin Pop
  def _MassageProcData(data):
619 abdf0113 Iustin Pop
    """Transform the output of _GetProdData into a nicer form.
620 a8083063 Iustin Pop

621 c41eea6e Iustin Pop
    @return: a dictionary of minor: joined lines from /proc/drbd
622 c41eea6e Iustin Pop
        for that minor
623 a8083063 Iustin Pop

624 a8083063 Iustin Pop
    """
625 abdf0113 Iustin Pop
    lmatch = re.compile("^ *([0-9]+):.*$")
626 abdf0113 Iustin Pop
    results = {}
627 abdf0113 Iustin Pop
    old_minor = old_line = None
628 abdf0113 Iustin Pop
    for line in data:
629 abdf0113 Iustin Pop
      lresult = lmatch.match(line)
630 abdf0113 Iustin Pop
      if lresult is not None:
631 abdf0113 Iustin Pop
        if old_minor is not None:
632 abdf0113 Iustin Pop
          results[old_minor] = old_line
633 abdf0113 Iustin Pop
        old_minor = int(lresult.group(1))
634 abdf0113 Iustin Pop
        old_line = line
635 abdf0113 Iustin Pop
      else:
636 abdf0113 Iustin Pop
        if old_minor is not None:
637 abdf0113 Iustin Pop
          old_line += " " + line.strip()
638 abdf0113 Iustin Pop
    # add last line
639 abdf0113 Iustin Pop
    if old_minor is not None:
640 abdf0113 Iustin Pop
      results[old_minor] = old_line
641 abdf0113 Iustin Pop
    return results
642 a8083063 Iustin Pop
643 abdf0113 Iustin Pop
  @classmethod
644 abdf0113 Iustin Pop
  def _GetVersion(cls):
645 abdf0113 Iustin Pop
    """Return the DRBD version.
646 a8083063 Iustin Pop

647 abdf0113 Iustin Pop
    This will return a dict with keys:
648 c41eea6e Iustin Pop
      - k_major
649 c41eea6e Iustin Pop
      - k_minor
650 c41eea6e Iustin Pop
      - k_point
651 c41eea6e Iustin Pop
      - api
652 c41eea6e Iustin Pop
      - proto
653 c41eea6e Iustin Pop
      - proto2 (only on drbd > 8.2.X)
654 a8083063 Iustin Pop

655 a8083063 Iustin Pop
    """
656 abdf0113 Iustin Pop
    proc_data = cls._GetProcData()
657 abdf0113 Iustin Pop
    first_line = proc_data[0].strip()
658 abdf0113 Iustin Pop
    version = cls._VERSION_RE.match(first_line)
659 abdf0113 Iustin Pop
    if not version:
660 abdf0113 Iustin Pop
      raise errors.BlockDeviceError("Can't parse DRBD version from '%s'" %
661 abdf0113 Iustin Pop
                                    first_line)
662 a8083063 Iustin Pop
663 abdf0113 Iustin Pop
    values = version.groups()
664 abdf0113 Iustin Pop
    retval = {'k_major': int(values[0]),
665 abdf0113 Iustin Pop
              'k_minor': int(values[1]),
666 abdf0113 Iustin Pop
              'k_point': int(values[2]),
667 abdf0113 Iustin Pop
              'api': int(values[3]),
668 abdf0113 Iustin Pop
              'proto': int(values[4]),
669 abdf0113 Iustin Pop
             }
670 abdf0113 Iustin Pop
    if values[5] is not None:
671 abdf0113 Iustin Pop
      retval['proto2'] = values[5]
672 a8083063 Iustin Pop
673 abdf0113 Iustin Pop
    return retval
674 abdf0113 Iustin Pop
675 abdf0113 Iustin Pop
  @staticmethod
676 abdf0113 Iustin Pop
  def _DevPath(minor):
677 abdf0113 Iustin Pop
    """Return the path to a drbd device for a given minor.
678 a8083063 Iustin Pop

679 a8083063 Iustin Pop
    """
680 abdf0113 Iustin Pop
    return "/dev/drbd%d" % minor
681 a8083063 Iustin Pop
682 abdf0113 Iustin Pop
  @classmethod
683 abdf0113 Iustin Pop
  def _GetUsedDevs(cls):
684 abdf0113 Iustin Pop
    """Compute the list of used DRBD devices.
685 a8083063 Iustin Pop

686 a8083063 Iustin Pop
    """
687 abdf0113 Iustin Pop
    data = cls._GetProcData()
688 a8083063 Iustin Pop
689 abdf0113 Iustin Pop
    used_devs = {}
690 abdf0113 Iustin Pop
    valid_line = re.compile("^ *([0-9]+): cs:([^ ]+).*$")
691 abdf0113 Iustin Pop
    for line in data:
692 abdf0113 Iustin Pop
      match = valid_line.match(line)
693 abdf0113 Iustin Pop
      if not match:
694 abdf0113 Iustin Pop
        continue
695 abdf0113 Iustin Pop
      minor = int(match.group(1))
696 abdf0113 Iustin Pop
      state = match.group(2)
697 abdf0113 Iustin Pop
      if state == cls._ST_UNCONFIGURED:
698 abdf0113 Iustin Pop
        continue
699 abdf0113 Iustin Pop
      used_devs[minor] = state, line
700 a8083063 Iustin Pop
701 abdf0113 Iustin Pop
    return used_devs
702 a8083063 Iustin Pop
703 abdf0113 Iustin Pop
  def _SetFromMinor(self, minor):
704 abdf0113 Iustin Pop
    """Set our parameters based on the given minor.
705 0834c866 Iustin Pop

706 abdf0113 Iustin Pop
    This sets our minor variable and our dev_path.
707 a8083063 Iustin Pop

708 a8083063 Iustin Pop
    """
709 abdf0113 Iustin Pop
    if minor is None:
710 abdf0113 Iustin Pop
      self.minor = self.dev_path = None
711 cb999543 Iustin Pop
      self.attached = False
712 a8083063 Iustin Pop
    else:
713 abdf0113 Iustin Pop
      self.minor = minor
714 abdf0113 Iustin Pop
      self.dev_path = self._DevPath(minor)
715 cb999543 Iustin Pop
      self.attached = True
716 a8083063 Iustin Pop
717 a8083063 Iustin Pop
  @staticmethod
718 abdf0113 Iustin Pop
  def _CheckMetaSize(meta_device):
719 abdf0113 Iustin Pop
    """Check if the given meta device looks like a valid one.
720 a8083063 Iustin Pop

721 abdf0113 Iustin Pop
    This currently only check the size, which must be around
722 abdf0113 Iustin Pop
    128MiB.
723 a8083063 Iustin Pop

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

747 abdf0113 Iustin Pop
    This is not supported for drbd devices.
748 a8083063 Iustin Pop

749 a8083063 Iustin Pop
    """
750 abdf0113 Iustin Pop
    raise errors.ProgrammerError("Can't rename a drbd device")
751 a8083063 Iustin Pop
752 f3e513ad Iustin Pop
753 a2cfdea2 Iustin Pop
class DRBD8(BaseDRBD):
754 a2cfdea2 Iustin Pop
  """DRBD v8.x block device.
755 a2cfdea2 Iustin Pop

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

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

765 a2cfdea2 Iustin Pop
  """
766 a2cfdea2 Iustin Pop
  _MAX_MINORS = 255
767 a2cfdea2 Iustin Pop
  _PARSE_SHOW = None
768 a2cfdea2 Iustin Pop
769 cf8df3f3 Iustin Pop
  # timeout constants
770 cf8df3f3 Iustin Pop
  _NET_RECONFIG_TIMEOUT = 60
771 cf8df3f3 Iustin Pop
772 a2cfdea2 Iustin Pop
  def __init__(self, unique_id, children):
773 fc1dc9d7 Iustin Pop
    if children and children.count(None) > 0:
774 fc1dc9d7 Iustin Pop
      children = []
775 a2cfdea2 Iustin Pop
    super(DRBD8, self).__init__(unique_id, children)
776 a2cfdea2 Iustin Pop
    self.major = self._DRBD_MAJOR
777 c3f9340c Guido Trotter
    version = self._GetVersion()
778 c3f9340c Guido Trotter
    if version['k_major'] != 8 :
779 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Mismatch in DRBD kernel version and"
780 a2cfdea2 Iustin Pop
                                    " requested ganeti usage: kernel is"
781 c3f9340c Guido Trotter
                                    " %s.%s, ganeti wants 8.x" %
782 c3f9340c Guido Trotter
                                    (version['k_major'], version['k_minor']))
783 a2cfdea2 Iustin Pop
784 b00b95dd Iustin Pop
    if len(children) not in (0, 2):
785 a2cfdea2 Iustin Pop
      raise ValueError("Invalid configuration data %s" % str(children))
786 f9518d38 Iustin Pop
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 6:
787 a2cfdea2 Iustin Pop
      raise ValueError("Invalid configuration data %s" % str(unique_id))
788 ffa1c0dc Iustin Pop
    (self._lhost, self._lport,
789 ffa1c0dc Iustin Pop
     self._rhost, self._rport,
790 f9518d38 Iustin Pop
     self._aminor, self._secret) = unique_id
791 ffa1c0dc Iustin Pop
    if (self._lhost is not None and self._lhost == self._rhost and
792 ffa1c0dc Iustin Pop
        self._lport == self._rport):
793 ffa1c0dc Iustin Pop
      raise ValueError("Invalid configuration data, same local/remote %s" %
794 ffa1c0dc Iustin Pop
                       (unique_id,))
795 a2cfdea2 Iustin Pop
    self.Attach()
796 a2cfdea2 Iustin Pop
797 a2cfdea2 Iustin Pop
  @classmethod
798 a2cfdea2 Iustin Pop
  def _InitMeta(cls, minor, dev_path):
799 a2cfdea2 Iustin Pop
    """Initialize a meta device.
800 a2cfdea2 Iustin Pop

801 a2cfdea2 Iustin Pop
    This will not work if the given minor is in use.
802 a2cfdea2 Iustin Pop

803 a2cfdea2 Iustin Pop
    """
804 a2cfdea2 Iustin Pop
    result = utils.RunCmd(["drbdmeta", "--force", cls._DevPath(minor),
805 a2cfdea2 Iustin Pop
                           "v08", dev_path, "0", "create-md"])
806 a2cfdea2 Iustin Pop
    if result.failed:
807 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Can't initialize meta device: %s" %
808 a2cfdea2 Iustin Pop
                                    result.output)
809 a2cfdea2 Iustin Pop
810 a2cfdea2 Iustin Pop
  @classmethod
811 a2cfdea2 Iustin Pop
  def _FindUnusedMinor(cls):
812 a2cfdea2 Iustin Pop
    """Find an unused DRBD device.
813 a2cfdea2 Iustin Pop

814 a2cfdea2 Iustin Pop
    This is specific to 8.x as the minors are allocated dynamically,
815 a2cfdea2 Iustin Pop
    so non-existing numbers up to a max minor count are actually free.
816 a2cfdea2 Iustin Pop

817 a2cfdea2 Iustin Pop
    """
818 a2cfdea2 Iustin Pop
    data = cls._GetProcData()
819 a2cfdea2 Iustin Pop
820 a2cfdea2 Iustin Pop
    unused_line = re.compile("^ *([0-9]+): cs:Unconfigured$")
821 a2cfdea2 Iustin Pop
    used_line = re.compile("^ *([0-9]+): cs:")
822 a2cfdea2 Iustin Pop
    highest = None
823 a2cfdea2 Iustin Pop
    for line in data:
824 a2cfdea2 Iustin Pop
      match = unused_line.match(line)
825 a2cfdea2 Iustin Pop
      if match:
826 a2cfdea2 Iustin Pop
        return int(match.group(1))
827 a2cfdea2 Iustin Pop
      match = used_line.match(line)
828 a2cfdea2 Iustin Pop
      if match:
829 a2cfdea2 Iustin Pop
        minor = int(match.group(1))
830 a2cfdea2 Iustin Pop
        highest = max(highest, minor)
831 a2cfdea2 Iustin Pop
    if highest is None: # there are no minors in use at all
832 a2cfdea2 Iustin Pop
      return 0
833 a2cfdea2 Iustin Pop
    if highest >= cls._MAX_MINORS:
834 468c5f77 Iustin Pop
      logging.error("Error: no free drbd minors!")
835 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Can't find a free DRBD minor")
836 a2cfdea2 Iustin Pop
    return highest + 1
837 a2cfdea2 Iustin Pop
838 a2cfdea2 Iustin Pop
  @classmethod
839 a2cfdea2 Iustin Pop
  def _IsValidMeta(cls, meta_device):
840 a2cfdea2 Iustin Pop
    """Check if the given meta device looks like a valid one.
841 a2cfdea2 Iustin Pop

842 a2cfdea2 Iustin Pop
    """
843 a2cfdea2 Iustin Pop
    minor = cls._FindUnusedMinor()
844 a2cfdea2 Iustin Pop
    minor_path = cls._DevPath(minor)
845 a2cfdea2 Iustin Pop
    result = utils.RunCmd(["drbdmeta", minor_path,
846 a2cfdea2 Iustin Pop
                           "v08", meta_device, "0",
847 a2cfdea2 Iustin Pop
                           "dstate"])
848 a2cfdea2 Iustin Pop
    if result.failed:
849 468c5f77 Iustin Pop
      logging.error("Invalid meta device %s: %s", meta_device, result.output)
850 a2cfdea2 Iustin Pop
      return False
851 a2cfdea2 Iustin Pop
    return True
852 a2cfdea2 Iustin Pop
853 a2cfdea2 Iustin Pop
  @classmethod
854 a2cfdea2 Iustin Pop
  def _GetShowParser(cls):
855 a2cfdea2 Iustin Pop
    """Return a parser for `drbd show` output.
856 a2cfdea2 Iustin Pop

857 a2cfdea2 Iustin Pop
    This will either create or return an already-create parser for the
858 a2cfdea2 Iustin Pop
    output of the command `drbd show`.
859 a2cfdea2 Iustin Pop

860 a2cfdea2 Iustin Pop
    """
861 a2cfdea2 Iustin Pop
    if cls._PARSE_SHOW is not None:
862 a2cfdea2 Iustin Pop
      return cls._PARSE_SHOW
863 a2cfdea2 Iustin Pop
864 a2cfdea2 Iustin Pop
    # pyparsing setup
865 a2cfdea2 Iustin Pop
    lbrace = pyp.Literal("{").suppress()
866 a2cfdea2 Iustin Pop
    rbrace = pyp.Literal("}").suppress()
867 a2cfdea2 Iustin Pop
    semi = pyp.Literal(";").suppress()
868 a2cfdea2 Iustin Pop
    # this also converts the value to an int
869 c522ea02 Iustin Pop
    number = pyp.Word(pyp.nums).setParseAction(lambda s, l, t: int(t[0]))
870 a2cfdea2 Iustin Pop
871 a2cfdea2 Iustin Pop
    comment = pyp.Literal ("#") + pyp.Optional(pyp.restOfLine)
872 a2cfdea2 Iustin Pop
    defa = pyp.Literal("_is_default").suppress()
873 a2cfdea2 Iustin Pop
    dbl_quote = pyp.Literal('"').suppress()
874 a2cfdea2 Iustin Pop
875 a2cfdea2 Iustin Pop
    keyword = pyp.Word(pyp.alphanums + '-')
876 a2cfdea2 Iustin Pop
877 a2cfdea2 Iustin Pop
    # value types
878 a2cfdea2 Iustin Pop
    value = pyp.Word(pyp.alphanums + '_-/.:')
879 a2cfdea2 Iustin Pop
    quoted = dbl_quote + pyp.CharsNotIn('"') + dbl_quote
880 a2cfdea2 Iustin Pop
    addr_port = (pyp.Word(pyp.nums + '.') + pyp.Literal(':').suppress() +
881 a2cfdea2 Iustin Pop
                 number)
882 a2cfdea2 Iustin Pop
    # meta device, extended syntax
883 a2cfdea2 Iustin Pop
    meta_value = ((value ^ quoted) + pyp.Literal('[').suppress() +
884 a2cfdea2 Iustin Pop
                  number + pyp.Word(']').suppress())
885 a2cfdea2 Iustin Pop
886 a2cfdea2 Iustin Pop
    # a statement
887 a2cfdea2 Iustin Pop
    stmt = (~rbrace + keyword + ~lbrace +
888 63012024 Guido Trotter
            pyp.Optional(addr_port ^ value ^ quoted ^ meta_value) +
889 a2cfdea2 Iustin Pop
            pyp.Optional(defa) + semi +
890 a2cfdea2 Iustin Pop
            pyp.Optional(pyp.restOfLine).suppress())
891 a2cfdea2 Iustin Pop
892 a2cfdea2 Iustin Pop
    # an entire section
893 a2cfdea2 Iustin Pop
    section_name = pyp.Word(pyp.alphas + '_')
894 a2cfdea2 Iustin Pop
    section = section_name + lbrace + pyp.ZeroOrMore(pyp.Group(stmt)) + rbrace
895 a2cfdea2 Iustin Pop
896 a2cfdea2 Iustin Pop
    bnf = pyp.ZeroOrMore(pyp.Group(section ^ stmt))
897 a2cfdea2 Iustin Pop
    bnf.ignore(comment)
898 a2cfdea2 Iustin Pop
899 a2cfdea2 Iustin Pop
    cls._PARSE_SHOW = bnf
900 a2cfdea2 Iustin Pop
901 a2cfdea2 Iustin Pop
    return bnf
902 a2cfdea2 Iustin Pop
903 a2cfdea2 Iustin Pop
  @classmethod
904 3840729d Iustin Pop
  def _GetShowData(cls, minor):
905 3840729d Iustin Pop
    """Return the `drbdsetup show` data for a minor.
906 a2cfdea2 Iustin Pop

907 a2cfdea2 Iustin Pop
    """
908 a2cfdea2 Iustin Pop
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "show"])
909 a2cfdea2 Iustin Pop
    if result.failed:
910 468c5f77 Iustin Pop
      logging.error("Can't display the drbd config: %s - %s",
911 468c5f77 Iustin Pop
                    result.fail_reason, result.output)
912 3840729d Iustin Pop
      return None
913 3840729d Iustin Pop
    return result.stdout
914 3840729d Iustin Pop
915 3840729d Iustin Pop
  @classmethod
916 3840729d Iustin Pop
  def _GetDevInfo(cls, out):
917 3840729d Iustin Pop
    """Parse details about a given DRBD minor.
918 3840729d Iustin Pop

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

924 3840729d Iustin Pop
    """
925 3840729d Iustin Pop
    data = {}
926 a2cfdea2 Iustin Pop
    if not out:
927 a2cfdea2 Iustin Pop
      return data
928 a2cfdea2 Iustin Pop
929 a2cfdea2 Iustin Pop
    bnf = cls._GetShowParser()
930 a2cfdea2 Iustin Pop
    # run pyparse
931 a2cfdea2 Iustin Pop
932 a2cfdea2 Iustin Pop
    try:
933 a2cfdea2 Iustin Pop
      results = bnf.parseString(out)
934 a2cfdea2 Iustin Pop
    except pyp.ParseException, err:
935 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Can't parse drbdsetup show output: %s" %
936 a2cfdea2 Iustin Pop
                                    str(err))
937 a2cfdea2 Iustin Pop
938 a2cfdea2 Iustin Pop
    # and massage the results into our desired format
939 a2cfdea2 Iustin Pop
    for section in results:
940 a2cfdea2 Iustin Pop
      sname = section[0]
941 a2cfdea2 Iustin Pop
      if sname == "_this_host":
942 a2cfdea2 Iustin Pop
        for lst in section[1:]:
943 a2cfdea2 Iustin Pop
          if lst[0] == "disk":
944 a2cfdea2 Iustin Pop
            data["local_dev"] = lst[1]
945 a2cfdea2 Iustin Pop
          elif lst[0] == "meta-disk":
946 a2cfdea2 Iustin Pop
            data["meta_dev"] = lst[1]
947 a2cfdea2 Iustin Pop
            data["meta_index"] = lst[2]
948 a2cfdea2 Iustin Pop
          elif lst[0] == "address":
949 a2cfdea2 Iustin Pop
            data["local_addr"] = tuple(lst[1:])
950 a2cfdea2 Iustin Pop
      elif sname == "_remote_host":
951 a2cfdea2 Iustin Pop
        for lst in section[1:]:
952 a2cfdea2 Iustin Pop
          if lst[0] == "address":
953 a2cfdea2 Iustin Pop
            data["remote_addr"] = tuple(lst[1:])
954 a2cfdea2 Iustin Pop
    return data
955 a2cfdea2 Iustin Pop
956 a2cfdea2 Iustin Pop
  def _MatchesLocal(self, info):
957 a2cfdea2 Iustin Pop
    """Test if our local config matches with an existing device.
958 a2cfdea2 Iustin Pop

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

964 a2cfdea2 Iustin Pop
    """
965 b00b95dd Iustin Pop
    if self._children:
966 b00b95dd Iustin Pop
      backend, meta = self._children
967 b00b95dd Iustin Pop
    else:
968 b00b95dd Iustin Pop
      backend = meta = None
969 b00b95dd Iustin Pop
970 a2cfdea2 Iustin Pop
    if backend is not None:
971 b00b95dd Iustin Pop
      retval = ("local_dev" in info and info["local_dev"] == backend.dev_path)
972 a2cfdea2 Iustin Pop
    else:
973 a2cfdea2 Iustin Pop
      retval = ("local_dev" not in info)
974 b00b95dd Iustin Pop
975 a2cfdea2 Iustin Pop
    if meta is not None:
976 b00b95dd Iustin Pop
      retval = retval and ("meta_dev" in info and
977 b00b95dd Iustin Pop
                           info["meta_dev"] == meta.dev_path)
978 b00b95dd Iustin Pop
      retval = retval and ("meta_index" in info and
979 b00b95dd Iustin Pop
                           info["meta_index"] == 0)
980 a2cfdea2 Iustin Pop
    else:
981 a2cfdea2 Iustin Pop
      retval = retval and ("meta_dev" not in info and
982 a2cfdea2 Iustin Pop
                           "meta_index" not in info)
983 a2cfdea2 Iustin Pop
    return retval
984 a2cfdea2 Iustin Pop
985 a2cfdea2 Iustin Pop
  def _MatchesNet(self, info):
986 a2cfdea2 Iustin Pop
    """Test if our network config matches with an existing device.
987 a2cfdea2 Iustin Pop

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

993 a2cfdea2 Iustin Pop
    """
994 a2cfdea2 Iustin Pop
    if (((self._lhost is None and not ("local_addr" in info)) and
995 a2cfdea2 Iustin Pop
         (self._rhost is None and not ("remote_addr" in info)))):
996 a2cfdea2 Iustin Pop
      return True
997 a2cfdea2 Iustin Pop
998 a2cfdea2 Iustin Pop
    if self._lhost is None:
999 a2cfdea2 Iustin Pop
      return False
1000 a2cfdea2 Iustin Pop
1001 a2cfdea2 Iustin Pop
    if not ("local_addr" in info and
1002 a2cfdea2 Iustin Pop
            "remote_addr" in info):
1003 a2cfdea2 Iustin Pop
      return False
1004 a2cfdea2 Iustin Pop
1005 a2cfdea2 Iustin Pop
    retval = (info["local_addr"] == (self._lhost, self._lport))
1006 a2cfdea2 Iustin Pop
    retval = (retval and
1007 a2cfdea2 Iustin Pop
              info["remote_addr"] == (self._rhost, self._rport))
1008 a2cfdea2 Iustin Pop
    return retval
1009 a2cfdea2 Iustin Pop
1010 a2cfdea2 Iustin Pop
  @classmethod
1011 a2cfdea2 Iustin Pop
  def _AssembleLocal(cls, minor, backend, meta):
1012 a2cfdea2 Iustin Pop
    """Configure the local part of a DRBD device.
1013 a2cfdea2 Iustin Pop

1014 a2cfdea2 Iustin Pop
    This is the first thing that must be done on an unconfigured DRBD
1015 a2cfdea2 Iustin Pop
    device. And it must be done only once.
1016 a2cfdea2 Iustin Pop

1017 a2cfdea2 Iustin Pop
    """
1018 a2cfdea2 Iustin Pop
    if not cls._IsValidMeta(meta):
1019 a2cfdea2 Iustin Pop
      return False
1020 333411a7 Guido Trotter
    args = ["drbdsetup", cls._DevPath(minor), "disk",
1021 333411a7 Guido Trotter
            backend, meta, "0", "-e", "detach", "--create-device"]
1022 333411a7 Guido Trotter
    result = utils.RunCmd(args)
1023 a2cfdea2 Iustin Pop
    if result.failed:
1024 468c5f77 Iustin Pop
      logging.error("Can't attach local disk: %s", result.output)
1025 a2cfdea2 Iustin Pop
    return not result.failed
1026 a2cfdea2 Iustin Pop
1027 a2cfdea2 Iustin Pop
  @classmethod
1028 a2cfdea2 Iustin Pop
  def _AssembleNet(cls, minor, net_info, protocol,
1029 a2cfdea2 Iustin Pop
                   dual_pri=False, hmac=None, secret=None):
1030 a2cfdea2 Iustin Pop
    """Configure the network part of the device.
1031 a2cfdea2 Iustin Pop

1032 a2cfdea2 Iustin Pop
    """
1033 a2cfdea2 Iustin Pop
    lhost, lport, rhost, rport = net_info
1034 52857176 Iustin Pop
    if None in net_info:
1035 52857176 Iustin Pop
      # we don't want network connection and actually want to make
1036 52857176 Iustin Pop
      # sure its shutdown
1037 52857176 Iustin Pop
      return cls._ShutdownNet(minor)
1038 52857176 Iustin Pop
1039 7d585316 Iustin Pop
    # Workaround for a race condition. When DRBD is doing its dance to
1040 7d585316 Iustin Pop
    # establish a connection with its peer, it also sends the
1041 7d585316 Iustin Pop
    # synchronization speed over the wire. In some cases setting the
1042 7d585316 Iustin Pop
    # sync speed only after setting up both sides can race with DRBD
1043 7d585316 Iustin Pop
    # connecting, hence we set it here before telling DRBD anything
1044 7d585316 Iustin Pop
    # about its peer.
1045 7d585316 Iustin Pop
    cls._SetMinorSyncSpeed(minor, constants.SYNC_SPEED)
1046 7d585316 Iustin Pop
1047 a2cfdea2 Iustin Pop
    args = ["drbdsetup", cls._DevPath(minor), "net",
1048 f38478b2 Iustin Pop
            "%s:%s" % (lhost, lport), "%s:%s" % (rhost, rport), protocol,
1049 f38478b2 Iustin Pop
            "-A", "discard-zero-changes",
1050 f38478b2 Iustin Pop
            "-B", "consensus",
1051 ab6cc81c Iustin Pop
            "--create-device",
1052 f38478b2 Iustin Pop
            ]
1053 a2cfdea2 Iustin Pop
    if dual_pri:
1054 a2cfdea2 Iustin Pop
      args.append("-m")
1055 a2cfdea2 Iustin Pop
    if hmac and secret:
1056 a2cfdea2 Iustin Pop
      args.extend(["-a", hmac, "-x", secret])
1057 a2cfdea2 Iustin Pop
    result = utils.RunCmd(args)
1058 a2cfdea2 Iustin Pop
    if result.failed:
1059 468c5f77 Iustin Pop
      logging.error("Can't setup network for dbrd device: %s - %s",
1060 468c5f77 Iustin Pop
                    result.fail_reason, result.output)
1061 a2cfdea2 Iustin Pop
      return False
1062 a2cfdea2 Iustin Pop
1063 a2cfdea2 Iustin Pop
    timeout = time.time() + 10
1064 a2cfdea2 Iustin Pop
    ok = False
1065 a2cfdea2 Iustin Pop
    while time.time() < timeout:
1066 3840729d Iustin Pop
      info = cls._GetDevInfo(cls._GetShowData(minor))
1067 a2cfdea2 Iustin Pop
      if not "local_addr" in info or not "remote_addr" in info:
1068 a2cfdea2 Iustin Pop
        time.sleep(1)
1069 a2cfdea2 Iustin Pop
        continue
1070 a2cfdea2 Iustin Pop
      if (info["local_addr"] != (lhost, lport) or
1071 a2cfdea2 Iustin Pop
          info["remote_addr"] != (rhost, rport)):
1072 a2cfdea2 Iustin Pop
        time.sleep(1)
1073 a2cfdea2 Iustin Pop
        continue
1074 a2cfdea2 Iustin Pop
      ok = True
1075 a2cfdea2 Iustin Pop
      break
1076 a2cfdea2 Iustin Pop
    if not ok:
1077 468c5f77 Iustin Pop
      logging.error("Timeout while configuring network")
1078 a2cfdea2 Iustin Pop
      return False
1079 a2cfdea2 Iustin Pop
    return True
1080 a2cfdea2 Iustin Pop
1081 b00b95dd Iustin Pop
  def AddChildren(self, devices):
1082 b00b95dd Iustin Pop
    """Add a disk to the DRBD device.
1083 b00b95dd Iustin Pop

1084 b00b95dd Iustin Pop
    """
1085 b00b95dd Iustin Pop
    if self.minor is None:
1086 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("Can't attach to dbrd8 during AddChildren")
1087 b00b95dd Iustin Pop
    if len(devices) != 2:
1088 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("Need two devices for AddChildren")
1089 3840729d Iustin Pop
    info = self._GetDevInfo(self._GetShowData(self.minor))
1090 03ece5f3 Iustin Pop
    if "local_dev" in info:
1091 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("DRBD8 already attached to a local disk")
1092 b00b95dd Iustin Pop
    backend, meta = devices
1093 b00b95dd Iustin Pop
    if backend.dev_path is None or meta.dev_path is None:
1094 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("Children not ready during AddChildren")
1095 b00b95dd Iustin Pop
    backend.Open()
1096 b00b95dd Iustin Pop
    meta.Open()
1097 b00b95dd Iustin Pop
    if not self._CheckMetaSize(meta.dev_path):
1098 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("Invalid meta device size")
1099 b00b95dd Iustin Pop
    self._InitMeta(self._FindUnusedMinor(), meta.dev_path)
1100 b00b95dd Iustin Pop
    if not self._IsValidMeta(meta.dev_path):
1101 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("Cannot initalize meta device")
1102 b00b95dd Iustin Pop
1103 b00b95dd Iustin Pop
    if not self._AssembleLocal(self.minor, backend.dev_path, meta.dev_path):
1104 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("Can't attach to local storage")
1105 b00b95dd Iustin Pop
    self._children = devices
1106 b00b95dd Iustin Pop
1107 b00b95dd Iustin Pop
  def RemoveChildren(self, devices):
1108 b00b95dd Iustin Pop
    """Detach the drbd device from local storage.
1109 b00b95dd Iustin Pop

1110 b00b95dd Iustin Pop
    """
1111 b00b95dd Iustin Pop
    if self.minor is None:
1112 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("Can't attach to drbd8 during"
1113 b00b95dd Iustin Pop
                                    " RemoveChildren")
1114 03ece5f3 Iustin Pop
    # early return if we don't actually have backing storage
1115 3840729d Iustin Pop
    info = self._GetDevInfo(self._GetShowData(self.minor))
1116 03ece5f3 Iustin Pop
    if "local_dev" not in info:
1117 03ece5f3 Iustin Pop
      return
1118 b00b95dd Iustin Pop
    if len(self._children) != 2:
1119 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("We don't have two children: %s" %
1120 b00b95dd Iustin Pop
                                    self._children)
1121 e739bd57 Iustin Pop
    if self._children.count(None) == 2: # we don't actually have children :)
1122 468c5f77 Iustin Pop
      logging.error("Requested detach while detached")
1123 e739bd57 Iustin Pop
      return
1124 b00b95dd Iustin Pop
    if len(devices) != 2:
1125 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("We need two children in RemoveChildren")
1126 e739bd57 Iustin Pop
    for child, dev in zip(self._children, devices):
1127 e739bd57 Iustin Pop
      if dev != child.dev_path:
1128 e739bd57 Iustin Pop
        raise errors.BlockDeviceError("Mismatch in local storage"
1129 e739bd57 Iustin Pop
                                      " (%s != %s) in RemoveChildren" %
1130 e739bd57 Iustin Pop
                                      (dev, child.dev_path))
1131 b00b95dd Iustin Pop
1132 b00b95dd Iustin Pop
    if not self._ShutdownLocal(self.minor):
1133 b00b95dd Iustin Pop
      raise errors.BlockDeviceError("Can't detach from local storage")
1134 b00b95dd Iustin Pop
    self._children = []
1135 b00b95dd Iustin Pop
1136 7d585316 Iustin Pop
  @classmethod
1137 7d585316 Iustin Pop
  def _SetMinorSyncSpeed(cls, minor, kbytes):
1138 a2cfdea2 Iustin Pop
    """Set the speed of the DRBD syncer.
1139 a2cfdea2 Iustin Pop

1140 7d585316 Iustin Pop
    This is the low-level implementation.
1141 7d585316 Iustin Pop

1142 7d585316 Iustin Pop
    @type minor: int
1143 7d585316 Iustin Pop
    @param minor: the drbd minor whose settings we change
1144 7d585316 Iustin Pop
    @type kbytes: int
1145 7d585316 Iustin Pop
    @param kbytes: the speed in kbytes/second
1146 7d585316 Iustin Pop
    @rtype: boolean
1147 7d585316 Iustin Pop
    @return: the success of the operation
1148 7d585316 Iustin Pop

1149 a2cfdea2 Iustin Pop
    """
1150 7d585316 Iustin Pop
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "syncer",
1151 7d585316 Iustin Pop
                           "-r", "%d" % kbytes, "--create-device"])
1152 a2cfdea2 Iustin Pop
    if result.failed:
1153 468c5f77 Iustin Pop
      logging.error("Can't change syncer rate: %s - %s",
1154 468c5f77 Iustin Pop
                    result.fail_reason, result.output)
1155 7d585316 Iustin Pop
    return not result.failed
1156 7d585316 Iustin Pop
1157 7d585316 Iustin Pop
  def SetSyncSpeed(self, kbytes):
1158 7d585316 Iustin Pop
    """Set the speed of the DRBD syncer.
1159 7d585316 Iustin Pop

1160 7d585316 Iustin Pop
    @type kbytes: int
1161 7d585316 Iustin Pop
    @param kbytes: the speed in kbytes/second
1162 7d585316 Iustin Pop
    @rtype: boolean
1163 7d585316 Iustin Pop
    @return: the success of the operation
1164 7d585316 Iustin Pop

1165 7d585316 Iustin Pop
    """
1166 7d585316 Iustin Pop
    if self.minor is None:
1167 7d585316 Iustin Pop
      logging.info("Not attached during SetSyncSpeed")
1168 7d585316 Iustin Pop
      return False
1169 7d585316 Iustin Pop
    children_result = super(DRBD8, self).SetSyncSpeed(kbytes)
1170 7d585316 Iustin Pop
    return self._SetMinorSyncSpeed(self.minor, kbytes) and children_result
1171 a2cfdea2 Iustin Pop
1172 6b90c22e Iustin Pop
  def GetProcStatus(self):
1173 6b90c22e Iustin Pop
    """Return device data from /proc.
1174 6b90c22e Iustin Pop

1175 6b90c22e Iustin Pop
    """
1176 6b90c22e Iustin Pop
    if self.minor is None:
1177 6b90c22e Iustin Pop
      raise errors.BlockDeviceError("GetStats() called while not attached")
1178 6b90c22e Iustin Pop
    proc_info = self._MassageProcData(self._GetProcData())
1179 6b90c22e Iustin Pop
    if self.minor not in proc_info:
1180 6b90c22e Iustin Pop
      raise errors.BlockDeviceError("Can't find myself in /proc (minor %d)" %
1181 6b90c22e Iustin Pop
                                    self.minor)
1182 6b90c22e Iustin Pop
    return DRBD8Status(proc_info[self.minor])
1183 6b90c22e Iustin Pop
1184 a2cfdea2 Iustin Pop
  def GetSyncStatus(self):
1185 a2cfdea2 Iustin Pop
    """Returns the sync status of the device.
1186 a2cfdea2 Iustin Pop

1187 a2cfdea2 Iustin Pop

1188 a2cfdea2 Iustin Pop
    If sync_percent is None, it means all is ok
1189 a2cfdea2 Iustin Pop
    If estimated_time is None, it means we can't esimate
1190 0834c866 Iustin Pop
    the time needed, otherwise it's the time left in seconds.
1191 0834c866 Iustin Pop

1192 0834c866 Iustin Pop

1193 0834c866 Iustin Pop
    We set the is_degraded parameter to True on two conditions:
1194 0834c866 Iustin Pop
    network not connected or local disk missing.
1195 0834c866 Iustin Pop

1196 0834c866 Iustin Pop
    We compute the ldisk parameter based on wheter we have a local
1197 0834c866 Iustin Pop
    disk or not.
1198 a2cfdea2 Iustin Pop

1199 c41eea6e Iustin Pop
    @rtype: tuple
1200 c41eea6e Iustin Pop
    @return: (sync_percent, estimated_time, is_degraded, ldisk)
1201 c41eea6e Iustin Pop

1202 a2cfdea2 Iustin Pop
    """
1203 a2cfdea2 Iustin Pop
    if self.minor is None and not self.Attach():
1204 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Can't attach to device in GetSyncStatus")
1205 6b90c22e Iustin Pop
    stats = self.GetProcStatus()
1206 6b90c22e Iustin Pop
    ldisk = not stats.is_disk_uptodate
1207 6b90c22e Iustin Pop
    is_degraded = not stats.is_connected
1208 6b90c22e Iustin Pop
    return stats.sync_percent, stats.est_time, is_degraded or ldisk, ldisk
1209 a2cfdea2 Iustin Pop
1210 a2cfdea2 Iustin Pop
  def Open(self, force=False):
1211 a2cfdea2 Iustin Pop
    """Make the local state primary.
1212 a2cfdea2 Iustin Pop

1213 f860ff4e Guido Trotter
    If the 'force' parameter is given, the '-o' option is passed to
1214 f860ff4e Guido Trotter
    drbdsetup. Since this is a potentially dangerous operation, the
1215 a2cfdea2 Iustin Pop
    force flag should be only given after creation, when it actually
1216 f860ff4e Guido Trotter
    is mandatory.
1217 a2cfdea2 Iustin Pop

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

1234 a2cfdea2 Iustin Pop
    This will, of course, fail if the device is in use.
1235 a2cfdea2 Iustin Pop

1236 a2cfdea2 Iustin Pop
    """
1237 a2cfdea2 Iustin Pop
    if self.minor is None and not self.Attach():
1238 468c5f77 Iustin Pop
      logging.info("Instance not attached to a device")
1239 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Can't find device")
1240 a2cfdea2 Iustin Pop
    result = utils.RunCmd(["drbdsetup", self.dev_path, "secondary"])
1241 a2cfdea2 Iustin Pop
    if result.failed:
1242 fdbd668d Iustin Pop
      msg = ("Can't switch drbd device to"
1243 fdbd668d Iustin Pop
             " secondary: %s" % result.output)
1244 468c5f77 Iustin Pop
      logging.error(msg)
1245 fdbd668d Iustin Pop
      raise errors.BlockDeviceError(msg)
1246 a2cfdea2 Iustin Pop
1247 cf8df3f3 Iustin Pop
  def DisconnectNet(self):
1248 cf8df3f3 Iustin Pop
    """Removes network configuration.
1249 cf8df3f3 Iustin Pop

1250 cf8df3f3 Iustin Pop
    This method shutdowns the network side of the device.
1251 cf8df3f3 Iustin Pop

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

1260 cf8df3f3 Iustin Pop
    """
1261 cf8df3f3 Iustin Pop
    if self.minor is None:
1262 cf8df3f3 Iustin Pop
      raise errors.BlockDeviceError("DRBD disk not attached in re-attach net")
1263 cf8df3f3 Iustin Pop
1264 cf8df3f3 Iustin Pop
    if None in (self._lhost, self._lport, self._rhost, self._rport):
1265 cf8df3f3 Iustin Pop
      raise errors.BlockDeviceError("DRBD disk missing network info in"
1266 cf8df3f3 Iustin Pop
                                    " DisconnectNet()")
1267 cf8df3f3 Iustin Pop
1268 cf8df3f3 Iustin Pop
    ever_disconnected = self._ShutdownNet(self.minor)
1269 cf8df3f3 Iustin Pop
    timeout_limit = time.time() + self._NET_RECONFIG_TIMEOUT
1270 cf8df3f3 Iustin Pop
    sleep_time = 0.100 # we start the retry time at 100 miliseconds
1271 cf8df3f3 Iustin Pop
    while time.time() < timeout_limit:
1272 cf8df3f3 Iustin Pop
      status = self.GetProcStatus()
1273 cf8df3f3 Iustin Pop
      if status.is_standalone:
1274 cf8df3f3 Iustin Pop
        break
1275 cf8df3f3 Iustin Pop
      # retry the disconnect, it seems possible that due to a
1276 cf8df3f3 Iustin Pop
      # well-time disconnect on the peer, my disconnect command might
1277 cf8df3f3 Iustin Pop
      # be ingored and forgotten
1278 cf8df3f3 Iustin Pop
      ever_disconnected = self._ShutdownNet(self.minor) or ever_disconnected
1279 cf8df3f3 Iustin Pop
      time.sleep(sleep_time)
1280 cf8df3f3 Iustin Pop
      sleep_time = min(2, sleep_time * 1.5)
1281 cf8df3f3 Iustin Pop
1282 cf8df3f3 Iustin Pop
    if not status.is_standalone:
1283 cf8df3f3 Iustin Pop
      if ever_disconnected:
1284 cf8df3f3 Iustin Pop
        msg = ("Device did not react to the"
1285 cf8df3f3 Iustin Pop
               " 'disconnect' command in a timely manner")
1286 cf8df3f3 Iustin Pop
      else:
1287 cf8df3f3 Iustin Pop
        msg = ("Can't shutdown network, even after multiple retries")
1288 cf8df3f3 Iustin Pop
      raise errors.BlockDeviceError(msg)
1289 cf8df3f3 Iustin Pop
1290 cf8df3f3 Iustin Pop
    reconfig_time = time.time() - timeout_limit + self._NET_RECONFIG_TIMEOUT
1291 cf8df3f3 Iustin Pop
    if reconfig_time > 15: # hardcoded alert limit
1292 cf8df3f3 Iustin Pop
      logging.debug("DRBD8.DisconnectNet: detach took %.3f seconds",
1293 cf8df3f3 Iustin Pop
                    reconfig_time)
1294 cf8df3f3 Iustin Pop
1295 cf8df3f3 Iustin Pop
  def AttachNet(self, multimaster):
1296 cf8df3f3 Iustin Pop
    """Reconnects the network.
1297 cf8df3f3 Iustin Pop

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

1302 cf8df3f3 Iustin Pop
    Args:
1303 cf8df3f3 Iustin Pop
      - multimaster: init the network in dual-primary mode
1304 cf8df3f3 Iustin Pop

1305 cf8df3f3 Iustin Pop
    """
1306 cf8df3f3 Iustin Pop
    if self.minor is None:
1307 cf8df3f3 Iustin Pop
      raise errors.BlockDeviceError("DRBD disk not attached in AttachNet")
1308 cf8df3f3 Iustin Pop
1309 cf8df3f3 Iustin Pop
    if None in (self._lhost, self._lport, self._rhost, self._rport):
1310 cf8df3f3 Iustin Pop
      raise errors.BlockDeviceError("DRBD disk missing network info in"
1311 cf8df3f3 Iustin Pop
                                    " AttachNet()")
1312 cf8df3f3 Iustin Pop
1313 cf8df3f3 Iustin Pop
    status = self.GetProcStatus()
1314 cf8df3f3 Iustin Pop
1315 cf8df3f3 Iustin Pop
    if not status.is_standalone:
1316 cf8df3f3 Iustin Pop
      raise errors.BlockDeviceError("Device is not standalone in AttachNet")
1317 cf8df3f3 Iustin Pop
1318 cf8df3f3 Iustin Pop
    return self._AssembleNet(self.minor,
1319 cf8df3f3 Iustin Pop
                             (self._lhost, self._lport,
1320 cf8df3f3 Iustin Pop
                              self._rhost, self._rport),
1321 cf8df3f3 Iustin Pop
                             "C", dual_pri=multimaster)
1322 cf8df3f3 Iustin Pop
1323 a2cfdea2 Iustin Pop
  def Attach(self):
1324 2d0c8319 Iustin Pop
    """Check if our minor is configured.
1325 2d0c8319 Iustin Pop

1326 2d0c8319 Iustin Pop
    This doesn't do any device configurations - it only checks if the
1327 2d0c8319 Iustin Pop
    minor is in a state different from Unconfigured.
1328 2d0c8319 Iustin Pop

1329 2d0c8319 Iustin Pop
    Note that this function will not change the state of the system in
1330 2d0c8319 Iustin Pop
    any way (except in case of side-effects caused by reading from
1331 2d0c8319 Iustin Pop
    /proc).
1332 2d0c8319 Iustin Pop

1333 2d0c8319 Iustin Pop
    """
1334 2d0c8319 Iustin Pop
    used_devs = self._GetUsedDevs()
1335 2d0c8319 Iustin Pop
    if self._aminor in used_devs:
1336 2d0c8319 Iustin Pop
      minor = self._aminor
1337 2d0c8319 Iustin Pop
    else:
1338 2d0c8319 Iustin Pop
      minor = None
1339 2d0c8319 Iustin Pop
1340 2d0c8319 Iustin Pop
    self._SetFromMinor(minor)
1341 2d0c8319 Iustin Pop
    return minor is not None
1342 2d0c8319 Iustin Pop
1343 2d0c8319 Iustin Pop
  def Assemble(self):
1344 2d0c8319 Iustin Pop
    """Assemble the drbd.
1345 2d0c8319 Iustin Pop

1346 2d0c8319 Iustin Pop
    Method:
1347 2d0c8319 Iustin Pop
      - if we have a configured device, we try to ensure that it matches
1348 2d0c8319 Iustin Pop
        our config
1349 2d0c8319 Iustin Pop
      - if not, we create it from zero
1350 2d0c8319 Iustin Pop

1351 2d0c8319 Iustin Pop
    """
1352 2d0c8319 Iustin Pop
    result = super(DRBD8, self).Assemble()
1353 2d0c8319 Iustin Pop
    if not result:
1354 2d0c8319 Iustin Pop
      return result
1355 2d0c8319 Iustin Pop
1356 2d0c8319 Iustin Pop
    self.Attach()
1357 2d0c8319 Iustin Pop
    if self.minor is None:
1358 2d0c8319 Iustin Pop
      # local device completely unconfigured
1359 2d0c8319 Iustin Pop
      return self._FastAssemble()
1360 2d0c8319 Iustin Pop
    else:
1361 2d0c8319 Iustin Pop
      # we have to recheck the local and network status and try to fix
1362 2d0c8319 Iustin Pop
      # the device
1363 2d0c8319 Iustin Pop
      return self._SlowAssemble()
1364 2d0c8319 Iustin Pop
1365 2d0c8319 Iustin Pop
  def _SlowAssemble(self):
1366 2d0c8319 Iustin Pop
    """Assembles the DRBD device from a (partially) configured device.
1367 a2cfdea2 Iustin Pop

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

1372 a2cfdea2 Iustin Pop
    """
1373 a1578d63 Iustin Pop
    for minor in (self._aminor,):
1374 3840729d Iustin Pop
      info = self._GetDevInfo(self._GetShowData(minor))
1375 a2cfdea2 Iustin Pop
      match_l = self._MatchesLocal(info)
1376 a2cfdea2 Iustin Pop
      match_r = self._MatchesNet(info)
1377 a2cfdea2 Iustin Pop
      if match_l and match_r:
1378 a2cfdea2 Iustin Pop
        break
1379 a2cfdea2 Iustin Pop
      if match_l and not match_r and "local_addr" not in info:
1380 a2cfdea2 Iustin Pop
        res_r = self._AssembleNet(minor,
1381 a2cfdea2 Iustin Pop
                                  (self._lhost, self._lport,
1382 a2cfdea2 Iustin Pop
                                   self._rhost, self._rport),
1383 3c03759a Iustin Pop
                                  constants.DRBD_NET_PROTOCOL,
1384 3c03759a Iustin Pop
                                  hmac=constants.DRBD_HMAC_ALG,
1385 2899d9de Iustin Pop
                                  secret=self._secret
1386 2899d9de Iustin Pop
                                  )
1387 3840729d Iustin Pop
        if res_r:
1388 3840729d Iustin Pop
          if self._MatchesNet(self._GetDevInfo(self._GetShowData(minor))):
1389 3840729d Iustin Pop
            break
1390 fc1dc9d7 Iustin Pop
      # the weakest case: we find something that is only net attached
1391 fc1dc9d7 Iustin Pop
      # even though we were passed some children at init time
1392 fc1dc9d7 Iustin Pop
      if match_r and "local_dev" not in info:
1393 fc1dc9d7 Iustin Pop
        break
1394 bf25af3b Iustin Pop
1395 bf25af3b Iustin Pop
      # this case must be considered only if we actually have local
1396 bf25af3b Iustin Pop
      # storage, i.e. not in diskless mode, because all diskless
1397 bf25af3b Iustin Pop
      # devices are equal from the point of view of local
1398 bf25af3b Iustin Pop
      # configuration
1399 bf25af3b Iustin Pop
      if (match_l and "local_dev" in info and
1400 bf25af3b Iustin Pop
          not match_r and "local_addr" in info):
1401 9cdbe77f Iustin Pop
        # strange case - the device network part points to somewhere
1402 9cdbe77f Iustin Pop
        # else, even though its local storage is ours; as we own the
1403 9cdbe77f Iustin Pop
        # drbd space, we try to disconnect from the remote peer and
1404 9cdbe77f Iustin Pop
        # reconnect to our correct one
1405 9cdbe77f Iustin Pop
        if not self._ShutdownNet(minor):
1406 9cdbe77f Iustin Pop
          raise errors.BlockDeviceError("Device has correct local storage,"
1407 9cdbe77f Iustin Pop
                                        " wrong remote peer and is unable to"
1408 9cdbe77f Iustin Pop
                                        " disconnect in order to attach to"
1409 9cdbe77f Iustin Pop
                                        " the correct peer")
1410 9cdbe77f Iustin Pop
        # note: _AssembleNet also handles the case when we don't want
1411 9cdbe77f Iustin Pop
        # local storage (i.e. one or more of the _[lr](host|port) is
1412 9cdbe77f Iustin Pop
        # None)
1413 9cdbe77f Iustin Pop
        if (self._AssembleNet(minor, (self._lhost, self._lport,
1414 3c03759a Iustin Pop
                                      self._rhost, self._rport),
1415 3c03759a Iustin Pop
                              constants.DRBD_NET_PROTOCOL,
1416 2899d9de Iustin Pop
                              hmac=constants.DRBD_HMAC_ALG,
1417 2899d9de Iustin Pop
                              secret=self._secret) and
1418 3840729d Iustin Pop
            self._MatchesNet(self._GetDevInfo(self._GetShowData(minor)))):
1419 9cdbe77f Iustin Pop
          break
1420 9cdbe77f Iustin Pop
1421 a2cfdea2 Iustin Pop
    else:
1422 a2cfdea2 Iustin Pop
      minor = None
1423 a2cfdea2 Iustin Pop
1424 a2cfdea2 Iustin Pop
    self._SetFromMinor(minor)
1425 a2cfdea2 Iustin Pop
    return minor is not None
1426 a2cfdea2 Iustin Pop
1427 2d0c8319 Iustin Pop
  def _FastAssemble(self):
1428 2d0c8319 Iustin Pop
    """Assemble the drbd device from zero.
1429 a2cfdea2 Iustin Pop

1430 2d0c8319 Iustin Pop
    This is run when in Assemble we detect our minor is unused.
1431 a2cfdea2 Iustin Pop

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

1463 b00b95dd Iustin Pop
    I/Os will continue to be served from the remote device. If we
1464 b00b95dd Iustin Pop
    don't have a remote device, this operation will fail.
1465 b00b95dd Iustin Pop

1466 b00b95dd Iustin Pop
    """
1467 b00b95dd Iustin Pop
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "detach"])
1468 b00b95dd Iustin Pop
    if result.failed:
1469 468c5f77 Iustin Pop
      logging.error("Can't detach local device: %s", result.output)
1470 b00b95dd Iustin Pop
    return not result.failed
1471 b00b95dd Iustin Pop
1472 b00b95dd Iustin Pop
  @classmethod
1473 f3e513ad Iustin Pop
  def _ShutdownNet(cls, minor):
1474 f3e513ad Iustin Pop
    """Disconnect from the remote peer.
1475 f3e513ad Iustin Pop

1476 f3e513ad Iustin Pop
    This fails if we don't have a local device.
1477 f3e513ad Iustin Pop

1478 f3e513ad Iustin Pop
    """
1479 f3e513ad Iustin Pop
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "disconnect"])
1480 a8459f1c Iustin Pop
    if result.failed:
1481 468c5f77 Iustin Pop
      logging.error("Can't shutdown network: %s", result.output)
1482 f3e513ad Iustin Pop
    return not result.failed
1483 f3e513ad Iustin Pop
1484 f3e513ad Iustin Pop
  @classmethod
1485 a2cfdea2 Iustin Pop
  def _ShutdownAll(cls, minor):
1486 a2cfdea2 Iustin Pop
    """Deactivate the device.
1487 a2cfdea2 Iustin Pop

1488 a2cfdea2 Iustin Pop
    This will, of course, fail if the device is in use.
1489 a2cfdea2 Iustin Pop

1490 a2cfdea2 Iustin Pop
    """
1491 a2cfdea2 Iustin Pop
    result = utils.RunCmd(["drbdsetup", cls._DevPath(minor), "down"])
1492 a2cfdea2 Iustin Pop
    if result.failed:
1493 468c5f77 Iustin Pop
      logging.error("Can't shutdown drbd device: %s", result.output)
1494 a2cfdea2 Iustin Pop
    return not result.failed
1495 a2cfdea2 Iustin Pop
1496 a2cfdea2 Iustin Pop
  def Shutdown(self):
1497 a2cfdea2 Iustin Pop
    """Shutdown the DRBD device.
1498 a2cfdea2 Iustin Pop

1499 a2cfdea2 Iustin Pop
    """
1500 a2cfdea2 Iustin Pop
    if self.minor is None and not self.Attach():
1501 468c5f77 Iustin Pop
      logging.info("DRBD device not attached to a device during Shutdown")
1502 a2cfdea2 Iustin Pop
      return True
1503 a2cfdea2 Iustin Pop
    if not self._ShutdownAll(self.minor):
1504 a2cfdea2 Iustin Pop
      return False
1505 a2cfdea2 Iustin Pop
    self.minor = None
1506 a2cfdea2 Iustin Pop
    self.dev_path = None
1507 a2cfdea2 Iustin Pop
    return True
1508 a2cfdea2 Iustin Pop
1509 a2cfdea2 Iustin Pop
  def Remove(self):
1510 a2cfdea2 Iustin Pop
    """Stub remove for DRBD devices.
1511 a2cfdea2 Iustin Pop

1512 a2cfdea2 Iustin Pop
    """
1513 a2cfdea2 Iustin Pop
    return self.Shutdown()
1514 a2cfdea2 Iustin Pop
1515 a2cfdea2 Iustin Pop
  @classmethod
1516 a2cfdea2 Iustin Pop
  def Create(cls, unique_id, children, size):
1517 a2cfdea2 Iustin Pop
    """Create a new DRBD8 device.
1518 a2cfdea2 Iustin Pop

1519 a2cfdea2 Iustin Pop
    Since DRBD devices are not created per se, just assembled, this
1520 a2cfdea2 Iustin Pop
    function only initializes the metadata.
1521 a2cfdea2 Iustin Pop

1522 a2cfdea2 Iustin Pop
    """
1523 a2cfdea2 Iustin Pop
    if len(children) != 2:
1524 a2cfdea2 Iustin Pop
      raise errors.ProgrammerError("Invalid setup for the drbd device")
1525 a2cfdea2 Iustin Pop
    meta = children[1]
1526 a2cfdea2 Iustin Pop
    meta.Assemble()
1527 a2cfdea2 Iustin Pop
    if not meta.Attach():
1528 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Can't attach to meta device")
1529 a2cfdea2 Iustin Pop
    if not cls._CheckMetaSize(meta.dev_path):
1530 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Invalid meta device size")
1531 a2cfdea2 Iustin Pop
    cls._InitMeta(cls._FindUnusedMinor(), meta.dev_path)
1532 a2cfdea2 Iustin Pop
    if not cls._IsValidMeta(meta.dev_path):
1533 a2cfdea2 Iustin Pop
      raise errors.BlockDeviceError("Cannot initalize meta device")
1534 a2cfdea2 Iustin Pop
    return cls(unique_id, children)
1535 a2cfdea2 Iustin Pop
1536 1005d816 Iustin Pop
  def Grow(self, amount):
1537 1005d816 Iustin Pop
    """Resize the DRBD device and its backing storage.
1538 1005d816 Iustin Pop

1539 1005d816 Iustin Pop
    """
1540 1005d816 Iustin Pop
    if self.minor is None:
1541 1005d816 Iustin Pop
      raise errors.ProgrammerError("drbd8: Grow called while not attached")
1542 1005d816 Iustin Pop
    if len(self._children) != 2 or None in self._children:
1543 1005d816 Iustin Pop
      raise errors.BlockDeviceError("Cannot grow diskless DRBD8 device")
1544 1005d816 Iustin Pop
    self._children[0].Grow(amount)
1545 1005d816 Iustin Pop
    result = utils.RunCmd(["drbdsetup", self.dev_path, "resize"])
1546 1005d816 Iustin Pop
    if result.failed:
1547 1005d816 Iustin Pop
      raise errors.BlockDeviceError("resize failed for %s: %s" %
1548 1005d816 Iustin Pop
                                    (self.dev_path, result.output))
1549 1005d816 Iustin Pop
    return
1550 1005d816 Iustin Pop
1551 a8083063 Iustin Pop
1552 6f695a2e Manuel Franceschini
class FileStorage(BlockDev):
1553 6f695a2e Manuel Franceschini
  """File device.
1554 abdf0113 Iustin Pop

1555 6f695a2e Manuel Franceschini
  This class represents the a file storage backend device.
1556 6f695a2e Manuel Franceschini

1557 6f695a2e Manuel Franceschini
  The unique_id for the file device is a (file_driver, file_path) tuple.
1558 abdf0113 Iustin Pop

1559 6f695a2e Manuel Franceschini
  """
1560 6f695a2e Manuel Franceschini
  def __init__(self, unique_id, children):
1561 6f695a2e Manuel Franceschini
    """Initalizes a file device backend.
1562 6f695a2e Manuel Franceschini

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

1576 6f695a2e Manuel Franceschini
    Checks whether the file device exists, raises BlockDeviceError otherwise.
1577 6f695a2e Manuel Franceschini

1578 6f695a2e Manuel Franceschini
    """
1579 6f695a2e Manuel Franceschini
    if not os.path.exists(self.dev_path):
1580 6f695a2e Manuel Franceschini
      raise errors.BlockDeviceError("File device '%s' does not exist." %
1581 6f695a2e Manuel Franceschini
                                    self.dev_path)
1582 6f695a2e Manuel Franceschini
    return True
1583 6f695a2e Manuel Franceschini
1584 6f695a2e Manuel Franceschini
  def Shutdown(self):
1585 6f695a2e Manuel Franceschini
    """Shutdown the device.
1586 6f695a2e Manuel Franceschini

1587 6f695a2e Manuel Franceschini
    This is a no-op for the file type, as we don't deacivate
1588 6f695a2e Manuel Franceschini
    the file on shutdown.
1589 6f695a2e Manuel Franceschini

1590 6f695a2e Manuel Franceschini
    """
1591 6f695a2e Manuel Franceschini
    return True
1592 6f695a2e Manuel Franceschini
1593 6f695a2e Manuel Franceschini
  def Open(self, force=False):
1594 6f695a2e Manuel Franceschini
    """Make the device ready for I/O.
1595 6f695a2e Manuel Franceschini

1596 6f695a2e Manuel Franceschini
    This is a no-op for the file type.
1597 6f695a2e Manuel Franceschini

1598 6f695a2e Manuel Franceschini
    """
1599 6f695a2e Manuel Franceschini
    pass
1600 6f695a2e Manuel Franceschini
1601 6f695a2e Manuel Franceschini
  def Close(self):
1602 6f695a2e Manuel Franceschini
    """Notifies that the device will no longer be used for I/O.
1603 6f695a2e Manuel Franceschini

1604 6f695a2e Manuel Franceschini
    This is a no-op for the file type.
1605 6f695a2e Manuel Franceschini

1606 6f695a2e Manuel Franceschini
    """
1607 6f695a2e Manuel Franceschini
    pass
1608 6f695a2e Manuel Franceschini
1609 6f695a2e Manuel Franceschini
  def Remove(self):
1610 6f695a2e Manuel Franceschini
    """Remove the file backing the block device.
1611 6f695a2e Manuel Franceschini

1612 c41eea6e Iustin Pop
    @rtype: boolean
1613 c41eea6e Iustin Pop
    @return: True if the removal was successful
1614 6f695a2e Manuel Franceschini

1615 6f695a2e Manuel Franceschini
    """
1616 6f695a2e Manuel Franceschini
    if not os.path.exists(self.dev_path):
1617 6f695a2e Manuel Franceschini
      return True
1618 6f695a2e Manuel Franceschini
    try:
1619 6f695a2e Manuel Franceschini
      os.remove(self.dev_path)
1620 6f695a2e Manuel Franceschini
      return True
1621 6f695a2e Manuel Franceschini
    except OSError, err:
1622 468c5f77 Iustin Pop
      logging.error("Can't remove file '%s': %s", self.dev_path, err)
1623 6f695a2e Manuel Franceschini
      return False
1624 6f695a2e Manuel Franceschini
1625 6f695a2e Manuel Franceschini
  def Attach(self):
1626 6f695a2e Manuel Franceschini
    """Attach to an existing file.
1627 6f695a2e Manuel Franceschini

1628 6f695a2e Manuel Franceschini
    Check if this file already exists.
1629 6f695a2e Manuel Franceschini

1630 c41eea6e Iustin Pop
    @rtype: boolean
1631 c41eea6e Iustin Pop
    @return: True if file exists
1632 6f695a2e Manuel Franceschini

1633 6f695a2e Manuel Franceschini
    """
1634 ecb091e3 Iustin Pop
    self.attached = os.path.exists(self.dev_path)
1635 ecb091e3 Iustin Pop
    return self.attached
1636 6f695a2e Manuel Franceschini
1637 6f695a2e Manuel Franceschini
  @classmethod
1638 6f695a2e Manuel Franceschini
  def Create(cls, unique_id, children, size):
1639 6f695a2e Manuel Franceschini
    """Create a new file.
1640 6f695a2e Manuel Franceschini

1641 c41eea6e Iustin Pop
    @param size: the size of file in MiB
1642 6f695a2e Manuel Franceschini

1643 c41eea6e Iustin Pop
    @rtype: L{bdev.FileStorage}
1644 c41eea6e Iustin Pop
    @return: an instance of FileStorage
1645 6f695a2e Manuel Franceschini

1646 6f695a2e Manuel Franceschini
    """
1647 6f695a2e Manuel Franceschini
    if not isinstance(unique_id, (tuple, list)) or len(unique_id) != 2:
1648 6f695a2e Manuel Franceschini
      raise ValueError("Invalid configuration data %s" % str(unique_id))
1649 6f695a2e Manuel Franceschini
    dev_path = unique_id[1]
1650 6f695a2e Manuel Franceschini
    try:
1651 6f695a2e Manuel Franceschini
      f = open(dev_path, 'w')
1652 6f695a2e Manuel Franceschini
    except IOError, err:
1653 b62ddbe5 Guido Trotter
      raise errors.BlockDeviceError("Could not create '%'" % err)
1654 6f695a2e Manuel Franceschini
    else:
1655 6f695a2e Manuel Franceschini
      f.truncate(size * 1024 * 1024)
1656 6f695a2e Manuel Franceschini
      f.close()
1657 6f695a2e Manuel Franceschini
1658 6f695a2e Manuel Franceschini
    return FileStorage(unique_id, children)
1659 6f695a2e Manuel Franceschini
1660 6f695a2e Manuel Franceschini
1661 a8083063 Iustin Pop
DEV_MAP = {
1662 fe96220b Iustin Pop
  constants.LD_LV: LogicalVolume,
1663 a1f445d3 Iustin Pop
  constants.LD_DRBD8: DRBD8,
1664 6f695a2e Manuel Franceschini
  constants.LD_FILE: FileStorage,
1665 a8083063 Iustin Pop
  }
1666 a8083063 Iustin Pop
1667 a8083063 Iustin Pop
1668 a8083063 Iustin Pop
def FindDevice(dev_type, unique_id, children):
1669 a8083063 Iustin Pop
  """Search for an existing, assembled device.
1670 a8083063 Iustin Pop

1671 a8083063 Iustin Pop
  This will succeed only if the device exists and is assembled, but it
1672 a8083063 Iustin Pop
  does not do any actions in order to activate the device.
1673 a8083063 Iustin Pop

1674 a8083063 Iustin Pop
  """
1675 a8083063 Iustin Pop
  if dev_type not in DEV_MAP:
1676 a8083063 Iustin Pop
    raise errors.ProgrammerError("Invalid block device type '%s'" % dev_type)
1677 a8083063 Iustin Pop
  device = DEV_MAP[dev_type](unique_id, children)
1678 cb999543 Iustin Pop
  if not device.attached:
1679 a8083063 Iustin Pop
    return None
1680 ecb091e3 Iustin Pop
  return device
1681 a8083063 Iustin Pop
1682 a8083063 Iustin Pop
1683 f96e3c4f Iustin Pop
def Assemble(dev_type, unique_id, children):
1684 a8083063 Iustin Pop
  """Try to attach or assemble an existing device.
1685 a8083063 Iustin Pop

1686 f96e3c4f Iustin Pop
  This will attach to assemble the device, as needed, to bring it
1687 f96e3c4f Iustin Pop
  fully up. It must be safe to run on already-assembled devices.
1688 a8083063 Iustin Pop

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

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