export: add meaningful exit code
[ganeti-local] / scripts / gnt-backup
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   fin_resu, dlist = SubmitOpCode(op)
78   if not isinstance(dlist, list):
79     ToStderr("Cannot parse execution results")
80     return 1
81   tot_dsk = len(dlist)
82   # TODO: handle diskless instances
83   if dlist.count(False) == 0:
84     # all OK
85     rcode = 0
86   elif dlist.count(True) == 0:
87     ToStderr("Error: No disks were backed up successfully."
88              " The export doesn't have any valid data,"
89              " it is recommended to retry the operation.")
90     rcode = 1
91   else:
92     ToStderr("Partial export failure: %d disks backed up, %d disks failed.",
93              dlist.count(True), dlist.count(False))
94     rcode = 2
95   if not fin_resu:
96     rcode = 1
97   return rcode
98
99 def ImportInstance(opts, args):
100   """Add an instance to the cluster.
101
102   @param opts: the command line options selected by the user
103   @type args: list
104   @param args: should contain only one element, the new instance name
105   @rtype: int
106   @return: the desired exit code
107
108   """
109   instance = args[0]
110
111   (pnode, snode) = SplitNodeOption(opts.node)
112
113   hypervisor = None
114   hvparams = {}
115   if opts.hypervisor:
116     hypervisor, hvparams = opts.hypervisor
117
118   if opts.nics:
119     try:
120       nic_max = max(int(nidx[0])+1 for nidx in opts.nics)
121     except ValueError, err:
122       raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
123     nics = [{}] * nic_max
124     for nidx, ndict in opts.nics:
125       nidx = int(nidx)
126       nics[nidx] = ndict
127   elif opts.no_nics:
128     # no nics
129     nics = []
130   else:
131     # default of one nic, all auto
132     nics = [{}]
133
134   if opts.disk_template == constants.DT_DISKLESS:
135     if opts.disks or opts.sd_size is not None:
136       raise errors.OpPrereqError("Diskless instance but disk"
137                                  " information passed")
138     disks = []
139   else:
140     if not opts.disks and not opts.sd_size:
141       raise errors.OpPrereqError("No disk information specified")
142     if opts.disks and opts.sd_size is not None:
143       raise errors.OpPrereqError("Please use either the '--disk' or"
144                                  " '-s' option")
145     if opts.sd_size is not None:
146       opts.disks = [(0, {"size": opts.sd_size})]
147     try:
148       disk_max = max(int(didx[0])+1 for didx in opts.disks)
149     except ValueError, err:
150       raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
151     disks = [{}] * disk_max
152     for didx, ddict in opts.disks:
153       didx = int(didx)
154       if "size" not in ddict:
155         raise errors.OpPrereqError("Missing size for disk %d" % didx)
156       try:
157         ddict["size"] = utils.ParseUnit(ddict["size"])
158       except ValueError, err:
159         raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
160                                    (didx, err))
161       disks[didx] = ddict
162
163   utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
164   utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
165
166   op = opcodes.OpCreateInstance(instance_name=instance,
167                                 disk_template=opts.disk_template,
168                                 disks=disks,
169                                 nics=nics,
170                                 mode=constants.INSTANCE_IMPORT,
171                                 pnode=pnode, snode=snode,
172                                 ip_check=opts.ip_check,
173                                 start=False,
174                                 src_node=opts.src_node, src_path=opts.src_dir,
175                                 wait_for_sync=opts.wait_for_sync,
176                                 file_storage_dir=opts.file_storage_dir,
177                                 file_driver=opts.file_driver,
178                                 iallocator=opts.iallocator,
179                                 hypervisor=hypervisor,
180                                 hvparams=hvparams,
181                                 beparams=opts.beparams)
182
183   SubmitOpCode(op)
184   return 0
185
186
187 def RemoveExport(opts, args):
188   """Remove an export from the cluster.
189
190   @param opts: the command line options selected by the user
191   @type args: list
192   @param args: should contain only one element, the name of the
193       instance whose backup should be removed
194   @rtype: int
195   @return: the desired exit code
196
197   """
198   instance = args[0]
199   op = opcodes.OpRemoveExport(instance_name=args[0])
200
201   SubmitOpCode(op)
202   return 0
203
204
205 # this is defined separately due to readability only
206 import_opts = [
207   DEBUG_OPT,
208   make_option("-n", "--node", dest="node",
209               help="Target node and optional secondary node",
210               metavar="<pnode>[:<snode>]"),
211   keyval_option("-B", "--backend", dest="beparams",
212                 type="keyval", default={},
213                 help="Backend parameters"),
214   make_option("-t", "--disk-template", dest="disk_template",
215               help="Custom disk setup (diskless, file, plain, drbd)",
216               default=None, metavar="TEMPL"),
217   ikv_option("--disk", help="Disk information",
218              default=[], dest="disks",
219              action="append",
220              type="identkeyval"),
221   cli_option("-s", "--os-size", dest="sd_size", help="Disk size for a"
222              " single-disk configuration, when not using the --disk option,"
223              " in MiB unless a suffix is used",
224              default=None, type="unit", metavar="<size>"),
225   ikv_option("--net", help="NIC information",
226              default=[], dest="nics",
227              action="append",
228              type="identkeyval"),
229   make_option("--no-nics", default=False, action="store_true",
230               help="Do not create any network cards for the instance"),
231   make_option("--no-wait-for-sync", dest="wait_for_sync", default=True,
232               action="store_false", help="Don't wait for sync (DANGEROUS!)"),
233   make_option("--src-node", dest="src_node", help="Source node",
234               metavar="<node>"),
235   make_option("--src-dir", dest="src_dir", help="Source directory",
236               metavar="<dir>"),
237   make_option("--no-ip-check", dest="ip_check", default=True,
238               action="store_false", help="Don't check that the instance's IP"
239               " is alive"),
240   make_option("-I", "--iallocator", metavar="<NAME>",
241               help="Select nodes for the instance automatically using the"
242               " <NAME> iallocator plugin", default=None, type="string"),
243   make_option("--file-storage-dir", dest="file_storage_dir",
244               help="Relative path under default cluster-wide file storage dir"
245               " to store file-based disks", default=None,
246               metavar="<DIR>"),
247   make_option("--file-driver", dest="file_driver", help="Driver to use"
248               " for image files", default="loop", metavar="<DRIVER>"),
249   ikv_option("-H", "--hypervisor", dest="hypervisor",
250               help="Hypervisor and hypervisor options, in the format"
251               " hypervisor:option=value,option=value,...", default=None,
252               type="identkeyval"),
253   ]
254
255 commands = {
256   'list': (PrintExportList, ARGS_NONE,
257            [DEBUG_OPT,
258             make_option("--node", dest="nodes", default=[], action="append",
259                         help="List only backups stored on this node"
260                              " (can be used multiple times)"),
261             ],
262            "", "Lists instance exports available in the ganeti cluster"),
263   'export': (ExportInstance, ARGS_ONE,
264              [DEBUG_OPT, FORCE_OPT,
265               make_option("-n", "--node", dest="node", help="Target node",
266                           metavar="<node>"),
267               make_option("","--noshutdown", dest="shutdown",
268                           action="store_false", default=True,
269                           help="Don't shutdown the instance (unsafe)"), ],
270              "-n <target_node> [opts...] <name>",
271              "Exports an instance to an image"),
272   'import': (ImportInstance, ARGS_ONE, import_opts,
273              ("[...] -t disk-type -n node[:secondary-node]"
274               " <name>"),
275              "Imports an instance from an exported image"),
276   'remove': (RemoveExport, ARGS_ONE,
277              [DEBUG_OPT],
278              "<name>",
279              "Remove exports of named instance from the filesystem."),
280   }
281
282 if __name__ == '__main__':
283   sys.exit(GenericMain(commands))