4 # Copyright (C) 2010, 2011, 2012 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 ganeti.cli import *
28 from ganeti import constants
29 from ganeti import opcodes
30 from ganeti import utils
31 from ganeti import compat
32 from cStringIO import StringIO
35 #: default list of fields for L{ListGroups}
36 _LIST_DEF_FIELDS = ["name", "node_cnt", "pinst_cnt", "alloc_policy", "ndparams"]
38 _ENV_OVERRIDE = compat.UniqueFrozenset(["list"])
41 def AddGroup(opts, args):
42 """Add a node group to the cluster.
44 @param opts: the command line options selected by the user
46 @param args: a list of length 1 with the name of the group to create
48 @return: the desired exit code
51 ipolicy = CreateIPolicyFromOpts(
52 ispecs_mem_size=opts.ispecs_mem_size,
53 ispecs_cpu_count=opts.ispecs_cpu_count,
54 ispecs_disk_count=opts.ispecs_disk_count,
55 ispecs_disk_size=opts.ispecs_disk_size,
56 ispecs_nic_count=opts.ispecs_nic_count,
57 ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
58 ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
62 diskparams = dict(opts.diskparams)
65 disk_state = utils.FlatToDict(opts.disk_state)
68 hv_state = dict(opts.hv_state)
70 op = opcodes.OpGroupAdd(group_name=group_name, ndparams=opts.ndparams,
71 alloc_policy=opts.alloc_policy,
72 diskparams=diskparams, ipolicy=ipolicy,
74 disk_state=disk_state)
75 SubmitOrSend(op, opts)
78 def AssignNodes(opts, args):
79 """Assign nodes to a group.
81 @param opts: the command line options selected by the user
83 @param args: args[0]: group to assign nodes to; args[1:]: nodes to assign
85 @return: the desired exit code
91 op = opcodes.OpGroupAssignNodes(group_name=group_name, nodes=node_names,
93 SubmitOrSend(op, opts)
97 """Format dict data into command-line format.
99 @param data: The input dict to be formatted
100 @return: The formatted dict
106 return utils.CommaJoin(["%s=%s" % (key, value)
107 for key, value in data.items()])
110 def ListGroups(opts, args):
111 """List node groups and their properties.
113 @param opts: the command line options selected by the user
115 @param args: groups to list, or empty for all
117 @return: the desired exit code
120 desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
122 "node_list": (",".join, False),
123 "pinst_list": (",".join, False),
124 "ndparams": (_FmtDict, False),
127 cl = GetClient(query=True)
129 return GenericList(constants.QR_GROUP, desired_fields, args, None,
130 opts.separator, not opts.no_headers,
131 format_override=fmtoverride, verbose=opts.verbose,
132 force_filter=opts.force_filter, cl=cl)
135 def ListGroupFields(opts, args):
138 @param opts: the command line options selected by the user
140 @param args: fields to list, or empty for all
142 @return: the desired exit code
145 cl = GetClient(query=True)
147 return GenericListFields(constants.QR_GROUP, args, opts.separator,
148 not opts.no_headers, cl=cl)
151 def SetGroupParams(opts, args):
152 """Modifies a node group's parameters.
154 @param opts: the command line options selected by the user
156 @param args: should contain only one element, the node group name
159 @return: the desired exit code
162 allmods = [opts.ndparams, opts.alloc_policy, opts.diskparams, opts.hv_state,
163 opts.disk_state, opts.ispecs_mem_size, opts.ispecs_cpu_count,
164 opts.ispecs_disk_count, opts.ispecs_disk_size,
165 opts.ispecs_nic_count, opts.ipolicy_vcpu_ratio,
166 opts.ipolicy_spindle_ratio, opts.diskparams]
167 if allmods.count(None) == len(allmods):
168 ToStderr("Please give at least one of the parameters.")
172 disk_state = utils.FlatToDict(opts.disk_state)
176 hv_state = dict(opts.hv_state)
178 diskparams = dict(opts.diskparams)
180 # set the default values
182 opts.ispecs_mem_size,
183 opts.ispecs_cpu_count,
184 opts.ispecs_disk_count,
185 opts.ispecs_disk_size,
186 opts.ispecs_nic_count,
188 for ispec in to_ipolicy:
190 if isinstance(ispec[param], basestring):
191 if ispec[param].lower() == "default":
192 ispec[param] = constants.VALUE_DEFAULT
193 # create ipolicy object
194 ipolicy = CreateIPolicyFromOpts(
195 ispecs_mem_size=opts.ispecs_mem_size,
196 ispecs_cpu_count=opts.ispecs_cpu_count,
197 ispecs_disk_count=opts.ispecs_disk_count,
198 ispecs_disk_size=opts.ispecs_disk_size,
199 ispecs_nic_count=opts.ispecs_nic_count,
200 ipolicy_disk_templates=opts.ipolicy_disk_templates,
201 ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
202 ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
204 allowed_values=[constants.VALUE_DEFAULT])
206 op = opcodes.OpGroupSetParams(group_name=args[0],
207 ndparams=opts.ndparams,
208 alloc_policy=opts.alloc_policy,
210 disk_state=disk_state,
211 diskparams=diskparams,
214 result = SubmitOrSend(op, opts)
217 ToStdout("Modified node group %s", args[0])
218 for param, data in result:
219 ToStdout(" - %-5s -> %s", param, data)
224 def RemoveGroup(opts, args):
225 """Remove a node group from the cluster.
227 @param opts: the command line options selected by the user
229 @param args: a list of length 1 with the name of the group to remove
231 @return: the desired exit code
235 op = opcodes.OpGroupRemove(group_name=group_name)
236 SubmitOrSend(op, opts)
239 def RenameGroup(opts, args):
240 """Rename a node group.
242 @param opts: the command line options selected by the user
244 @param args: a list of length 2, [old_name, new_name]
246 @return: the desired exit code
249 group_name, new_name = args
250 op = opcodes.OpGroupRename(group_name=group_name, new_name=new_name)
251 SubmitOrSend(op, opts)
254 def EvacuateGroup(opts, args):
255 """Evacuate a node group.
258 (group_name, ) = args
262 op = opcodes.OpGroupEvacuate(group_name=group_name,
263 iallocator=opts.iallocator,
264 target_groups=opts.to,
265 early_release=opts.early_release)
266 result = SubmitOrSend(op, opts, cl=cl)
268 # Keep track of submitted jobs
269 jex = JobExecutor(cl=cl, opts=opts)
271 for (status, job_id) in result[constants.JOB_IDS_KEY]:
272 jex.AddJobId(None, status, job_id)
274 results = jex.GetResults()
275 bad_cnt = len([row for row in results if not row[0]])
277 ToStdout("All instances evacuated successfully.")
278 rcode = constants.EXIT_SUCCESS
280 ToStdout("There were %s errors during the evacuation.", bad_cnt)
281 rcode = constants.EXIT_FAILURE
286 def _FormatDict(custom, actual, level=2):
287 """Helper function to L{cli.FormatParameterDict}.
289 @param custom: The customized dict
290 @param actual: The fully filled dict
294 FormatParameterDict(buf, custom, actual, level=level)
295 return buf.getvalue().rstrip("\n")
298 def GroupInfo(_, args):
299 """Shows info about node group.
302 cl = GetClient(query=True)
303 selected_fields = ["name",
304 "ndparams", "custom_ndparams",
305 "diskparams", "custom_diskparams",
306 "ipolicy", "custom_ipolicy"]
307 result = cl.QueryGroups(names=args, fields=selected_fields,
311 ndparams, custom_ndparams,
312 diskparams, custom_diskparams,
313 ipolicy, custom_ipolicy) in result:
314 ToStdout("Node group: %s" % name)
315 ToStdout(" Node parameters:")
316 ToStdout(_FormatDict(custom_ndparams, ndparams))
317 ToStdout(" Disk parameters:")
318 ToStdout(_FormatDict(custom_diskparams, diskparams))
319 ToStdout(" Instance policy:")
320 ToStdout(_FormatDict(custom_ipolicy, ipolicy))
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_OPT] + 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_OPT],
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_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, HV_STATE_OPT,
347 DISK_STATE_OPT, DISK_PARAMS_OPT, PRIORITY_OPT] + INSTANCE_POLICY_OPTS,
348 "<group_name>", "Alters the parameters of a node group"),
350 RemoveGroup, ARGS_ONE_GROUP, [DRY_RUN_OPT, PRIORITY_OPT, SUBMIT_OPT],
351 "[--dry-run] <group-name>",
352 "Remove an (empty) node group from the cluster"),
354 RenameGroup, [ArgGroup(min=2, max=2)],
355 [DRY_RUN_OPT, SUBMIT_OPT, PRIORITY_OPT],
356 "[--dry-run] <group-name> <new-name>", "Rename a node group"),
358 EvacuateGroup, [ArgGroup(min=1, max=1)],
359 [TO_GROUP_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT, SUBMIT_OPT, PRIORITY_OPT],
360 "[-I <iallocator>] [--to <group>]",
361 "Evacuate all instances within a group"),
363 ListTags, ARGS_ONE_GROUP, [],
364 "<group_name>", "List the tags of the given group"),
366 AddTags, [ArgGroup(min=1, max=1), ArgUnknown()],
367 [TAG_SRC_OPT, PRIORITY_OPT, SUBMIT_OPT],
368 "<group_name> tag...", "Add tags to the given group"),
370 RemoveTags, [ArgGroup(min=1, max=1), ArgUnknown()],
371 [TAG_SRC_OPT, PRIORITY_OPT, SUBMIT_OPT],
372 "<group_name> tag...", "Remove tags from the given group"),
374 GroupInfo, ARGS_MANY_GROUPS, [], "<group_name>", "Show group information"),
379 return GenericMain(commands,
380 override={"tag_type": constants.TAG_NODEGROUP},
381 env_override=_ENV_OVERRIDE)