Statistics
| Branch: | Tag: | Revision:

root / lib / server / noded.py @ aa922d64

History | View | Annotate | Download (31 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2010, 2011, 2012 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
"""Ganeti node daemon"""
23

    
24
# pylint: disable=C0103,W0142
25

    
26
# C0103: Functions in this module need to have a given name structure,
27
# and the name of the daemon doesn't match
28

    
29
# W0142: Used * or ** magic, since we do use it extensively in this
30
# module
31

    
32
import os
33
import sys
34
import logging
35
import signal
36
import codecs
37

    
38
from optparse import OptionParser
39

    
40
from ganeti import backend
41
from ganeti import constants
42
from ganeti import objects
43
from ganeti import errors
44
from ganeti import jstore
45
from ganeti import daemon
46
from ganeti import http
47
from ganeti import utils
48
from ganeti import storage
49
from ganeti import serializer
50
from ganeti import netutils
51
from ganeti import pathutils
52
from ganeti import ssconf
53

    
54
import ganeti.http.server # pylint: disable=W0611
55

    
56

    
57
queue_lock = None
58

    
59

    
60
def _PrepareQueueLock():
61
  """Try to prepare the queue lock.
62

63
  @return: None for success, otherwise an exception object
64

65
  """
66
  global queue_lock # pylint: disable=W0603
67

    
68
  if queue_lock is not None:
69
    return None
70

    
71
  # Prepare job queue
72
  try:
73
    queue_lock = jstore.InitAndVerifyQueue(must_lock=False)
74
    return None
75
  except EnvironmentError, err:
76
    return err
77

    
78

    
79
def _RequireJobQueueLock(fn):
80
  """Decorator for job queue manipulating functions.
81

82
  """
83
  QUEUE_LOCK_TIMEOUT = 10
84

    
85
  def wrapper(*args, **kwargs):
86
    # Locking in exclusive, blocking mode because there could be several
87
    # children running at the same time. Waiting up to 10 seconds.
88
    if _PrepareQueueLock() is not None:
89
      raise errors.JobQueueError("Job queue failed initialization,"
90
                                 " cannot update jobs")
91
    queue_lock.Exclusive(blocking=True, timeout=QUEUE_LOCK_TIMEOUT)
92
    try:
93
      return fn(*args, **kwargs)
94
    finally:
95
      queue_lock.Unlock()
96

    
97
  return wrapper
98

    
99

    
100
def _DecodeImportExportIO(ieio, ieioargs):
101
  """Decodes import/export I/O information.
102

103
  """
104
  if ieio == constants.IEIO_RAW_DISK:
105
    assert len(ieioargs) == 1
106
    return (objects.Disk.FromDict(ieioargs[0]), )
107

    
108
  if ieio == constants.IEIO_SCRIPT:
109
    assert len(ieioargs) == 2
110
    return (objects.Disk.FromDict(ieioargs[0]), ieioargs[1])
111

    
112
  return ieioargs
113

    
114

    
115
def _DefaultAlternative(value, default):
116
  """Returns value or, if evaluating to False, a default value.
117

118
  Returns the given value, unless it evaluates to False. In the latter case the
119
  default value is returned.
120

121
  @param value: Value to return if it doesn't evaluate to False
122
  @param default: Default value
123
  @return: Given value or the default
124

125
  """
126
  if value:
127
    return value
128

    
129
  return default
130

    
131

    
132
class MlockallRequestExecutor(http.server.HttpServerRequestExecutor):
133
  """Subclass ensuring request handlers are locked in RAM.
134

135
  """
136
  def __init__(self, *args, **kwargs):
137
    utils.Mlockall()
138

    
139
    http.server.HttpServerRequestExecutor.__init__(self, *args, **kwargs)
140

    
141

    
142
class NodeRequestHandler(http.server.HttpServerHandler):
143
  """The server implementation.
144

145
  This class holds all methods exposed over the RPC interface.
146

147
  """
148
  # too many public methods, and unused args - all methods get params
149
  # due to the API
150
  # pylint: disable=R0904,W0613
151
  def __init__(self):
152
    http.server.HttpServerHandler.__init__(self)
153
    self.noded_pid = os.getpid()
154

    
155
  def HandleRequest(self, req):
156
    """Handle a request.
157

158
    """
159
    if req.request_method.upper() != http.HTTP_POST:
160
      raise http.HttpBadRequest("Only the POST method is supported")
161

    
162
    path = req.request_path
163
    if path.startswith("/"):
164
      path = path[1:]
165

    
166
    method = getattr(self, "perspective_%s" % path, None)
167
    if method is None:
168
      raise http.HttpNotFound()
169

    
170
    try:
171
      result = (True, method(serializer.LoadJson(req.request_body)))
172

    
173
    except backend.RPCFail, err:
174
      # our custom failure exception; str(err) works fine if the
175
      # exception was constructed with a single argument, and in
176
      # this case, err.message == err.args[0] == str(err)
177
      result = (False, str(err))
178
    except errors.QuitGanetiException, err:
179
      # Tell parent to quit
180
      logging.info("Shutting down the node daemon, arguments: %s",
181
                   str(err.args))
182
      os.kill(self.noded_pid, signal.SIGTERM)
183
      # And return the error's arguments, which must be already in
184
      # correct tuple format
185
      result = err.args
186
    except Exception, err:
187
      logging.exception("Error in RPC call")
188
      result = (False, "Error while executing backend function: %s" % str(err))
189

    
190
    return serializer.DumpJson(result)
191

    
192
  # the new block devices  --------------------------
193

    
194
  @staticmethod
195
  def perspective_blockdev_create(params):
196
    """Create a block device.
197

198
    """
199
    (bdev_s, size, owner, on_primary, info, excl_stor) = params
200
    bdev = objects.Disk.FromDict(bdev_s)
201
    if bdev is None:
202
      raise ValueError("can't unserialize data!")
203
    return backend.BlockdevCreate(bdev, size, owner, on_primary, info,
204
                                  excl_stor)
205

    
206
  @staticmethod
207
  def perspective_blockdev_pause_resume_sync(params):
208
    """Pause/resume sync of a block device.
209

210
    """
211
    disks_s, pause = params
212
    disks = [objects.Disk.FromDict(bdev_s) for bdev_s in disks_s]
213
    return backend.BlockdevPauseResumeSync(disks, pause)
214

    
215
  @staticmethod
216
  def perspective_blockdev_wipe(params):
217
    """Wipe a block device.
218

219
    """
220
    bdev_s, offset, size = params
221
    bdev = objects.Disk.FromDict(bdev_s)
222
    return backend.BlockdevWipe(bdev, offset, size)
223

    
224
  @staticmethod
225
  def perspective_blockdev_remove(params):
226
    """Remove a block device.
227

228
    """
229
    bdev_s = params[0]
230
    bdev = objects.Disk.FromDict(bdev_s)
231
    return backend.BlockdevRemove(bdev)
232

    
233
  @staticmethod
234
  def perspective_blockdev_rename(params):
235
    """Remove a block device.
236

237
    """
238
    devlist = [(objects.Disk.FromDict(ds), uid) for ds, uid in params[0]]
239
    return backend.BlockdevRename(devlist)
240

    
241
  @staticmethod
242
  def perspective_blockdev_assemble(params):
243
    """Assemble a block device.
244

245
    """
246
    bdev_s, owner, on_primary, idx = params
247
    bdev = objects.Disk.FromDict(bdev_s)
248
    if bdev is None:
249
      raise ValueError("can't unserialize data!")
250
    return backend.BlockdevAssemble(bdev, owner, on_primary, idx)
251

    
252
  @staticmethod
253
  def perspective_blockdev_shutdown(params):
254
    """Shutdown a block device.
255

256
    """
257
    bdev_s = params[0]
258
    bdev = objects.Disk.FromDict(bdev_s)
259
    if bdev is None:
260
      raise ValueError("can't unserialize data!")
261
    return backend.BlockdevShutdown(bdev)
262

    
263
  @staticmethod
264
  def perspective_blockdev_addchildren(params):
265
    """Add a child to a mirror device.
266

267
    Note: this is only valid for mirror devices. It's the caller's duty
268
    to send a correct disk, otherwise we raise an error.
269

270
    """
271
    bdev_s, ndev_s = params
272
    bdev = objects.Disk.FromDict(bdev_s)
273
    ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
274
    if bdev is None or ndevs.count(None) > 0:
275
      raise ValueError("can't unserialize data!")
276
    return backend.BlockdevAddchildren(bdev, ndevs)
277

    
278
  @staticmethod
279
  def perspective_blockdev_removechildren(params):
280
    """Remove a child from a mirror device.
281

282
    This is only valid for mirror devices, of course. It's the callers
283
    duty to send a correct disk, otherwise we raise an error.
284

285
    """
286
    bdev_s, ndev_s = params
287
    bdev = objects.Disk.FromDict(bdev_s)
288
    ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
289
    if bdev is None or ndevs.count(None) > 0:
290
      raise ValueError("can't unserialize data!")
291
    return backend.BlockdevRemovechildren(bdev, ndevs)
292

    
293
  @staticmethod
294
  def perspective_blockdev_getmirrorstatus(params):
295
    """Return the mirror status for a list of disks.
296

297
    """
298
    disks = [objects.Disk.FromDict(dsk_s)
299
             for dsk_s in params[0]]
300
    return [status.ToDict()
301
            for status in backend.BlockdevGetmirrorstatus(disks)]
302

    
303
  @staticmethod
304
  def perspective_blockdev_getmirrorstatus_multi(params):
305
    """Return the mirror status for a list of disks.
306

307
    """
308
    (node_disks, ) = params
309

    
310
    disks = [objects.Disk.FromDict(dsk_s) for dsk_s in node_disks]
311

    
312
    result = []
313

    
314
    for (success, status) in backend.BlockdevGetmirrorstatusMulti(disks):
315
      if success:
316
        result.append((success, status.ToDict()))
317
      else:
318
        result.append((success, status))
319

    
320
    return result
321

    
322
  @staticmethod
323
  def perspective_blockdev_find(params):
324
    """Expose the FindBlockDevice functionality for a disk.
325

326
    This will try to find but not activate a disk.
327

328
    """
329
    disk = objects.Disk.FromDict(params[0])
330

    
331
    result = backend.BlockdevFind(disk)
332
    if result is None:
333
      return None
334

    
335
    return result.ToDict()
336

    
337
  @staticmethod
338
  def perspective_blockdev_snapshot(params):
339
    """Create a snapshot device.
340

341
    Note that this is only valid for LVM disks, if we get passed
342
    something else we raise an exception. The snapshot device can be
343
    remove by calling the generic block device remove call.
344

345
    """
346
    cfbd = objects.Disk.FromDict(params[0])
347
    return backend.BlockdevSnapshot(cfbd)
348

    
349
  @staticmethod
350
  def perspective_blockdev_grow(params):
351
    """Grow a stack of devices.
352

353
    """
354
    if len(params) < 4:
355
      raise ValueError("Received only 3 parameters in blockdev_grow,"
356
                       " old master?")
357
    cfbd = objects.Disk.FromDict(params[0])
358
    amount = params[1]
359
    dryrun = params[2]
360
    backingstore = params[3]
361
    return backend.BlockdevGrow(cfbd, amount, dryrun, backingstore)
362

    
363
  @staticmethod
364
  def perspective_blockdev_close(params):
365
    """Closes the given block devices.
366

367
    """
368
    disks = [objects.Disk.FromDict(cf) for cf in params[1]]
369
    return backend.BlockdevClose(params[0], disks)
370

    
371
  @staticmethod
372
  def perspective_blockdev_getsize(params):
373
    """Compute the sizes of the given block devices.
374

375
    """
376
    disks = [objects.Disk.FromDict(cf) for cf in params[0]]
377
    return backend.BlockdevGetsize(disks)
378

    
379
  @staticmethod
380
  def perspective_blockdev_export(params):
381
    """Compute the sizes of the given block devices.
382

383
    """
384
    disk = objects.Disk.FromDict(params[0])
385
    dest_node, dest_path, cluster_name = params[1:]
386
    return backend.BlockdevExport(disk, dest_node, dest_path, cluster_name)
387

    
388
  @staticmethod
389
  def perspective_blockdev_setinfo(params):
390
    """Sets metadata information on the given block device.
391

392
    """
393
    (disk, info) = params
394
    disk = objects.Disk.FromDict(disk)
395
    return backend.BlockdevSetInfo(disk, info)
396

    
397
  # blockdev/drbd specific methods ----------
398

    
399
  @staticmethod
400
  def perspective_drbd_disconnect_net(params):
401
    """Disconnects the network connection of drbd disks.
402

403
    Note that this is only valid for drbd disks, so the members of the
404
    disk list must all be drbd devices.
405

406
    """
407
    nodes_ip, disks = params
408
    disks = [objects.Disk.FromDict(cf) for cf in disks]
409
    return backend.DrbdDisconnectNet(nodes_ip, disks)
410

    
411
  @staticmethod
412
  def perspective_drbd_attach_net(params):
413
    """Attaches the network connection of drbd disks.
414

415
    Note that this is only valid for drbd disks, so the members of the
416
    disk list must all be drbd devices.
417

418
    """
419
    nodes_ip, disks, instance_name, multimaster = params
420
    disks = [objects.Disk.FromDict(cf) for cf in disks]
421
    return backend.DrbdAttachNet(nodes_ip, disks,
422
                                     instance_name, multimaster)
423

    
424
  @staticmethod
425
  def perspective_drbd_wait_sync(params):
426
    """Wait until DRBD disks are synched.
427

428
    Note that this is only valid for drbd disks, so the members of the
429
    disk list must all be drbd devices.
430

431
    """
432
    nodes_ip, disks = params
433
    disks = [objects.Disk.FromDict(cf) for cf in disks]
434
    return backend.DrbdWaitSync(nodes_ip, disks)
435

    
436
  @staticmethod
437
  def perspective_drbd_helper(params):
438
    """Query drbd helper.
439

440
    """
441
    return backend.GetDrbdUsermodeHelper()
442

    
443
  # export/import  --------------------------
444

    
445
  @staticmethod
446
  def perspective_finalize_export(params):
447
    """Expose the finalize export functionality.
448

449
    """
450
    instance = objects.Instance.FromDict(params[0])
451

    
452
    snap_disks = []
453
    for disk in params[1]:
454
      if isinstance(disk, bool):
455
        snap_disks.append(disk)
456
      else:
457
        snap_disks.append(objects.Disk.FromDict(disk))
458

    
459
    return backend.FinalizeExport(instance, snap_disks)
460

    
461
  @staticmethod
462
  def perspective_export_info(params):
463
    """Query information about an existing export on this node.
464

465
    The given path may not contain an export, in which case we return
466
    None.
467

468
    """
469
    path = params[0]
470
    return backend.ExportInfo(path)
471

    
472
  @staticmethod
473
  def perspective_export_list(params):
474
    """List the available exports on this node.
475

476
    Note that as opposed to export_info, which may query data about an
477
    export in any path, this only queries the standard Ganeti path
478
    (pathutils.EXPORT_DIR).
479

480
    """
481
    return backend.ListExports()
482

    
483
  @staticmethod
484
  def perspective_export_remove(params):
485
    """Remove an export.
486

487
    """
488
    export = params[0]
489
    return backend.RemoveExport(export)
490

    
491
  # block device ---------------------
492
  @staticmethod
493
  def perspective_bdev_sizes(params):
494
    """Query the list of block devices
495

496
    """
497
    devices = params[0]
498
    return backend.GetBlockDevSizes(devices)
499

    
500
  # volume  --------------------------
501

    
502
  @staticmethod
503
  def perspective_lv_list(params):
504
    """Query the list of logical volumes in a given volume group.
505

506
    """
507
    vgname = params[0]
508
    return backend.GetVolumeList(vgname)
509

    
510
  @staticmethod
511
  def perspective_vg_list(params):
512
    """Query the list of volume groups.
513

514
    """
515
    return backend.ListVolumeGroups()
516

    
517
  # Storage --------------------------
518

    
519
  @staticmethod
520
  def perspective_storage_list(params):
521
    """Get list of storage units.
522

523
    """
524
    (su_name, su_args, name, fields) = params
525
    return storage.GetStorage(su_name, *su_args).List(name, fields)
526

    
527
  @staticmethod
528
  def perspective_storage_modify(params):
529
    """Modify a storage unit.
530

531
    """
532
    (su_name, su_args, name, changes) = params
533
    return storage.GetStorage(su_name, *su_args).Modify(name, changes)
534

    
535
  @staticmethod
536
  def perspective_storage_execute(params):
537
    """Execute an operation on a storage unit.
538

539
    """
540
    (su_name, su_args, name, op) = params
541
    return storage.GetStorage(su_name, *su_args).Execute(name, op)
542

    
543
  # bridge  --------------------------
544

    
545
  @staticmethod
546
  def perspective_bridges_exist(params):
547
    """Check if all bridges given exist on this node.
548

549
    """
550
    bridges_list = params[0]
551
    return backend.BridgesExist(bridges_list)
552

    
553
  # instance  --------------------------
554

    
555
  @staticmethod
556
  def perspective_instance_os_add(params):
557
    """Install an OS on a given instance.
558

559
    """
560
    inst_s = params[0]
561
    inst = objects.Instance.FromDict(inst_s)
562
    reinstall = params[1]
563
    debug = params[2]
564
    return backend.InstanceOsAdd(inst, reinstall, debug)
565

    
566
  @staticmethod
567
  def perspective_instance_run_rename(params):
568
    """Runs the OS rename script for an instance.
569

570
    """
571
    inst_s, old_name, debug = params
572
    inst = objects.Instance.FromDict(inst_s)
573
    return backend.RunRenameInstance(inst, old_name, debug)
574

    
575
  @staticmethod
576
  def perspective_instance_shutdown(params):
577
    """Shutdown an instance.
578

579
    """
580
    instance = objects.Instance.FromDict(params[0])
581
    timeout = params[1]
582
    return backend.InstanceShutdown(instance, timeout)
583

    
584
  @staticmethod
585
  def perspective_instance_start(params):
586
    """Start an instance.
587

588
    """
589
    (instance_name, startup_paused) = params
590
    instance = objects.Instance.FromDict(instance_name)
591
    return backend.StartInstance(instance, startup_paused)
592

    
593
  @staticmethod
594
  def perspective_migration_info(params):
595
    """Gather information about an instance to be migrated.
596

597
    """
598
    instance = objects.Instance.FromDict(params[0])
599
    return backend.MigrationInfo(instance)
600

    
601
  @staticmethod
602
  def perspective_accept_instance(params):
603
    """Prepare the node to accept an instance.
604

605
    """
606
    instance, info, target = params
607
    instance = objects.Instance.FromDict(instance)
608
    return backend.AcceptInstance(instance, info, target)
609

    
610
  @staticmethod
611
  def perspective_instance_finalize_migration_dst(params):
612
    """Finalize the instance migration on the destination node.
613

614
    """
615
    instance, info, success = params
616
    instance = objects.Instance.FromDict(instance)
617
    return backend.FinalizeMigrationDst(instance, info, success)
618

    
619
  @staticmethod
620
  def perspective_instance_migrate(params):
621
    """Migrates an instance.
622

623
    """
624
    instance, target, live = params
625
    instance = objects.Instance.FromDict(instance)
626
    return backend.MigrateInstance(instance, target, live)
627

    
628
  @staticmethod
629
  def perspective_instance_finalize_migration_src(params):
630
    """Finalize the instance migration on the source node.
631

632
    """
633
    instance, success, live = params
634
    instance = objects.Instance.FromDict(instance)
635
    return backend.FinalizeMigrationSource(instance, success, live)
636

    
637
  @staticmethod
638
  def perspective_instance_get_migration_status(params):
639
    """Reports migration status.
640

641
    """
642
    instance = objects.Instance.FromDict(params[0])
643
    return backend.GetMigrationStatus(instance).ToDict()
644

    
645
  @staticmethod
646
  def perspective_instance_reboot(params):
647
    """Reboot an instance.
648

649
    """
650
    instance = objects.Instance.FromDict(params[0])
651
    reboot_type = params[1]
652
    shutdown_timeout = params[2]
653
    return backend.InstanceReboot(instance, reboot_type, shutdown_timeout)
654

    
655
  @staticmethod
656
  def perspective_instance_balloon_memory(params):
657
    """Modify instance runtime memory.
658

659
    """
660
    instance_dict, memory = params
661
    instance = objects.Instance.FromDict(instance_dict)
662
    return backend.InstanceBalloonMemory(instance, memory)
663

    
664
  @staticmethod
665
  def perspective_instance_info(params):
666
    """Query instance information.
667

668
    """
669
    return backend.GetInstanceInfo(params[0], params[1])
670

    
671
  @staticmethod
672
  def perspective_instance_migratable(params):
673
    """Query whether the specified instance can be migrated.
674

675
    """
676
    instance = objects.Instance.FromDict(params[0])
677
    return backend.GetInstanceMigratable(instance)
678

    
679
  @staticmethod
680
  def perspective_all_instances_info(params):
681
    """Query information about all instances.
682

683
    """
684
    return backend.GetAllInstancesInfo(params[0])
685

    
686
  @staticmethod
687
  def perspective_instance_list(params):
688
    """Query the list of running instances.
689

690
    """
691
    return backend.GetInstanceList(params[0])
692

    
693
  # node --------------------------
694

    
695
  @staticmethod
696
  def perspective_node_has_ip_address(params):
697
    """Checks if a node has the given ip address.
698

699
    """
700
    return netutils.IPAddress.Own(params[0])
701

    
702
  @staticmethod
703
  def perspective_node_info(params):
704
    """Query node information.
705

706
    """
707
    (vg_names, hv_names, excl_stor) = params
708
    return backend.GetNodeInfo(vg_names, hv_names, excl_stor)
709

    
710
  @staticmethod
711
  def perspective_etc_hosts_modify(params):
712
    """Modify a node entry in /etc/hosts.
713

714
    """
715
    backend.EtcHostsModify(params[0], params[1], params[2])
716

    
717
    return True
718

    
719
  @staticmethod
720
  def perspective_node_verify(params):
721
    """Run a verify sequence on this node.
722

723
    """
724
    return backend.VerifyNode(params[0], params[1])
725

    
726
  @classmethod
727
  def perspective_node_verify_light(cls, params):
728
    """Run a light verify sequence on this node.
729

730
    """
731
    # So far it's the same as the normal node_verify
732
    return cls.perspective_node_verify(params)
733

    
734
  @staticmethod
735
  def perspective_node_start_master_daemons(params):
736
    """Start the master daemons on this node.
737

738
    """
739
    return backend.StartMasterDaemons(params[0])
740

    
741
  @staticmethod
742
  def perspective_node_activate_master_ip(params):
743
    """Activate the master IP on this node.
744

745
    """
746
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
747
    return backend.ActivateMasterIp(master_params, params[1])
748

    
749
  @staticmethod
750
  def perspective_node_deactivate_master_ip(params):
751
    """Deactivate the master IP on this node.
752

753
    """
754
    master_params = objects.MasterNetworkParameters.FromDict(params[0])
755
    return backend.DeactivateMasterIp(master_params, params[1])
756

    
757
  @staticmethod
758
  def perspective_node_stop_master(params):
759
    """Stops master daemons on this node.
760

761
    """
762
    return backend.StopMasterDaemons()
763

    
764
  @staticmethod
765
  def perspective_node_change_master_netmask(params):
766
    """Change the master IP netmask.
767

768
    """
769
    return backend.ChangeMasterNetmask(params[0], params[1], params[2],
770
                                       params[3])
771

    
772
  @staticmethod
773
  def perspective_node_leave_cluster(params):
774
    """Cleanup after leaving a cluster.
775

776
    """
777
    return backend.LeaveCluster(params[0])
778

    
779
  @staticmethod
780
  def perspective_node_volumes(params):
781
    """Query the list of all logical volume groups.
782

783
    """
784
    return backend.NodeVolumes()
785

    
786
  @staticmethod
787
  def perspective_node_demote_from_mc(params):
788
    """Demote a node from the master candidate role.
789

790
    """
791
    return backend.DemoteFromMC()
792

    
793
  @staticmethod
794
  def perspective_node_powercycle(params):
795
    """Tries to powercycle the nod.
796

797
    """
798
    hypervisor_type = params[0]
799
    return backend.PowercycleNode(hypervisor_type)
800

    
801
  # cluster --------------------------
802

    
803
  @staticmethod
804
  def perspective_version(params):
805
    """Query version information.
806

807
    """
808
    return constants.PROTOCOL_VERSION
809

    
810
  @staticmethod
811
  def perspective_upload_file(params):
812
    """Upload a file.
813

814
    Note that the backend implementation imposes strict rules on which
815
    files are accepted.
816

817
    """
818
    return backend.UploadFile(*(params[0]))
819

    
820
  @staticmethod
821
  def perspective_master_info(params):
822
    """Query master information.
823

824
    """
825
    return backend.GetMasterInfo()
826

    
827
  @staticmethod
828
  def perspective_run_oob(params):
829
    """Runs oob on node.
830

831
    """
832
    output = backend.RunOob(params[0], params[1], params[2], params[3])
833
    if output:
834
      result = serializer.LoadJson(output)
835
    else:
836
      result = None
837
    return result
838

    
839
  @staticmethod
840
  def perspective_restricted_command(params):
841
    """Runs a restricted command.
842

843
    """
844
    (cmd, ) = params
845

    
846
    return backend.RunRestrictedCmd(cmd)
847

    
848
  @staticmethod
849
  def perspective_write_ssconf_files(params):
850
    """Write ssconf files.
851

852
    """
853
    (values,) = params
854
    return ssconf.WriteSsconfFiles(values)
855

    
856
  @staticmethod
857
  def perspective_get_watcher_pause(params):
858
    """Get watcher pause end.
859

860
    """
861
    return utils.ReadWatcherPauseFile(pathutils.WATCHER_PAUSEFILE)
862

    
863
  @staticmethod
864
  def perspective_set_watcher_pause(params):
865
    """Set watcher pause.
866

867
    """
868
    (until, ) = params
869
    return backend.SetWatcherPause(until)
870

    
871
  # os -----------------------
872

    
873
  @staticmethod
874
  def perspective_os_diagnose(params):
875
    """Query detailed information about existing OSes.
876

877
    """
878
    return backend.DiagnoseOS()
879

    
880
  @staticmethod
881
  def perspective_os_get(params):
882
    """Query information about a given OS.
883

884
    """
885
    name = params[0]
886
    os_obj = backend.OSFromDisk(name)
887
    return os_obj.ToDict()
888

    
889
  @staticmethod
890
  def perspective_os_validate(params):
891
    """Run a given OS' validation routine.
892

893
    """
894
    required, name, checks, params = params
895
    return backend.ValidateOS(required, name, checks, params)
896

    
897
  # extstorage -----------------------
898

    
899
  @staticmethod
900
  def perspective_extstorage_diagnose(params):
901
    """Query detailed information about existing extstorage providers.
902

903
    """
904
    return backend.DiagnoseExtStorage()
905

    
906
  # hooks -----------------------
907

    
908
  @staticmethod
909
  def perspective_hooks_runner(params):
910
    """Run hook scripts.
911

912
    """
913
    hpath, phase, env = params
914
    hr = backend.HooksRunner()
915
    return hr.RunHooks(hpath, phase, env)
916

    
917
  # iallocator -----------------
918

    
919
  @staticmethod
920
  def perspective_iallocator_runner(params):
921
    """Run an iallocator script.
922

923
    """
924
    name, idata = params
925
    iar = backend.IAllocatorRunner()
926
    return iar.Run(name, idata)
927

    
928
  # test -----------------------
929

    
930
  @staticmethod
931
  def perspective_test_delay(params):
932
    """Run test delay.
933

934
    """
935
    duration = params[0]
936
    status, rval = utils.TestDelay(duration)
937
    if not status:
938
      raise backend.RPCFail(rval)
939
    return rval
940

    
941
  # file storage ---------------
942

    
943
  @staticmethod
944
  def perspective_file_storage_dir_create(params):
945
    """Create the file storage directory.
946

947
    """
948
    file_storage_dir = params[0]
949
    return backend.CreateFileStorageDir(file_storage_dir)
950

    
951
  @staticmethod
952
  def perspective_file_storage_dir_remove(params):
953
    """Remove the file storage directory.
954

955
    """
956
    file_storage_dir = params[0]
957
    return backend.RemoveFileStorageDir(file_storage_dir)
958

    
959
  @staticmethod
960
  def perspective_file_storage_dir_rename(params):
961
    """Rename the file storage directory.
962

963
    """
964
    old_file_storage_dir = params[0]
965
    new_file_storage_dir = params[1]
966
    return backend.RenameFileStorageDir(old_file_storage_dir,
967
                                        new_file_storage_dir)
968

    
969
  # jobs ------------------------
970

    
971
  @staticmethod
972
  @_RequireJobQueueLock
973
  def perspective_jobqueue_update(params):
974
    """Update job queue.
975

976
    """
977
    (file_name, content) = params
978
    return backend.JobQueueUpdate(file_name, content)
979

    
980
  @staticmethod
981
  @_RequireJobQueueLock
982
  def perspective_jobqueue_purge(params):
983
    """Purge job queue.
984

985
    """
986
    return backend.JobQueuePurge()
987

    
988
  @staticmethod
989
  @_RequireJobQueueLock
990
  def perspective_jobqueue_rename(params):
991
    """Rename a job queue file.
992

993
    """
994
    # TODO: What if a file fails to rename?
995
    return [backend.JobQueueRename(old, new) for old, new in params[0]]
996

    
997
  @staticmethod
998
  @_RequireJobQueueLock
999
  def perspective_jobqueue_set_drain_flag(params):
1000
    """Set job queue's drain flag.
1001

1002
    """
1003
    (flag, ) = params
1004

    
1005
    return jstore.SetDrainFlag(flag)
1006

    
1007
  # hypervisor ---------------
1008

    
1009
  @staticmethod
1010
  def perspective_hypervisor_validate_params(params):
1011
    """Validate the hypervisor parameters.
1012

1013
    """
1014
    (hvname, hvparams) = params
1015
    return backend.ValidateHVParams(hvname, hvparams)
1016

    
1017
  # Crypto
1018

    
1019
  @staticmethod
1020
  def perspective_x509_cert_create(params):
1021
    """Creates a new X509 certificate for SSL/TLS.
1022

1023
    """
1024
    (validity, ) = params
1025
    return backend.CreateX509Certificate(validity)
1026

    
1027
  @staticmethod
1028
  def perspective_x509_cert_remove(params):
1029
    """Removes a X509 certificate.
1030

1031
    """
1032
    (name, ) = params
1033
    return backend.RemoveX509Certificate(name)
1034

    
1035
  # Import and export
1036

    
1037
  @staticmethod
1038
  def perspective_import_start(params):
1039
    """Starts an import daemon.
1040

1041
    """
1042
    (opts_s, instance, component, (dest, dest_args)) = params
1043

    
1044
    opts = objects.ImportExportOptions.FromDict(opts_s)
1045

    
1046
    return backend.StartImportExportDaemon(constants.IEM_IMPORT, opts,
1047
                                           None, None,
1048
                                           objects.Instance.FromDict(instance),
1049
                                           component, dest,
1050
                                           _DecodeImportExportIO(dest,
1051
                                                                 dest_args))
1052

    
1053
  @staticmethod
1054
  def perspective_export_start(params):
1055
    """Starts an export daemon.
1056

1057
    """
1058
    (opts_s, host, port, instance, component, (source, source_args)) = params
1059

    
1060
    opts = objects.ImportExportOptions.FromDict(opts_s)
1061

    
1062
    return backend.StartImportExportDaemon(constants.IEM_EXPORT, opts,
1063
                                           host, port,
1064
                                           objects.Instance.FromDict(instance),
1065
                                           component, source,
1066
                                           _DecodeImportExportIO(source,
1067
                                                                 source_args))
1068

    
1069
  @staticmethod
1070
  def perspective_impexp_status(params):
1071
    """Retrieves the status of an import or export daemon.
1072

1073
    """
1074
    return backend.GetImportExportStatus(params[0])
1075

    
1076
  @staticmethod
1077
  def perspective_impexp_abort(params):
1078
    """Aborts an import or export.
1079

1080
    """
1081
    return backend.AbortImportExport(params[0])
1082

    
1083
  @staticmethod
1084
  def perspective_impexp_cleanup(params):
1085
    """Cleans up after an import or export.
1086

1087
    """
1088
    return backend.CleanupImportExport(params[0])
1089

    
1090

    
1091
def CheckNoded(_, args):
1092
  """Initial checks whether to run or exit with a failure.
1093

1094
  """
1095
  if args: # noded doesn't take any arguments
1096
    print >> sys.stderr, ("Usage: %s [-f] [-d] [-p port] [-b ADDRESS]" %
1097
                          sys.argv[0])
1098
    sys.exit(constants.EXIT_FAILURE)
1099
  try:
1100
    codecs.lookup("string-escape")
1101
  except LookupError:
1102
    print >> sys.stderr, ("Can't load the string-escape code which is part"
1103
                          " of the Python installation. Is your installation"
1104
                          " complete/correct? Aborting.")
1105
    sys.exit(constants.EXIT_FAILURE)
1106

    
1107

    
1108
def PrepNoded(options, _):
1109
  """Preparation node daemon function, executed with the PID file held.
1110

1111
  """
1112
  if options.mlock:
1113
    request_executor_class = MlockallRequestExecutor
1114
    try:
1115
      utils.Mlockall()
1116
    except errors.NoCtypesError:
1117
      logging.warning("Cannot set memory lock, ctypes module not found")
1118
      request_executor_class = http.server.HttpServerRequestExecutor
1119
  else:
1120
    request_executor_class = http.server.HttpServerRequestExecutor
1121

    
1122
  # Read SSL certificate
1123
  if options.ssl:
1124
    ssl_params = http.HttpSslParams(ssl_key_path=options.ssl_key,
1125
                                    ssl_cert_path=options.ssl_cert)
1126
  else:
1127
    ssl_params = None
1128

    
1129
  err = _PrepareQueueLock()
1130
  if err is not None:
1131
    # this might be some kind of file-system/permission error; while
1132
    # this breaks the job queue functionality, we shouldn't prevent
1133
    # startup of the whole node daemon because of this
1134
    logging.critical("Can't init/verify the queue, proceeding anyway: %s", err)
1135

    
1136
  handler = NodeRequestHandler()
1137

    
1138
  mainloop = daemon.Mainloop()
1139
  server = \
1140
    http.server.HttpServer(mainloop, options.bind_address, options.port,
1141
                           handler, ssl_params=ssl_params, ssl_verify_peer=True,
1142
                           request_executor_class=request_executor_class)
1143
  server.Start()
1144

    
1145
  return (mainloop, server)
1146

    
1147

    
1148
def ExecNoded(options, args, prep_data): # pylint: disable=W0613
1149
  """Main node daemon function, executed with the PID file held.
1150

1151
  """
1152
  (mainloop, server) = prep_data
1153
  try:
1154
    mainloop.Run()
1155
  finally:
1156
    server.Stop()
1157

    
1158

    
1159
def Main():
1160
  """Main function for the node daemon.
1161

1162
  """
1163
  parser = OptionParser(description="Ganeti node daemon",
1164
                        usage="%prog [-f] [-d] [-p port] [-b ADDRESS]",
1165
                        version="%%prog (ganeti) %s" %
1166
                        constants.RELEASE_VERSION)
1167
  parser.add_option("--no-mlock", dest="mlock",
1168
                    help="Do not mlock the node memory in ram",
1169
                    default=True, action="store_false")
1170

    
1171
  daemon.GenericMain(constants.NODED, parser, CheckNoded, PrepNoded, ExecNoded,
1172
                     default_ssl_cert=pathutils.NODED_CERT_FILE,
1173
                     default_ssl_key=pathutils.NODED_CERT_FILE,
1174
                     console_logging=True)