Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 59072e7e

History | View | Annotate | Download (19.8 kB)

1
#
2
#
3

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

    
21

    
22
"""Configuration management for Ganeti
23

24
This module provides the interface to the Ganeti cluster configuration.
25

26
The configuration data is stored on every node but is updated on the master
27
only. After each update, the master distributes the data to the other nodes.
28

29
Currently, the data storage format is JSON. YAML was slow and consuming too
30
much memory.
31

32
"""
33

    
34
import os
35
import tempfile
36
import random
37

    
38
from ganeti import errors
39
from ganeti import logger
40
from ganeti import utils
41
from ganeti import constants
42
from ganeti import rpc
43
from ganeti import objects
44

    
45

    
46
class ConfigWriter:
47
  """The interface to the cluster configuration.
48

49
  """
50
  def __init__(self, cfg_file=None, offline=False):
51
    self._config_data = None
52
    self._config_time = None
53
    self._config_size = None
54
    self._config_inode = None
55
    self._offline = offline
56
    if cfg_file is None:
57
      self._cfg_file = constants.CLUSTER_CONF_FILE
58
    else:
59
      self._cfg_file = cfg_file
60
    self._temporary_ids = set()
61
    # Note: in order to prevent errors when resolving our name in
62
    # _DistributeConfig, we compute it here once and reuse it; it's
63
    # better to raise an error before starting to modify the config
64
    # file than after it was modified
65
    self._my_hostname = utils.HostInfo().name
66

    
67
  # this method needs to be static, so that we can call it on the class
68
  @staticmethod
69
  def IsCluster():
70
    """Check if the cluster is configured.
71

72
    """
73
    return os.path.exists(constants.CLUSTER_CONF_FILE)
74

    
75
  def GenerateMAC(self):
76
    """Generate a MAC for an instance.
77

78
    This should check the current instances for duplicates.
79

80
    """
81
    self._OpenConfig()
82
    self._ReleaseLock()
83
    prefix = self._config_data.cluster.mac_prefix
84
    all_macs = self._AllMACs()
85
    retries = 64
86
    while retries > 0:
87
      byte1 = random.randrange(0, 256)
88
      byte2 = random.randrange(0, 256)
89
      byte3 = random.randrange(0, 256)
90
      mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
91
      if mac not in all_macs:
92
        break
93
      retries -= 1
94
    else:
95
      raise errors.ConfigurationError("Can't generate unique MAC")
96
    return mac
97

    
98
  def _ComputeAllLVs(self):
99
    """Compute the list of all LVs.
100

101
    """
102
    self._OpenConfig()
103
    self._ReleaseLock()
104
    lvnames = set()
105
    for instance in self._config_data.instances.values():
106
      node_data = instance.MapLVsByNode()
107
      for lv_list in node_data.values():
108
        lvnames.update(lv_list)
109
    return lvnames
110

    
111
  def GenerateUniqueID(self, exceptions=None):
112
    """Generate an unique disk name.
113

114
    This checks the current node, instances and disk names for
115
    duplicates.
116

117
    Args:
118
      - exceptions: a list with some other names which should be checked
119
                    for uniqueness (used for example when you want to get
120
                    more than one id at one time without adding each one in
121
                    turn to the config file
122

123
    Returns: the unique id as a string
124

125
    """
126
    existing = set()
127
    existing.update(self._temporary_ids)
128
    existing.update(self._ComputeAllLVs())
129
    existing.update(self._config_data.instances.keys())
130
    existing.update(self._config_data.nodes.keys())
131
    if exceptions is not None:
132
      existing.update(exceptions)
133
    retries = 64
134
    while retries > 0:
135
      unique_id = utils.GetUUID()
136
      if unique_id not in existing and unique_id is not None:
137
        break
138
    else:
139
      raise errors.ConfigurationError("Not able generate an unique ID"
140
                                      " (last tried ID: %s" % unique_id)
141
    self._temporary_ids.add(unique_id)
142
    return unique_id
143

    
144
  def _AllMACs(self):
145
    """Return all MACs present in the config.
146

147
    """
148
    self._OpenConfig()
149
    self._ReleaseLock()
150

    
151
    result = []
152
    for instance in self._config_data.instances.values():
153
      for nic in instance.nics:
154
        result.append(nic.mac)
155

    
156
    return result
157

    
158
  def VerifyConfig(self):
159
    """Stub verify function.
160
    """
161
    self._OpenConfig()
162
    self._ReleaseLock()
163

    
164
    result = []
165
    seen_macs = []
166
    data = self._config_data
167
    for instance_name in data.instances:
168
      instance = data.instances[instance_name]
169
      if instance.primary_node not in data.nodes:
170
        result.append("Instance '%s' has invalid primary node '%s'" %
171
                      (instance_name, instance.primary_node))
172
      for snode in instance.secondary_nodes:
173
        if snode not in data.nodes:
174
          result.append("Instance '%s' has invalid secondary node '%s'" %
175
                        (instance_name, snode))
176
      for idx, nic in enumerate(instance.nics):
177
        if nic.mac in seen_macs:
178
          result.append("Instance '%s' has NIC %d mac %s duplicate" %
179
                        (instance_name, idx, nic.mac))
180
        else:
181
          seen_macs.append(nic.mac)
182
    return result
183

    
184
  def SetDiskID(self, disk, node_name):
185
    """Convert the unique ID to the ID needed on the target nodes.
186

187
    This is used only for drbd, which needs ip/port configuration.
188

189
    The routine descends down and updates its children also, because
190
    this helps when the only the top device is passed to the remote
191
    node.
192

193
    """
194
    if disk.children:
195
      for child in disk.children:
196
        self.SetDiskID(child, node_name)
197

    
198
    if disk.logical_id is None and disk.physical_id is not None:
199
      return
200
    if disk.dev_type == "drbd":
201
      pnode, snode, port = disk.logical_id
202
      if node_name not in (pnode, snode):
203
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
204
                                        node_name)
205
      pnode_info = self.GetNodeInfo(pnode)
206
      snode_info = self.GetNodeInfo(snode)
207
      if pnode_info is None or snode_info is None:
208
        raise errors.ConfigurationError("Can't find primary or secondary node"
209
                                        " for %s" % str(disk))
210
      if pnode == node_name:
211
        disk.physical_id = (pnode_info.secondary_ip, port,
212
                            snode_info.secondary_ip, port)
213
      else: # it must be secondary, we tested above
214
        disk.physical_id = (snode_info.secondary_ip, port,
215
                            pnode_info.secondary_ip, port)
216
    else:
217
      disk.physical_id = disk.logical_id
218
    return
219

    
220
  def AddTcpUdpPort(self, port):
221
    """Adds a new port to the available port pool.
222

223
    """
224
    if not isinstance(port, int):
225
      raise errors.ProgrammerError("Invalid type passed for port")
226

    
227
    self._OpenConfig()
228
    self._config_data.cluster.tcpudp_port_pool.add(port)
229
    self._WriteConfig()
230

    
231
  def GetPortList(self):
232
    """Returns a copy of the current port list.
233

234
    """
235
    self._OpenConfig()
236
    self._ReleaseLock()
237
    return self._config_data.cluster.tcpudp_port_pool.copy()
238

    
239
  def AllocatePort(self):
240
    """Allocate a port.
241

242
    The port will be taken from the available port pool or from the
243
    default port range (and in this case we increase
244
    highest_used_port).
245

246
    """
247
    self._OpenConfig()
248

    
249
    # If there are TCP/IP ports configured, we use them first.
250
    if self._config_data.cluster.tcpudp_port_pool:
251
      port = self._config_data.cluster.tcpudp_port_pool.pop()
252
    else:
253
      port = self._config_data.cluster.highest_used_port + 1
254
      if port >= constants.LAST_DRBD_PORT:
255
        raise errors.ConfigurationError("The highest used port is greater"
256
                                        " than %s. Aborting." %
257
                                        constants.LAST_DRBD_PORT)
258
      self._config_data.cluster.highest_used_port = port
259

    
260
    self._WriteConfig()
261
    return port
262

    
263
  def GetHostKey(self):
264
    """Return the rsa hostkey from the config.
265

266
    Args: None
267

268
    Returns: rsa hostkey
269
    """
270
    self._OpenConfig()
271
    self._ReleaseLock()
272
    return self._config_data.cluster.rsahostkeypub
273

    
274
  def AddInstance(self, instance):
275
    """Add an instance to the config.
276

277
    This should be used after creating a new instance.
278

279
    Args:
280
      instance: the instance object
281
    """
282
    if not isinstance(instance, objects.Instance):
283
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
284

    
285
    if instance.disk_template != constants.DT_DISKLESS:
286
      all_lvs = instance.MapLVsByNode()
287
      logger.Info("Instance '%s' DISK_LAYOUT: %s" % (instance.name, all_lvs))
288

    
289
    self._OpenConfig()
290
    self._config_data.instances[instance.name] = instance
291
    self._WriteConfig()
292

    
293
  def MarkInstanceUp(self, instance_name):
294
    """Mark the instance status to up in the config.
295

296
    """
297
    self._OpenConfig()
298

    
299
    if instance_name not in self._config_data.instances:
300
      raise errors.ConfigurationError("Unknown instance '%s'" %
301
                                      instance_name)
302
    instance = self._config_data.instances[instance_name]
303
    instance.status = "up"
304
    self._WriteConfig()
305

    
306
  def RemoveInstance(self, instance_name):
307
    """Remove the instance from the configuration.
308

309
    """
310
    self._OpenConfig()
311

    
312
    if instance_name not in self._config_data.instances:
313
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
314
    del self._config_data.instances[instance_name]
315
    self._WriteConfig()
316

    
317
  def RenameInstance(self, old_name, new_name):
318
    """Rename an instance.
319

320
    This needs to be done in ConfigWriter and not by RemoveInstance
321
    combined with AddInstance as only we can guarantee an atomic
322
    rename.
323

324
    """
325
    self._OpenConfig()
326
    if old_name not in self._config_data.instances:
327
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
328
    inst = self._config_data.instances[old_name]
329
    del self._config_data.instances[old_name]
330
    inst.name = new_name
331
    self._config_data.instances[inst.name] = inst
332
    self._WriteConfig()
333

    
334
  def MarkInstanceDown(self, instance_name):
335
    """Mark the status of an instance to down in the configuration.
336

337
    """
338
    self._OpenConfig()
339

    
340
    if instance_name not in self._config_data.instances:
341
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
342
    instance = self._config_data.instances[instance_name]
343
    instance.status = "down"
344
    self._WriteConfig()
345

    
346
  def GetInstanceList(self):
347
    """Get the list of instances.
348

349
    Returns:
350
      array of instances, ex. ['instance2.example.com','instance1.example.com']
351
      these contains all the instances, also the ones in Admin_down state
352

353
    """
354
    self._OpenConfig()
355
    self._ReleaseLock()
356

    
357
    return self._config_data.instances.keys()
358

    
359
  def ExpandInstanceName(self, short_name):
360
    """Attempt to expand an incomplete instance name.
361

362
    """
363
    self._OpenConfig()
364
    self._ReleaseLock()
365

    
366
    return utils.MatchNameComponent(short_name,
367
                                    self._config_data.instances.keys())
368

    
369
  def GetInstanceInfo(self, instance_name):
370
    """Returns informations about an instance.
371

372
    It takes the information from the configuration file. Other informations of
373
    an instance are taken from the live systems.
374

375
    Args:
376
      instance: name of the instance, ex instance1.example.com
377

378
    Returns:
379
      the instance object
380

381
    """
382
    self._OpenConfig()
383
    self._ReleaseLock()
384

    
385
    if instance_name not in self._config_data.instances:
386
      return None
387

    
388
    return self._config_data.instances[instance_name]
389

    
390
  def AddNode(self, node):
391
    """Add a node to the configuration.
392

393
    Args:
394
      node: an object.Node instance
395

396
    """
397
    self._OpenConfig()
398
    self._config_data.nodes[node.name] = node
399
    self._WriteConfig()
400

    
401
  def RemoveNode(self, node_name):
402
    """Remove a node from the configuration.
403

404
    """
405
    self._OpenConfig()
406
    if node_name not in self._config_data.nodes:
407
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
408

    
409
    del self._config_data.nodes[node_name]
410
    self._WriteConfig()
411

    
412
  def ExpandNodeName(self, short_name):
413
    """Attempt to expand an incomplete instance name.
414

415
    """
416
    self._OpenConfig()
417
    self._ReleaseLock()
418

    
419
    return utils.MatchNameComponent(short_name,
420
                                    self._config_data.nodes.keys())
421

    
422
  def GetNodeInfo(self, node_name):
423
    """Get the configuration of a node, as stored in the config.
424

425
    Args: node: nodename (tuple) of the node
426

427
    Returns: the node object
428

429
    """
430
    self._OpenConfig()
431
    self._ReleaseLock()
432

    
433
    if node_name not in self._config_data.nodes:
434
      return None
435

    
436
    return self._config_data.nodes[node_name]
437

    
438
  def GetNodeList(self):
439
    """Return the list of nodes which are in the configuration.
440

441
    """
442
    self._OpenConfig()
443
    self._ReleaseLock()
444
    return self._config_data.nodes.keys()
445

    
446
  def DumpConfig(self):
447
    """Return the entire configuration of the cluster.
448
    """
449
    self._OpenConfig()
450
    self._ReleaseLock()
451
    return self._config_data
452

    
453
  def _BumpSerialNo(self):
454
    """Bump up the serial number of the config.
455

456
    """
457
    self._config_data.cluster.serial_no += 1
458

    
459
  def _OpenConfig(self):
460
    """Read the config data from disk.
461

462
    In case we already have configuration data and the config file has
463
    the same mtime as when we read it, we skip the parsing of the
464
    file, since de-serialisation could be slow.
465

466
    """
467
    try:
468
      st = os.stat(self._cfg_file)
469
    except OSError, err:
470
      raise errors.ConfigurationError("Can't stat config file: %s" % err)
471
    if (self._config_data is not None and
472
        self._config_time is not None and
473
        self._config_time == st.st_mtime and
474
        self._config_size == st.st_size and
475
        self._config_inode == st.st_ino):
476
      # data is current, so skip loading of config file
477
      return
478
    f = open(self._cfg_file, 'r')
479
    try:
480
      try:
481
        data = objects.ConfigData.Load(f)
482
      except Exception, err:
483
        raise errors.ConfigurationError(err)
484
    finally:
485
      f.close()
486
    if (not hasattr(data, 'cluster') or
487
        not hasattr(data.cluster, 'config_version')):
488
      raise errors.ConfigurationError("Incomplete configuration"
489
                                      " (missing cluster.config_version)")
490
    if data.cluster.config_version != constants.CONFIG_VERSION:
491
      raise errors.ConfigurationError("Cluster configuration version"
492
                                      " mismatch, got %s instead of %s" %
493
                                      (data.cluster.config_version,
494
                                       constants.CONFIG_VERSION))
495
    self._config_data = data
496
    self._config_time = st.st_mtime
497
    self._config_size = st.st_size
498
    self._config_inode = st.st_ino
499

    
500
  def _ReleaseLock(self):
501
    """xxxx
502
    """
503

    
504
  def _DistributeConfig(self):
505
    """Distribute the configuration to the other nodes.
506

507
    Currently, this only copies the configuration file. In the future,
508
    it could be used to encapsulate the 2/3-phase update mechanism.
509

510
    """
511
    if self._offline:
512
      return True
513
    bad = False
514
    nodelist = self.GetNodeList()
515
    myhostname = self._my_hostname
516

    
517
    tgt_list = []
518
    for node in nodelist:
519
      nodeinfo = self.GetNodeInfo(node)
520
      if nodeinfo.name == myhostname:
521
        continue
522
      tgt_list.append(node)
523

    
524
    result = rpc.call_upload_file(tgt_list, self._cfg_file)
525
    for node in tgt_list:
526
      if not result[node]:
527
        logger.Error("copy of file %s to node %s failed" %
528
                     (self._cfg_file, node))
529
        bad = True
530
    return not bad
531

    
532
  def _WriteConfig(self, destination=None):
533
    """Write the configuration data to persistent storage.
534

535
    """
536
    if destination is None:
537
      destination = self._cfg_file
538
    self._BumpSerialNo()
539
    dir_name, file_name = os.path.split(destination)
540
    fd, name = tempfile.mkstemp('.newconfig', file_name, dir_name)
541
    f = os.fdopen(fd, 'w')
542
    try:
543
      self._config_data.Dump(f)
544
      os.fsync(f.fileno())
545
    finally:
546
      f.close()
547
    # we don't need to do os.close(fd) as f.close() did it
548
    os.rename(name, destination)
549
    # re-set our cache as not to re-read the config file
550
    try:
551
      st = os.stat(destination)
552
    except OSError, err:
553
      raise errors.ConfigurationError("Can't stat config file: %s" % err)
554
    self._config_time = st.st_mtime
555
    self._config_size = st.st_size
556
    self._config_inode = st.st_ino
557
    # and redistribute the config file
558
    self._DistributeConfig()
559

    
560
  def InitConfig(self, node, primary_ip, secondary_ip,
561
                 hostkeypub, mac_prefix, vg_name, def_bridge):
562
    """Create the initial cluster configuration.
563

564
    It will contain the current node, which will also be the master
565
    node, and no instances or operating systmes.
566

567
    Args:
568
      node: the nodename of the initial node
569
      primary_ip: the IP address of the current host
570
      secondary_ip: the secondary IP of the current host or None
571
      hostkeypub: the public hostkey of this host
572

573
    """
574
    hu_port = constants.FIRST_DRBD_PORT - 1
575
    globalconfig = objects.Cluster(config_version=constants.CONFIG_VERSION,
576
                                   serial_no=1,
577
                                   rsahostkeypub=hostkeypub,
578
                                   highest_used_port=hu_port,
579
                                   mac_prefix=mac_prefix,
580
                                   volume_group_name=vg_name,
581
                                   default_bridge=def_bridge,
582
                                   tcpudp_port_pool=set())
583
    if secondary_ip is None:
584
      secondary_ip = primary_ip
585
    nodeconfig = objects.Node(name=node, primary_ip=primary_ip,
586
                              secondary_ip=secondary_ip)
587

    
588
    self._config_data = objects.ConfigData(nodes={node: nodeconfig},
589
                                           instances={},
590
                                           cluster=globalconfig)
591
    self._WriteConfig()
592

    
593
  def GetVGName(self):
594
    """Return the volume group name.
595

596
    """
597
    self._OpenConfig()
598
    self._ReleaseLock()
599
    return self._config_data.cluster.volume_group_name
600

    
601
  def GetDefBridge(self):
602
    """Return the default bridge.
603

604
    """
605
    self._OpenConfig()
606
    self._ReleaseLock()
607
    return self._config_data.cluster.default_bridge
608

    
609
  def GetMACPrefix(self):
610
    """Return the mac prefix.
611

612
    """
613
    self._OpenConfig()
614
    self._ReleaseLock()
615
    return self._config_data.cluster.mac_prefix
616

    
617
  def GetClusterInfo(self):
618
    """Returns informations about the cluster
619

620
    Returns:
621
      the cluster object
622

623
    """
624
    self._OpenConfig()
625
    self._ReleaseLock()
626

    
627
    return self._config_data.cluster
628

    
629
  def Update(self, target):
630
    """Notify function to be called after updates.
631

632
    This function must be called when an object (as returned by
633
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
634
    caller wants the modifications saved to the backing store. Note
635
    that all modified objects will be saved, but the target argument
636
    is the one the caller wants to ensure that it's saved.
637

638
    """
639
    if self._config_data is None:
640
      raise errors.ProgrammerError("Configuration file not read,"
641
                                   " cannot save.")
642
    if isinstance(target, objects.Cluster):
643
      test = target == self._config_data.cluster
644
    elif isinstance(target, objects.Node):
645
      test = target in self._config_data.nodes.values()
646
    elif isinstance(target, objects.Instance):
647
      test = target in self._config_data.instances.values()
648
    else:
649
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
650
                                   " ConfigWriter.Update" % type(target))
651
    if not test:
652
      raise errors.ConfigurationError("Configuration updated since object"
653
                                      " has been read or unknown object")
654
    self._WriteConfig()