4 # Copyright (C) 2010, 2011, 2012, 2013 Google Inc.
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.
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.
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
21 """Node group related commands"""
23 # pylint: disable=W0401,W0614
24 # W0401: Wildcard import ganeti.cli
25 # W0614: Unused import %s from wildcard import (since we need cli)
27 from cStringIO import StringIO
29 from ganeti.cli import *
30 from ganeti import constants
31 from ganeti import opcodes
32 from ganeti import utils
33 from ganeti import compat
36 #: default list of fields for L{ListGroups}
37 _LIST_DEF_FIELDS = ["name", "node_cnt", "pinst_cnt", "alloc_policy", "ndparams"]
39 _ENV_OVERRIDE = compat.UniqueFrozenset(["list"])
42 def AddGroup(opts, args):
43 """Add a node group to the cluster.
45 @param opts: the command line options selected by the user
47 @param args: a list of length 1 with the name of the group to create
49 @return: the desired exit code
52 ipolicy = CreateIPolicyFromOpts(
53 minmax_ispecs=opts.ipolicy_bounds_specs,
54 ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
55 ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
56 ipolicy_disk_templates=opts.ipolicy_disk_templates,
60 diskparams = dict(opts.diskparams)
63 disk_state = utils.FlatToDict(opts.disk_state)
66 hv_state = dict(opts.hv_state)
68 op = opcodes.OpGroupAdd(group_name=group_name, ndparams=opts.ndparams,
69 alloc_policy=opts.alloc_policy,
70 diskparams=diskparams, ipolicy=ipolicy,
72 disk_state=disk_state)
73 SubmitOrSend(op, opts)
76 def AssignNodes(opts, args):
77 """Assign nodes to a group.
79 @param opts: the command line options selected by the user
81 @param args: args[0]: group to assign nodes to; args[1:]: nodes to assign
83 @return: the desired exit code
89 op = opcodes.OpGroupAssignNodes(group_name=group_name, nodes=node_names,
91 SubmitOrSend(op, opts)
95 """Format dict data into command-line format.
97 @param data: The input dict to be formatted
98 @return: The formatted dict
104 return utils.CommaJoin(["%s=%s" % (key, value)
105 for key, value in data.items()])
108 def ListGroups(opts, args):
109 """List node groups and their properties.
111 @param opts: the command line options selected by the user
113 @param args: groups to list, or empty for all
115 @return: the desired exit code
118 desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
120 "node_list": (",".join, False),
121 "pinst_list": (",".join, False),
122 "ndparams": (_FmtDict, False),
125 cl = GetClient(query=True)
127 return GenericList(constants.QR_GROUP, desired_fields, args, None,
128 opts.separator, not opts.no_headers,
129 format_override=fmtoverride, verbose=opts.verbose,
130 force_filter=opts.force_filter, cl=cl)
133 def ListGroupFields(opts, args):
136 @param opts: the command line options selected by the user
138 @param args: fields to list, or empty for all
140 @return: the desired exit code
143 cl = GetClient(query=True)
145 return GenericListFields(constants.QR_GROUP, args, opts.separator,
146 not opts.no_headers, cl=cl)
149 def SetGroupParams(opts, args):
150 """Modifies a node group's parameters.
152 @param opts: the command line options selected by the user
154 @param args: should contain only one element, the node group name
157 @return: the desired exit code
160 allmods = [opts.ndparams, opts.alloc_policy, opts.diskparams, opts.hv_state,
161 opts.disk_state, opts.ipolicy_bounds_specs,
162 opts.ipolicy_vcpu_ratio, opts.ipolicy_spindle_ratio,
163 opts.diskparams, opts.ipolicy_disk_templates]
164 if allmods.count(None) == len(allmods):
165 ToStderr("Please give at least one of the parameters.")
169 disk_state = utils.FlatToDict(opts.disk_state)
173 hv_state = dict(opts.hv_state)
175 diskparams = dict(opts.diskparams)
177 # create ipolicy object
178 ipolicy = CreateIPolicyFromOpts(
179 minmax_ispecs=opts.ipolicy_bounds_specs,
180 ipolicy_disk_templates=opts.ipolicy_disk_templates,
181 ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
182 ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
184 allowed_values=[constants.VALUE_DEFAULT])
186 op = opcodes.OpGroupSetParams(group_name=args[0],
187 ndparams=opts.ndparams,
188 alloc_policy=opts.alloc_policy,
190 disk_state=disk_state,
191 diskparams=diskparams,
194 result = SubmitOrSend(op, opts)
197 ToStdout("Modified node group %s", args[0])
198 for param, data in result:
199 ToStdout(" - %-5s -> %s", param, data)
204 def RemoveGroup(opts, args):
205 """Remove a node group from the cluster.
207 @param opts: the command line options selected by the user
209 @param args: a list of length 1 with the name of the group to remove
211 @return: the desired exit code
215 op = opcodes.OpGroupRemove(group_name=group_name)
216 SubmitOrSend(op, opts)
219 def RenameGroup(opts, args):
220 """Rename a node group.
222 @param opts: the command line options selected by the user
224 @param args: a list of length 2, [old_name, new_name]
226 @return: the desired exit code
229 group_name, new_name = args
230 op = opcodes.OpGroupRename(group_name=group_name, new_name=new_name)
231 SubmitOrSend(op, opts)
234 def EvacuateGroup(opts, args):
235 """Evacuate a node group.
238 (group_name, ) = args
242 op = opcodes.OpGroupEvacuate(group_name=group_name,
243 iallocator=opts.iallocator,
244 target_groups=opts.to,
245 early_release=opts.early_release)
246 result = SubmitOrSend(op, opts, cl=cl)
248 # Keep track of submitted jobs
249 jex = JobExecutor(cl=cl, opts=opts)
251 for (status, job_id) in result[constants.JOB_IDS_KEY]:
252 jex.AddJobId(None, status, job_id)
254 results = jex.GetResults()
255 bad_cnt = len([row for row in results if not row[0]])
257 ToStdout("All instances evacuated successfully.")
258 rcode = constants.EXIT_SUCCESS
260 ToStdout("There were %s errors during the evacuation.", bad_cnt)
261 rcode = constants.EXIT_FAILURE
266 def _FormatGroupInfo(group):
267 (name, ndparams, custom_ndparams, diskparams, custom_diskparams,
268 ipolicy, custom_ipolicy) = group
270 ("Node group", name),
271 ("Node parameters", FormatParamsDictInfo(custom_ndparams, ndparams)),
272 ("Disk parameters", FormatParamsDictInfo(custom_diskparams, diskparams)),
273 ("Instance policy", FormatPolicyInfo(custom_ipolicy, ipolicy, False)),
277 def GroupInfo(_, args):
278 """Shows info about node group.
281 cl = GetClient(query=True)
282 selected_fields = ["name",
283 "ndparams", "custom_ndparams",
284 "diskparams", "custom_diskparams",
285 "ipolicy", "custom_ipolicy"]
286 result = cl.QueryGroups(names=args, fields=selected_fields,
290 _FormatGroupInfo(group) for group in result
294 def _GetCreateCommand(group):
295 (name, ipolicy) = group
297 buf.write("gnt-group add")
298 PrintIPolicyCommand(buf, ipolicy, True)
301 return buf.getvalue()
304 def ShowCreateCommand(opts, args):
305 """Shows the command that can be used to re-create a node group.
307 Currently it works only for ipolicy specs.
310 cl = GetClient(query=True)
311 selected_fields = ["name"]
312 if opts.include_defaults:
313 selected_fields += ["ipolicy"]
315 selected_fields += ["custom_ipolicy"]
316 result = cl.QueryGroups(names=args, fields=selected_fields,
320 ToStdout(_GetCreateCommand(group))
325 AddGroup, ARGS_ONE_GROUP,
326 [DRY_RUN_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, DISK_PARAMS_OPT,
327 HV_STATE_OPT, DISK_STATE_OPT, PRIORITY_OPT]
328 + SUBMIT_OPTS + INSTANCE_POLICY_OPTS,
329 "<group_name>", "Add a new node group to the cluster"),
331 AssignNodes, ARGS_ONE_GROUP + ARGS_MANY_NODES,
332 [DRY_RUN_OPT, FORCE_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
333 "<group_name> <node>...", "Assign nodes to a group"),
335 ListGroups, ARGS_MANY_GROUPS,
336 [NOHDR_OPT, SEP_OPT, FIELDS_OPT, VERBOSE_OPT, FORCE_FILTER_OPT],
338 "Lists the node groups in the cluster. The available fields can be shown"
339 " using the \"list-fields\" command (see the man page for details)."
340 " The default list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
342 ListGroupFields, [ArgUnknown()], [NOHDR_OPT, SEP_OPT], "[fields...]",
343 "Lists all available fields for node groups"),
345 SetGroupParams, ARGS_ONE_GROUP,
346 [DRY_RUN_OPT] + SUBMIT_OPTS + [ALLOC_POLICY_OPT, NODE_PARAMS_OPT,
347 HV_STATE_OPT, DISK_STATE_OPT, DISK_PARAMS_OPT, PRIORITY_OPT]
348 + INSTANCE_POLICY_OPTS,
349 "<group_name>", "Alters the parameters of a node group"),
351 RemoveGroup, ARGS_ONE_GROUP, [DRY_RUN_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
352 "[--dry-run] <group-name>",
353 "Remove an (empty) node group from the cluster"),
355 RenameGroup, [ArgGroup(min=2, max=2)],
356 [DRY_RUN_OPT] + SUBMIT_OPTS + [PRIORITY_OPT],
357 "[--dry-run] <group-name> <new-name>", "Rename a node group"),
359 EvacuateGroup, [ArgGroup(min=1, max=1)],
360 [TO_GROUP_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT] + SUBMIT_OPTS,
361 "[-I <iallocator>] [--to <group>]",
362 "Evacuate all instances within a group"),
364 ListTags, ARGS_ONE_GROUP, [],
365 "<group_name>", "List the tags of the given group"),
367 AddTags, [ArgGroup(min=1, max=1), ArgUnknown()],
368 [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
369 "<group_name> tag...", "Add tags to the given group"),
371 RemoveTags, [ArgGroup(min=1, max=1), ArgUnknown()],
372 [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
373 "<group_name> tag...", "Remove tags from the given group"),
375 GroupInfo, ARGS_MANY_GROUPS, [], "[<group_name>...]",
376 "Show group information"),
378 ShowCreateCommand, ARGS_MANY_GROUPS, [INCLUDEDEFAULTS_OPT],
379 "[--include-defaults] [<group_name>...]",
380 "Show the command line to re-create a group"),
385 return GenericMain(commands,
386 override={"tag_type": constants.TAG_NODEGROUP},
387 env_override=_ENV_OVERRIDE)