Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-backup @ 8b46606c

History | View | Annotate | Download (9.7 kB)

1
#!/usr/bin/python
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
# pylint: disable-msg=W0401,W0614
23
# W0401: Wildcard import ganeti.cli
24
# W0614: Unused import %s from wildcard import (since we need cli)
25

    
26
import sys
27
from optparse import make_option
28

    
29
from ganeti.cli import *
30
from ganeti import opcodes
31
from ganeti import constants
32
from ganeti import errors
33
from ganeti import utils
34

    
35

    
36
_VALUE_TRUE = "true"
37

    
38
def PrintExportList(opts, args):
39
  """Prints a list of all the exported system images.
40

    
41
  @param opts: the command line options selected by the user
42
  @type args: list
43
  @param args: should be an empty list
44
  @rtype: int
45
  @return: the desired exit code
46

    
47
  """
48
  exports = GetClient().QueryExports(opts.nodes, False)
49
  retcode = 0
50
  for node in exports:
51
    ToStdout("Node: %s", node)
52
    ToStdout("Exports:")
53
    if isinstance(exports[node], list):
54
      for instance_name in exports[node]:
55
        ToStdout("\t%s", instance_name)
56
    else:
57
      ToStdout("  Could not get exports list")
58
      retcode = 1
59
  return retcode
60

    
61

    
62
def ExportInstance(opts, args):
63
  """Export an instance to an image in the cluster.
64

    
65
  @param opts: the command line options selected by the user
66
  @type args: list
67
  @param args: should contain only one element, the name
68
      of the instance to be exported
69
  @rtype: int
70
  @return: the desired exit code
71

    
72
  """
73
  op = opcodes.OpExportInstance(instance_name=args[0],
74
                                target_node=opts.node,
75
                                shutdown=opts.shutdown)
76

    
77
  SubmitOpCode(op)
78

    
79

    
80
def ImportInstance(opts, args):
81
  """Add an instance to the cluster.
82

    
83
  @param opts: the command line options selected by the user
84
  @type args: list
85
  @param args: should contain only one element, the new instance name
86
  @rtype: int
87
  @return: the desired exit code
88

    
89
  """
90
  instance = args[0]
91

    
92
  (pnode, snode) = SplitNodeOption(opts.node)
93

    
94
  hypervisor = None
95
  hvparams = {}
96
  if opts.hypervisor:
97
    hypervisor, hvparams = opts.hypervisor
98

    
99
  if opts.nics:
100
    try:
101
      nic_max = max(int(nidx[0])+1 for nidx in opts.nics)
102
    except ValueError, err:
103
      raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
104
    nics = [{}] * nic_max
105
    for nidx, ndict in opts.nics.items():
106
      nidx = int(nidx)
107
      if not isinstance(ndict, dict):
108
        msg = "Invalid nic/%d value: expected dict, got %s" % (nidx, ndict)
109
        raise errors.OpPrereqError(msg)
110
      nics[nidx] = ndict
111
  elif opts.no_nics:
112
    # no nics
113
    nics = []
114
  else:
115
    # default of one nic, all auto
116
    nics = [{}]
117

    
118
  if opts.disk_template == constants.DT_DISKLESS:
119
    if opts.disks or opts.sd_size is not None:
120
      raise errors.OpPrereqError("Diskless instance but disk"
121
                                 " information passed")
122
    disks = []
123
  else:
124
    if not opts.disks and not opts.sd_size:
125
      raise errors.OpPrereqError("No disk information specified")
126
    if opts.disks and opts.sd_size is not None:
127
      raise errors.OpPrereqError("Please use either the '--disk' or"
128
                                 " '-s' option")
129
    if opts.sd_size is not None:
130
      opts.disks = [(0, {"size": opts.sd_size})]
131
    try:
132
      disk_max = max(int(didx[0])+1 for didx in opts.disks)
133
    except ValueError, err:
134
      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
135
    disks = [{}] * disk_max
136
    for didx, ddict in opts.disks:
137
      didx = int(didx)
138
      if not isinstance(ddict, dict):
139
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
140
        raise errors.OpPrereqError(msg)
141
      elif "size" not in ddict:
142
        raise errors.OpPrereqError("Missing size for disk %d" % didx)
143
      try:
144
        ddict["size"] = utils.ParseUnit(ddict["size"])
145
      except ValueError, err:
146
        raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
147
                                   (didx, err))
148
      disks[didx] = ddict
149

    
150
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
151
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
152

    
153
  op = opcodes.OpCreateInstance(instance_name=instance,
154
                                disk_template=opts.disk_template,
155
                                disks=disks,
156
                                nics=nics,
157
                                mode=constants.INSTANCE_IMPORT,
158
                                pnode=pnode, snode=snode,
159
                                ip_check=opts.ip_check,
160
                                start=False,
161
                                src_node=opts.src_node, src_path=opts.src_dir,
162
                                wait_for_sync=opts.wait_for_sync,
163
                                file_storage_dir=opts.file_storage_dir,
164
                                file_driver=opts.file_driver,
165
                                iallocator=opts.iallocator,
166
                                hypervisor=hypervisor,
167
                                hvparams=hvparams,
168
                                beparams=opts.beparams)
169

    
170
  SubmitOpCode(op)
171
  return 0
172

    
173

    
174
def RemoveExport(opts, args):
175
  """Remove an export from the cluster.
176

    
177
  @param opts: the command line options selected by the user
178
  @type args: list
179
  @param args: should contain only one element, the name of the
180
      instance whose backup should be removed
181
  @rtype: int
182
  @return: the desired exit code
183

    
184
  """
185
  instance = args[0]
186
  op = opcodes.OpRemoveExport(instance_name=args[0])
187

    
188
  SubmitOpCode(op)
189
  return 0
190

    
191

    
192
# this is defined separately due to readability only
193
import_opts = [
194
  DEBUG_OPT,
195
  make_option("-n", "--node", dest="node",
196
              help="Target node and optional secondary node",
197
              metavar="<pnode>[:<snode>]"),
198
  keyval_option("-B", "--backend", dest="beparams",
199
                type="keyval", default={},
200
                help="Backend parameters"),
201
  make_option("-t", "--disk-template", dest="disk_template",
202
              help="Custom disk setup (diskless, file, plain, drbd)",
203
              default=None, metavar="TEMPL"),
204
  ikv_option("--disk", help="Disk information",
205
             default=[], dest="disks",
206
             action="append",
207
             type="identkeyval"),
208
  cli_option("-s", "--os-size", dest="sd_size", help="Disk size for a"
209
             " single-disk configuration, when not using the --disk option,"
210
             " in MiB unless a suffix is used",
211
             default=None, type="unit", metavar="<size>"),
212
  ikv_option("--net", help="NIC information",
213
             default=[], dest="nics",
214
             action="append",
215
             type="identkeyval"),
216
  make_option("--no-nics", default=False, action="store_true",
217
              help="Do not create any network cards for the instance"),
218
  make_option("--no-wait-for-sync", dest="wait_for_sync", default=True,
219
              action="store_false", help="Don't wait for sync (DANGEROUS!)"),
220
  make_option("--src-node", dest="src_node", help="Source node",
221
              metavar="<node>"),
222
  make_option("--src-dir", dest="src_dir", help="Source directory",
223
              metavar="<dir>"),
224
  make_option("--no-ip-check", dest="ip_check", default=True,
225
              action="store_false", help="Don't check that the instance's IP"
226
              " is alive"),
227
  make_option("-I", "--iallocator", metavar="<NAME>",
228
              help="Select nodes for the instance automatically using the"
229
              " <NAME> iallocator plugin", default=None, type="string"),
230
  make_option("--file-storage-dir", dest="file_storage_dir",
231
              help="Relative path under default cluster-wide file storage dir"
232
              " to store file-based disks", default=None,
233
              metavar="<DIR>"),
234
  make_option("--file-driver", dest="file_driver", help="Driver to use"
235
              " for image files", default="loop", metavar="<DRIVER>"),
236
  ikv_option("-H", "--hypervisor", dest="hypervisor",
237
              help="Hypervisor and hypervisor options, in the format"
238
              " hypervisor:option=value,option=value,...", default=None,
239
              type="identkeyval"),
240
  ]
241

    
242
commands = {
243
  'list': (PrintExportList, ARGS_NONE,
244
           [DEBUG_OPT,
245
            make_option("--node", dest="nodes", default=[], action="append",
246
                        help="List only backups stored on this node"
247
                             " (can be used multiple times)"),
248
            ],
249
           "", "Lists instance exports available in the ganeti cluster"),
250
  'export': (ExportInstance, ARGS_ONE,
251
             [DEBUG_OPT, FORCE_OPT,
252
              make_option("-n", "--node", dest="node", help="Target node",
253
                          metavar="<node>"),
254
              make_option("","--noshutdown", dest="shutdown",
255
                          action="store_false", default=True,
256
                          help="Don't shutdown the instance (unsafe)"), ],
257
             "-n <target_node> [opts...] <name>",
258
             "Exports an instance to an image"),
259
  'import': (ImportInstance, ARGS_ONE, import_opts,
260
             ("[...] -t disk-type -n node[:secondary-node]"
261
              " <name>"),
262
             "Imports an instance from an exported image"),
263
  'remove': (RemoveExport, ARGS_ONE,
264
             [DEBUG_OPT],
265
             "<name>",
266
             "Remove exports of named instance from the filesystem."),
267
  }
268

    
269
if __name__ == '__main__':
270
  sys.exit(GenericMain(commands))