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,
59 diskparams = dict(opts.diskparams)
62 disk_state = utils.FlatToDict(opts.disk_state)
65 hv_state = dict(opts.hv_state)
67 op = opcodes.OpGroupAdd(group_name=group_name, ndparams=opts.ndparams,
68 alloc_policy=opts.alloc_policy,
69 diskparams=diskparams, ipolicy=ipolicy,
71 disk_state=disk_state)
72 SubmitOrSend(op, opts)
75 def AssignNodes(opts, args):
76 """Assign nodes to a group.
78 @param opts: the command line options selected by the user
80 @param args: args[0]: group to assign nodes to; args[1:]: nodes to assign
82 @return: the desired exit code
88 op = opcodes.OpGroupAssignNodes(group_name=group_name, nodes=node_names,
90 SubmitOrSend(op, opts)
94 """Format dict data into command-line format.
96 @param data: The input dict to be formatted
97 @return: The formatted dict
103 return utils.CommaJoin(["%s=%s" % (key, value)
104 for key, value in data.items()])
107 def ListGroups(opts, args):
108 """List node groups and their properties.
110 @param opts: the command line options selected by the user
112 @param args: groups to list, or empty for all
114 @return: the desired exit code
117 desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
119 "node_list": (",".join, False),
120 "pinst_list": (",".join, False),
121 "ndparams": (_FmtDict, False),
124 cl = GetClient(query=True)
126 return GenericList(constants.QR_GROUP, desired_fields, args, None,
127 opts.separator, not opts.no_headers,
128 format_override=fmtoverride, verbose=opts.verbose,
129 force_filter=opts.force_filter, cl=cl)
132 def ListGroupFields(opts, args):
135 @param opts: the command line options selected by the user
137 @param args: fields to list, or empty for all
139 @return: the desired exit code
142 cl = GetClient(query=True)
144 return GenericListFields(constants.QR_GROUP, args, opts.separator,
145 not opts.no_headers, cl=cl)
148 def SetGroupParams(opts, args):
149 """Modifies a node group's parameters.
151 @param opts: the command line options selected by the user
153 @param args: should contain only one element, the node group name
156 @return: the desired exit code
159 allmods = [opts.ndparams, opts.alloc_policy, opts.diskparams, opts.hv_state,
160 opts.disk_state, opts.ipolicy_bounds_specs,
161 opts.ipolicy_vcpu_ratio, opts.ipolicy_spindle_ratio,
163 if allmods.count(None) == len(allmods):
164 ToStderr("Please give at least one of the parameters.")
168 disk_state = utils.FlatToDict(opts.disk_state)
172 hv_state = dict(opts.hv_state)
174 diskparams = dict(opts.diskparams)
176 # create ipolicy object
177 ipolicy = CreateIPolicyFromOpts(
178 minmax_ispecs=opts.ipolicy_bounds_specs,
179 ipolicy_disk_templates=opts.ipolicy_disk_templates,
180 ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
181 ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
183 allowed_values=[constants.VALUE_DEFAULT])
185 op = opcodes.OpGroupSetParams(group_name=args[0],
186 ndparams=opts.ndparams,
187 alloc_policy=opts.alloc_policy,
189 disk_state=disk_state,
190 diskparams=diskparams,
193 result = SubmitOrSend(op, opts)
196 ToStdout("Modified node group %s", args[0])
197 for param, data in result:
198 ToStdout(" - %-5s -> %s", param, data)
203 def RemoveGroup(opts, args):
204 """Remove a node group from the cluster.
206 @param opts: the command line options selected by the user
208 @param args: a list of length 1 with the name of the group to remove
210 @return: the desired exit code
214 op = opcodes.OpGroupRemove(group_name=group_name)
215 SubmitOrSend(op, opts)
218 def RenameGroup(opts, args):
219 """Rename a node group.
221 @param opts: the command line options selected by the user
223 @param args: a list of length 2, [old_name, new_name]
225 @return: the desired exit code
228 group_name, new_name = args
229 op = opcodes.OpGroupRename(group_name=group_name, new_name=new_name)
230 SubmitOrSend(op, opts)
233 def EvacuateGroup(opts, args):
234 """Evacuate a node group.
237 (group_name, ) = args
241 op = opcodes.OpGroupEvacuate(group_name=group_name,
242 iallocator=opts.iallocator,
243 target_groups=opts.to,
244 early_release=opts.early_release)
245 result = SubmitOrSend(op, opts, cl=cl)
247 # Keep track of submitted jobs
248 jex = JobExecutor(cl=cl, opts=opts)
250 for (status, job_id) in result[constants.JOB_IDS_KEY]:
251 jex.AddJobId(None, status, job_id)
253 results = jex.GetResults()
254 bad_cnt = len([row for row in results if not row[0]])
256 ToStdout("All instances evacuated successfully.")
257 rcode = constants.EXIT_SUCCESS
259 ToStdout("There were %s errors during the evacuation.", bad_cnt)
260 rcode = constants.EXIT_FAILURE
265 def _FormatGroupInfo(group):
266 (name, ndparams, custom_ndparams, diskparams, custom_diskparams,
267 ipolicy, custom_ipolicy) = group
269 ("Node group", name),
270 ("Node parameters", FormatParamsDictInfo(custom_ndparams, ndparams)),
271 ("Disk parameters", FormatParamsDictInfo(custom_diskparams, diskparams)),
272 ("Instance policy", FormatPolicyInfo(custom_ipolicy, ipolicy, False)),
276 def GroupInfo(_, args):
277 """Shows info about node group.
280 cl = GetClient(query=True)
281 selected_fields = ["name",
282 "ndparams", "custom_ndparams",
283 "diskparams", "custom_diskparams",
284 "ipolicy", "custom_ipolicy"]
285 result = cl.QueryGroups(names=args, fields=selected_fields,
289 _FormatGroupInfo(group) for group in result
293 def _GetCreateCommand(group):
294 (name, ipolicy) = group
296 buf.write("gnt-group add")
297 PrintIPolicyCommand(buf, ipolicy, True)
300 return buf.getvalue()
303 def ShowCreateCommand(opts, args):
304 """Shows the command that can be used to re-create a node group.
306 Currently it works only for ipolicy specs.
309 cl = GetClient(query=True)
310 selected_fields = ["name"]
311 if opts.include_defaults:
312 selected_fields += ["ipolicy"]
314 selected_fields += ["custom_ipolicy"]
315 result = cl.QueryGroups(names=args, fields=selected_fields,
319 ToStdout(_GetCreateCommand(group))
324 AddGroup, ARGS_ONE_GROUP,
325 [DRY_RUN_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, DISK_PARAMS_OPT,
326 HV_STATE_OPT, DISK_STATE_OPT, PRIORITY_OPT,
327 SUBMIT_OPT] + INSTANCE_POLICY_OPTS,
328 "<group_name>", "Add a new node group to the cluster"),
330 AssignNodes, ARGS_ONE_GROUP + ARGS_MANY_NODES,
331 [DRY_RUN_OPT, FORCE_OPT, PRIORITY_OPT, SUBMIT_OPT],
332 "<group_name> <node>...", "Assign nodes to a group"),
334 ListGroups, ARGS_MANY_GROUPS,
335 [NOHDR_OPT, SEP_OPT, FIELDS_OPT, VERBOSE_OPT, FORCE_FILTER_OPT],
337 "Lists the node groups in the cluster. The available fields can be shown"
338 " using the \"list-fields\" command (see the man page for details)."
339 " The default list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
341 ListGroupFields, [ArgUnknown()], [NOHDR_OPT, SEP_OPT], "[fields...]",
342 "Lists all available fields for node groups"),
344 SetGroupParams, ARGS_ONE_GROUP,
345 [DRY_RUN_OPT, SUBMIT_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, HV_STATE_OPT,
346 DISK_STATE_OPT, DISK_PARAMS_OPT, PRIORITY_OPT] + INSTANCE_POLICY_OPTS,
347 "<group_name>", "Alters the parameters of a node group"),
349 RemoveGroup, ARGS_ONE_GROUP, [DRY_RUN_OPT, PRIORITY_OPT, SUBMIT_OPT],
350 "[--dry-run] <group-name>",
351 "Remove an (empty) node group from the cluster"),
353 RenameGroup, [ArgGroup(min=2, max=2)],
354 [DRY_RUN_OPT, SUBMIT_OPT, PRIORITY_OPT],
355 "[--dry-run] <group-name> <new-name>", "Rename a node group"),
357 EvacuateGroup, [ArgGroup(min=1, max=1)],
358 [TO_GROUP_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT, SUBMIT_OPT, PRIORITY_OPT],
359 "[-I <iallocator>] [--to <group>]",
360 "Evacuate all instances within a group"),
362 ListTags, ARGS_ONE_GROUP, [],
363 "<group_name>", "List the tags of the given group"),
365 AddTags, [ArgGroup(min=1, max=1), ArgUnknown()],
366 [TAG_SRC_OPT, PRIORITY_OPT, SUBMIT_OPT],
367 "<group_name> tag...", "Add tags to the given group"),
369 RemoveTags, [ArgGroup(min=1, max=1), ArgUnknown()],
370 [TAG_SRC_OPT, PRIORITY_OPT, SUBMIT_OPT],
371 "<group_name> tag...", "Remove tags from the given group"),
373 GroupInfo, ARGS_MANY_GROUPS, [], "[<group_name>...]",
374 "Show group information"),
376 ShowCreateCommand, ARGS_MANY_GROUPS, [INCLUDEDEFAULTS_OPT],
377 "[--include-defaults] [<group_name>...]",
378 "Show the command line to re-create a group"),
383 return GenericMain(commands,
384 override={"tag_type": constants.TAG_NODEGROUP},
385 env_override=_ENV_OVERRIDE)