ganeti-noded 21.2 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/python
#

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


"""Ganeti node daemon"""

24
25
26
# functions in this module need to have a given name structure, so:
# pylint: disable-msg=C0103

Iustin Pop's avatar
Iustin Pop committed
27
28
29
import os
import sys
import traceback
Guido Trotter's avatar
Guido Trotter committed
30
import SocketServer
31
import errno
Iustin Pop's avatar
Iustin Pop committed
32
import logging
33
import signal
Iustin Pop's avatar
Iustin Pop committed
34
35
36
37
38
39
40

from optparse import OptionParser

from ganeti import backend
from ganeti import constants
from ganeti import objects
from ganeti import errors
41
from ganeti import jstore
42
from ganeti import daemon
43
from ganeti import http
44
from ganeti import utils
Iustin Pop's avatar
Iustin Pop committed
45

46
47
import ganeti.http.server

Iustin Pop's avatar
Iustin Pop committed
48

49
50
51
queue_lock = None


52
53
54
55
def _RequireJobQueueLock(fn):
  """Decorator for job queue manipulating functions.

  """
56
57
  QUEUE_LOCK_TIMEOUT = 10

58
59
  def wrapper(*args, **kwargs):
    # Locking in exclusive, blocking mode because there could be several
60
    # children running at the same time. Waiting up to 10 seconds.
61
    queue_lock.Exclusive(blocking=True, timeout=QUEUE_LOCK_TIMEOUT)
62
63
64
65
    try:
      return fn(*args, **kwargs)
    finally:
      queue_lock.Unlock()
66

67
68
69
  return wrapper


70
class NodeHttpServer(http.server.HttpServer):
71
72
73
74
75
  """The server implementation.

  This class holds all methods exposed over the RPC interface.

  """
76
  def __init__(self, *args, **kwargs):
77
    http.server.HttpServer.__init__(self, *args, **kwargs)
78
79
80
    self.noded_pid = os.getpid()

  def HandleRequest(self, req):
81
    """Handle a request.
Iustin Pop's avatar
Iustin Pop committed
82

83
    """
84
    if req.request_method.upper() != http.HTTP_PUT:
85
      raise http.HttpBadRequest()
86

87
    path = req.request_path
Iustin Pop's avatar
Iustin Pop committed
88
89
90
    if path.startswith("/"):
      path = path[1:]

91
92
    method = getattr(self, "perspective_%s" % path, None)
    if method is None:
93
      raise http.HttpNotFound()
Iustin Pop's avatar
Iustin Pop committed
94

Iustin Pop's avatar
Iustin Pop committed
95
    try:
96
97
98
99
100
101
      return method(req.request_body)
    except backend.RPCFail, err:
      # our custom failure exception; str(err) works fine if the
      # exception was constructed with a single argument, and in
      # this case, err.message == err.args[0] == str(err)
      return (False, str(err))
102
    except errors.QuitGanetiException, err:
103
      # Tell parent to quit
104
105
      logging.info("Shutting down the node daemon, arguments: %s",
                   str(err.args))
106
      os.kill(self.noded_pid, signal.SIGTERM)
107
108
109
110
111
112
      # And return the error's arguments, which must be already in
      # correct tuple format
      return err.args
    except:
      logging.exception("Error in RPC call")
      raise
Iustin Pop's avatar
Iustin Pop committed
113
114
115

  # the new block devices  --------------------------

116
117
118
119
120
  @staticmethod
  def perspective_blockdev_create(params):
    """Create a block device.

    """
121
    bdev_s, size, owner, on_primary, info = params
122
    bdev = objects.Disk.FromDict(bdev_s)
Iustin Pop's avatar
Iustin Pop committed
123
124
    if bdev is None:
      raise ValueError("can't unserialize data!")
125
    return backend.BlockdevCreate(bdev, size, owner, on_primary, info)
Iustin Pop's avatar
Iustin Pop committed
126

127
128
129
130
131
  @staticmethod
  def perspective_blockdev_remove(params):
    """Remove a block device.

    """
Iustin Pop's avatar
Iustin Pop committed
132
    bdev_s = params[0]
133
    bdev = objects.Disk.FromDict(bdev_s)
134
    return backend.BlockdevRemove(bdev)
Iustin Pop's avatar
Iustin Pop committed
135

Iustin Pop's avatar
Iustin Pop committed
136
137
138
139
140
141
  @staticmethod
  def perspective_blockdev_rename(params):
    """Remove a block device.

    """
    devlist = [(objects.Disk.FromDict(ds), uid) for ds, uid in params]
142
    return backend.BlockdevRename(devlist)
Iustin Pop's avatar
Iustin Pop committed
143

144
145
146
147
148
  @staticmethod
  def perspective_blockdev_assemble(params):
    """Assemble a block device.

    """
149
    bdev_s, owner, on_primary = params
150
    bdev = objects.Disk.FromDict(bdev_s)
Iustin Pop's avatar
Iustin Pop committed
151
152
    if bdev is None:
      raise ValueError("can't unserialize data!")
153
    return backend.BlockdevAssemble(bdev, owner, on_primary)
Iustin Pop's avatar
Iustin Pop committed
154

155
156
157
158
159
  @staticmethod
  def perspective_blockdev_shutdown(params):
    """Shutdown a block device.

    """
Iustin Pop's avatar
Iustin Pop committed
160
    bdev_s = params[0]
161
    bdev = objects.Disk.FromDict(bdev_s)
Iustin Pop's avatar
Iustin Pop committed
162
163
    if bdev is None:
      raise ValueError("can't unserialize data!")
164
    return backend.BlockdevShutdown(bdev)
Iustin Pop's avatar
Iustin Pop committed
165

166
  @staticmethod
167
  def perspective_blockdev_addchildren(params):
168
169
170
171
172
173
    """Add a child to a mirror device.

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

    """
Iustin Pop's avatar
Iustin Pop committed
174
    bdev_s, ndev_s = params
175
    bdev = objects.Disk.FromDict(bdev_s)
176
177
    ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
    if bdev is None or ndevs.count(None) > 0:
Iustin Pop's avatar
Iustin Pop committed
178
      raise ValueError("can't unserialize data!")
179
    return backend.BlockdevAddchildren(bdev, ndevs)
Iustin Pop's avatar
Iustin Pop committed
180

181
  @staticmethod
182
  def perspective_blockdev_removechildren(params):
183
184
185
186
187
188
    """Remove a child from a mirror device.

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

    """
Iustin Pop's avatar
Iustin Pop committed
189
    bdev_s, ndev_s = params
190
    bdev = objects.Disk.FromDict(bdev_s)
191
192
    ndevs = [objects.Disk.FromDict(disk_s) for disk_s in ndev_s]
    if bdev is None or ndevs.count(None) > 0:
Iustin Pop's avatar
Iustin Pop committed
193
      raise ValueError("can't unserialize data!")
194
    return backend.BlockdevRemovechildren(bdev, ndevs)
Iustin Pop's avatar
Iustin Pop committed
195

196
197
198
199
200
  @staticmethod
  def perspective_blockdev_getmirrorstatus(params):
    """Return the mirror status for a list of disks.

    """
201
    disks = [objects.Disk.FromDict(dsk_s)
Iustin Pop's avatar
Iustin Pop committed
202
            for dsk_s in params]
203
    return backend.BlockdevGetmirrorstatus(disks)
Iustin Pop's avatar
Iustin Pop committed
204

205
206
207
208
209
210
211
  @staticmethod
  def perspective_blockdev_find(params):
    """Expose the FindBlockDevice functionality for a disk.

    This will try to find but not activate a disk.

    """
212
    disk = objects.Disk.FromDict(params[0])
213
    return backend.BlockdevFind(disk)
Iustin Pop's avatar
Iustin Pop committed
214

215
216
217
218
219
220
221
222
223
  @staticmethod
  def perspective_blockdev_snapshot(params):
    """Create a snapshot device.

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

    """
224
    cfbd = objects.Disk.FromDict(params[0])
225
    return backend.BlockdevSnapshot(cfbd)
Iustin Pop's avatar
Iustin Pop committed
226

227
228
229
230
231
232
233
  @staticmethod
  def perspective_blockdev_grow(params):
    """Grow a stack of devices.

    """
    cfbd = objects.Disk.FromDict(params[0])
    amount = params[1]
234
    return backend.BlockdevGrow(cfbd, amount)
235

236
237
238
239
240
  @staticmethod
  def perspective_blockdev_close(params):
    """Closes the given block devices.

    """
241
    disks = [objects.Disk.FromDict(cf) for cf in params[1]]
242
    return backend.BlockdevClose(params[0], disks)
243

Iustin Pop's avatar
Iustin Pop committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
  # blockdev/drbd specific methods ----------

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

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

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

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

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

    """
    nodes_ip, disks, instance_name, multimaster = params
    disks = [objects.Disk.FromDict(cf) for cf in disks]
268
269
    return backend.DrbdAttachNet(nodes_ip, disks,
                                     instance_name, multimaster)
Iustin Pop's avatar
Iustin Pop committed
270
271
272
273
274
275
276
277
278
279
280
281
282

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

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

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

Iustin Pop's avatar
Iustin Pop committed
283
284
  # export/import  --------------------------

285
286
287
288
289
  @staticmethod
  def perspective_snapshot_export(params):
    """Export a given snapshot.

    """
290
    disk = objects.Disk.FromDict(params[0])
Iustin Pop's avatar
Iustin Pop committed
291
    dest_node = params[1]
292
    instance = objects.Instance.FromDict(params[2])
293
    cluster_name = params[3]
294
295
296
    dev_idx = params[4]
    return backend.ExportSnapshot(disk, dest_node, instance,
                                  cluster_name, dev_idx)
297
298
299
300

  @staticmethod
  def perspective_finalize_export(params):
    """Expose the finalize export functionality.
Iustin Pop's avatar
Iustin Pop committed
301

302
    """
303
304
    instance = objects.Instance.FromDict(params[0])
    snap_disks = [objects.Disk.FromDict(str_data)
Iustin Pop's avatar
Iustin Pop committed
305
306
307
                  for str_data in params[1]]
    return backend.FinalizeExport(instance, snap_disks)

308
309
310
311
312
313
314
315
316
  @staticmethod
  def perspective_export_info(params):
    """Query information about an existing export on this node.

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

    """
    path = params[0]
317
    return backend.ExportInfo(path)
Iustin Pop's avatar
Iustin Pop committed
318

319
320
321
322
323
324
325
326
327
  @staticmethod
  def perspective_export_list(params):
    """List the available exports on this node.

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

    """
Iustin Pop's avatar
Iustin Pop committed
328
329
    return backend.ListExports()

330
331
332
333
334
  @staticmethod
  def perspective_export_remove(params):
    """Remove an export.

    """
Iustin Pop's avatar
Iustin Pop committed
335
336
337
338
339
    export = params[0]
    return backend.RemoveExport(export)

  # volume  --------------------------

340
341
342
343
344
  @staticmethod
  def perspective_volume_list(params):
    """Query the list of logical volumes in a given volume group.

    """
Iustin Pop's avatar
Iustin Pop committed
345
    vgname = params[0]
346
    return True, backend.GetVolumeList(vgname)
Iustin Pop's avatar
Iustin Pop committed
347

348
349
350
351
352
  @staticmethod
  def perspective_vg_list(params):
    """Query the list of volume groups.

    """
Iustin Pop's avatar
Iustin Pop committed
353
354
355
356
    return backend.ListVolumeGroups()

  # bridge  --------------------------

357
358
359
360
361
  @staticmethod
  def perspective_bridges_exist(params):
    """Check if all bridges given exist on this node.

    """
Iustin Pop's avatar
Iustin Pop committed
362
363
364
365
366
    bridges_list = params[0]
    return backend.BridgesExist(bridges_list)

  # instance  --------------------------

367
368
369
370
371
  @staticmethod
  def perspective_instance_os_add(params):
    """Install an OS on a given instance.

    """
372
    inst_s = params[0]
373
    inst = objects.Instance.FromDict(inst_s)
374
375
    reinstall = params[1]
    return backend.InstanceOsAdd(inst, reinstall)
Iustin Pop's avatar
Iustin Pop committed
376

377
378
379
380
381
  @staticmethod
  def perspective_instance_run_rename(params):
    """Runs the OS rename script for an instance.

    """
382
    inst_s, old_name = params
383
    inst = objects.Instance.FromDict(inst_s)
384
    return backend.RunRenameInstance(inst, old_name)
385

386
387
388
389
390
  @staticmethod
  def perspective_instance_os_import(params):
    """Run the import function of an OS onto a given instance.

    """
391
    inst_s, src_node, src_images, cluster_name = params
392
    inst = objects.Instance.FromDict(inst_s)
393
394
    return backend.ImportOSIntoInstance(inst, src_node, src_images,
                                        cluster_name)
Iustin Pop's avatar
Iustin Pop committed
395

396
397
398
399
400
  @staticmethod
  def perspective_instance_shutdown(params):
    """Shutdown an instance.

    """
401
    instance = objects.Instance.FromDict(params[0])
402
    return backend.InstanceShutdown(instance)
Iustin Pop's avatar
Iustin Pop committed
403

404
405
406
407
408
  @staticmethod
  def perspective_instance_start(params):
    """Start an instance.

    """
409
    instance = objects.Instance.FromDict(params[0])
410
    return backend.StartInstance(instance)
Iustin Pop's avatar
Iustin Pop committed
411

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
  @staticmethod
  def perspective_migration_info(params):
    """Gather information about an instance to be migrated.

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

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

    """
    instance, info, target = params
    instance = objects.Instance.FromDict(instance)
    return backend.AcceptInstance(instance, info, target)

  @staticmethod
  def perspective_finalize_migration(params):
    """Finalize the instance migration.

    """
    instance, info, success = params
    instance = objects.Instance.FromDict(instance)
    return backend.FinalizeMigration(instance, info, success)

438
439
440
441
442
443
  @staticmethod
  def perspective_instance_migrate(params):
    """Migrates an instance.

    """
    instance, target, live = params
444
    instance = objects.Instance.FromDict(instance)
445
446
    return backend.MigrateInstance(instance, target, live)

447
448
449
450
451
452
453
  @staticmethod
  def perspective_instance_reboot(params):
    """Reboot an instance.

    """
    instance = objects.Instance.FromDict(params[0])
    reboot_type = params[1]
454
    return backend.InstanceReboot(instance, reboot_type)
455

456
457
458
459
460
  @staticmethod
  def perspective_instance_info(params):
    """Query instance information.

    """
Iustin Pop's avatar
Iustin Pop committed
461
    return backend.GetInstanceInfo(params[0], params[1])
Iustin Pop's avatar
Iustin Pop committed
462

463
464
465
466
467
468
469
470
  @staticmethod
  def perspective_instance_migratable(params):
    """Query whether the specified instance can be migrated.

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

471
472
473
474
475
  @staticmethod
  def perspective_all_instances_info(params):
    """Query information about all instances.

    """
476
    return backend.GetAllInstancesInfo(params[0])
Iustin Pop's avatar
Iustin Pop committed
477

478
479
480
481
482
  @staticmethod
  def perspective_instance_list(params):
    """Query the list of running instances.

    """
483
    return True, backend.GetInstanceList(params[0])
Iustin Pop's avatar
Iustin Pop committed
484
485
486

  # node --------------------------

487
488
489
490
491
  @staticmethod
  def perspective_node_tcp_ping(params):
    """Do a TcpPing on the remote node.

    """
492
493
    return utils.TcpPing(params[1], params[2], timeout=params[3],
                         live_port_needed=params[4], source=params[0])
494

495
496
497
498
499
  @staticmethod
  def perspective_node_has_ip_address(params):
    """Checks if a node has the given ip address.

    """
500
    return True, utils.OwnIpAddress(params[0])
501

502
503
504
505
506
  @staticmethod
  def perspective_node_info(params):
    """Query node information.

    """
507
508
    vgname, hypervisor_type = params
    return backend.GetNodeInfo(vgname, hypervisor_type)
Iustin Pop's avatar
Iustin Pop committed
509

510
511
512
513
514
  @staticmethod
  def perspective_node_add(params):
    """Complete the registration of this node in the cluster.

    """
Iustin Pop's avatar
Iustin Pop committed
515
516
517
    return backend.AddNode(params[0], params[1], params[2],
                           params[3], params[4], params[5])

518
519
520
521
522
  @staticmethod
  def perspective_node_verify(params):
    """Run a verify sequence on this node.

    """
523
    return backend.VerifyNode(params[0], params[1])
Iustin Pop's avatar
Iustin Pop committed
524

525
526
527
528
529
  @staticmethod
  def perspective_node_start_master(params):
    """Promote this node to master status.

    """
530
    return backend.StartMaster(params[0])
Iustin Pop's avatar
Iustin Pop committed
531

532
533
534
535
536
  @staticmethod
  def perspective_node_stop_master(params):
    """Demote this node from master status.

    """
537
    return backend.StopMaster(params[0])
Iustin Pop's avatar
Iustin Pop committed
538

539
540
541
542
543
  @staticmethod
  def perspective_node_leave_cluster(params):
    """Cleanup after leaving a cluster.

    """
Iustin Pop's avatar
Iustin Pop committed
544
545
    return backend.LeaveCluster()

546
547
548
549
550
  @staticmethod
  def perspective_node_volumes(params):
    """Query the list of all logical volume groups.

    """
551
552
    return backend.NodeVolumes()

553
554
555
556
557
558
559
560
  @staticmethod
  def perspective_node_demote_from_mc(params):
    """Demote a node from the master candidate role.

    """
    return backend.DemoteFromMC()


Iustin Pop's avatar
Iustin Pop committed
561
562
563
564
565
566
567
568
569
  @staticmethod
  def perspective_node_powercycle(params):
    """Tries to powercycle the nod.

    """
    hypervisor_type = params[0]
    return backend.PowercycleNode(hypervisor_type)


Iustin Pop's avatar
Iustin Pop committed
570
571
  # cluster --------------------------

572
573
574
575
576
  @staticmethod
  def perspective_version(params):
    """Query version information.

    """
577
    return True, constants.PROTOCOL_VERSION
Iustin Pop's avatar
Iustin Pop committed
578

579
580
581
582
583
584
585
586
  @staticmethod
  def perspective_upload_file(params):
    """Upload a file.

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

    """
Iustin Pop's avatar
Iustin Pop committed
587
588
    return backend.UploadFile(*params)

589
590
591
592
593
594
  @staticmethod
  def perspective_master_info(params):
    """Query master information.

    """
    return backend.GetMasterInfo()
Iustin Pop's avatar
Iustin Pop committed
595

596
597
598
599
600
  @staticmethod
  def perspective_write_ssconf_files(params):
    """Write ssconf files.

    """
601
602
    (values,) = params
    return backend.WriteSsconfFiles(values)
603

Iustin Pop's avatar
Iustin Pop committed
604
605
  # os -----------------------

606
607
608
609
610
  @staticmethod
  def perspective_os_diagnose(params):
    """Query detailed information about existing OSes.

    """
611
    return True, [os_obj.ToDict() for os_obj in backend.DiagnoseOS()]
Iustin Pop's avatar
Iustin Pop committed
612

613
614
615
616
617
  @staticmethod
  def perspective_os_get(params):
    """Query information about a given OS.

    """
Iustin Pop's avatar
Iustin Pop committed
618
619
    name = params[0]
    try:
620
      os_obj = backend.OSFromDisk(name)
Iustin Pop's avatar
Iustin Pop committed
621
    except errors.InvalidOS, err:
622
623
      os_obj = objects.OS.FromInvalidOS(err)
    return os_obj.ToDict()
Iustin Pop's avatar
Iustin Pop committed
624
625
626

  # hooks -----------------------

627
628
629
630
631
  @staticmethod
  def perspective_hooks_runner(params):
    """Run hook scripts.

    """
Iustin Pop's avatar
Iustin Pop committed
632
633
634
635
    hpath, phase, env = params
    hr = backend.HooksRunner()
    return hr.RunHooks(hpath, phase, env)

636
637
638
639
640
641
642
643
644
645
646
  # iallocator -----------------

  @staticmethod
  def perspective_iallocator_runner(params):
    """Run an iallocator script.

    """
    name, idata = params
    iar = backend.IAllocatorRunner()
    return iar.Run(name, idata)

647
648
649
650
651
652
653
654
655
656
  # test -----------------------

  @staticmethod
  def perspective_test_delay(params):
    """Run test delay.

    """
    duration = params[0]
    return utils.TestDelay(duration)

657
658
  # file storage ---------------

659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
  @staticmethod
  def perspective_file_storage_dir_create(params):
    """Create the file storage directory.

    """
    file_storage_dir = params[0]
    return backend.CreateFileStorageDir(file_storage_dir)

  @staticmethod
  def perspective_file_storage_dir_remove(params):
    """Remove the file storage directory.

    """
    file_storage_dir = params[0]
    return backend.RemoveFileStorageDir(file_storage_dir)

  @staticmethod
  def perspective_file_storage_dir_rename(params):
    """Rename the file storage directory.

    """
    old_file_storage_dir = params[0]
    new_file_storage_dir = params[1]
    return backend.RenameFileStorageDir(old_file_storage_dir,
                                        new_file_storage_dir)

685
686
  # jobs ------------------------

687
  @staticmethod
688
  @_RequireJobQueueLock
689
690
691
692
693
  def perspective_jobqueue_update(params):
    """Update job queue.

    """
    (file_name, content) = params
694
    return backend.JobQueueUpdate(file_name, content)
695
696

  @staticmethod
697
  @_RequireJobQueueLock
698
699
700
701
702
703
  def perspective_jobqueue_purge(params):
    """Purge job queue.

    """
    return backend.JobQueuePurge()

704
705
706
707
708
709
  @staticmethod
  @_RequireJobQueueLock
  def perspective_jobqueue_rename(params):
    """Rename a job queue file.

    """
710
711
    # TODO: What if a file fails to rename?
    return [backend.JobQueueRename(old, new) for old, new in params]
712

713
714
715
716
717
718
719
720
721
  @staticmethod
  def perspective_jobqueue_set_drain(params):
    """Set/unset the queue drain flag.

    """
    drain_flag = params[0]
    return backend.JobQueueSetDrainFlag(drain_flag)


722
723
724
725
726
727
728
729
730
731
  # hypervisor ---------------

  @staticmethod
  def perspective_hypervisor_validate_params(params):
    """Validate the hypervisor parameters.

    """
    (hvname, hvparams) = params
    return backend.ValidateHVParams(hvname, hvparams)

Iustin Pop's avatar
Iustin Pop committed
732
733
734
735

def ParseOptions():
  """Parse the command line options.

Iustin Pop's avatar
Iustin Pop committed
736
  @return: (options, args) as from OptionParser.parse_args()
Iustin Pop's avatar
Iustin Pop committed
737
738
739

  """
  parser = OptionParser(description="Ganeti node daemon",
740
                        usage="%prog [-f] [-d] [-b ADDRESS]",
Iustin Pop's avatar
Iustin Pop committed
741
742
743
744
745
746
747
748
749
                        version="%%prog (ganeti) %s" %
                        constants.RELEASE_VERSION)

  parser.add_option("-f", "--foreground", dest="fork",
                    help="Don't detach from the current terminal",
                    default=True, action="store_false")
  parser.add_option("-d", "--debug", dest="debug",
                    help="Enable some debug messages",
                    default=False, action="store_true")
750
751
752
753
  parser.add_option("-b", "--bind", dest="bind_address",
                    help="Bind address",
                    default="", metavar="ADDRESS")

Iustin Pop's avatar
Iustin Pop committed
754
755
756
757
758
  options, args = parser.parse_args()
  return options, args


def main():
759
760
761
  """Main function for the node daemon.

  """
762
763
  global queue_lock

Iustin Pop's avatar
Iustin Pop committed
764
  options, args = ParseOptions()
765
  utils.debug = options.debug
Iustin Pop's avatar
Iustin Pop committed
766
767
768
769

  if options.fork:
    utils.CloseFDs()

Iustin Pop's avatar
Iustin Pop committed
770
771
772
773
774
775
  for fname in (constants.SSL_CERT_FILE,):
    if not os.path.isfile(fname):
      print "config %s not there, will not run." % fname
      sys.exit(5)

  try:
Michael Hanselmann's avatar
Michael Hanselmann committed
776
    port = utils.GetNodeDaemonPort()
Iustin Pop's avatar
Iustin Pop committed
777
778
779
780
  except errors.ConfigurationError, err:
    print "Cluster configuration incomplete: '%s'" % str(err)
    sys.exit(5)

781
782
783
784
  dirs = [(val, constants.RUN_DIRS_MODE) for val in constants.SUB_RUN_DIRS]
  dirs.append((constants.LOG_OS_DIR, 0750))
  dirs.append((constants.LOCK_DIR, 1777))
  utils.EnsureDirs(dirs)
785

Iustin Pop's avatar
Iustin Pop committed
786
787
  # become a daemon
  if options.fork:
788
    utils.Daemonize(logfile=constants.LOG_NODESERVER)
Iustin Pop's avatar
Iustin Pop committed
789

790
  utils.WritePidFile(constants.NODED_PID)
791
  try:
Iustin Pop's avatar
Iustin Pop committed
792
793
    utils.SetupLogging(logfile=constants.LOG_NODESERVER, debug=options.debug,
                       stderr_logging=not options.fork)
794
    logging.info("ganeti node daemon startup")
795

796
797
798
799
    # Read SSL certificate
    ssl_params = http.HttpSslParams(ssl_key_path=constants.SSL_CERT_FILE,
                                    ssl_cert_path=constants.SSL_CERT_FILE)

800
801
    # Prepare job queue
    queue_lock = jstore.InitAndVerifyQueue(must_lock=False)
Iustin Pop's avatar
Iustin Pop committed
802

803
    mainloop = daemon.Mainloop()
804
    server = NodeHttpServer(mainloop, options.bind_address, port,
805
                            ssl_params=ssl_params, ssl_verify_peer=True)
806
807
808
809
810
    server.Start()
    try:
      mainloop.Run()
    finally:
      server.Stop()
811
  finally:
812
    utils.RemovePidFile(constants.NODED_PID)
813

Iustin Pop's avatar
Iustin Pop committed
814

815
if __name__ == '__main__':
Iustin Pop's avatar
Iustin Pop committed
816
  main()