gnt-group: Allow modify disk/hv state
[ganeti-local] / lib / client / gnt_group.py
1 #
2 #
3
4 # Copyright (C) 2010, 2011 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 """Node group related commands"""
22
23 # pylint: disable=W0401,W0614
24 # W0401: Wildcard import ganeti.cli
25 # W0614: Unused import %s from wildcard import (since we need cli)
26
27 from ganeti.cli import *
28 from ganeti import constants
29 from ganeti import opcodes
30 from ganeti import utils
31
32
33 #: default list of fields for L{ListGroups}
34 _LIST_DEF_FIELDS = ["name", "node_cnt", "pinst_cnt", "alloc_policy", "ndparams"]
35
36
37 _ENV_OVERRIDE = frozenset(["list"])
38
39
40 def AddGroup(opts, args):
41   """Add a node group to the cluster.
42
43   @param opts: the command line options selected by the user
44   @type args: list
45   @param args: a list of length 1 with the name of the group to create
46   @rtype: int
47   @return: the desired exit code
48
49   """
50   (group_name,) = args
51   diskparams = dict(opts.diskparams)
52   op = opcodes.OpGroupAdd(group_name=group_name, ndparams=opts.ndparams,
53                           alloc_policy=opts.alloc_policy,
54                           diskparams=diskparams)
55   SubmitOpCode(op, opts=opts)
56
57
58 def AssignNodes(opts, args):
59   """Assign nodes to a group.
60
61   @param opts: the command line options selected by the user
62   @type args: list
63   @param args: args[0]: group to assign nodes to; args[1:]: nodes to assign
64   @rtype: int
65   @return: the desired exit code
66
67   """
68   group_name = args[0]
69   node_names = args[1:]
70
71   op = opcodes.OpGroupAssignNodes(group_name=group_name, nodes=node_names,
72                                   force=opts.force)
73   SubmitOpCode(op, opts=opts)
74
75
76 def _FmtDict(data):
77   """Format dict data into command-line format.
78
79   @param data: The input dict to be formatted
80   @return: The formatted dict
81
82   """
83   if not data:
84     return "(empty)"
85
86   return utils.CommaJoin(["%s=%s" % (key, value)
87                           for key, value in data.items()])
88
89
90 def ListGroups(opts, args):
91   """List node groups and their properties.
92
93   @param opts: the command line options selected by the user
94   @type args: list
95   @param args: groups to list, or empty for all
96   @rtype: int
97   @return: the desired exit code
98
99   """
100   desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
101   fmtoverride = {
102     "node_list": (",".join, False),
103     "pinst_list": (",".join, False),
104     "ndparams": (_FmtDict, False),
105     }
106
107   return GenericList(constants.QR_GROUP, desired_fields, args, None,
108                      opts.separator, not opts.no_headers,
109                      format_override=fmtoverride, verbose=opts.verbose,
110                      force_filter=opts.force_filter)
111
112
113 def ListGroupFields(opts, args):
114   """List node fields.
115
116   @param opts: the command line options selected by the user
117   @type args: list
118   @param args: fields to list, or empty for all
119   @rtype: int
120   @return: the desired exit code
121
122   """
123   return GenericListFields(constants.QR_GROUP, args, opts.separator,
124                            not opts.no_headers)
125
126
127 def SetGroupParams(opts, args):
128   """Modifies a node group's parameters.
129
130   @param opts: the command line options selected by the user
131   @type args: list
132   @param args: should contain only one element, the node group name
133
134   @rtype: int
135   @return: the desired exit code
136
137   """
138   if (opts.ndparams is None and opts.alloc_policy is None and
139       not (opts.hv_state or opts.disk_state)):
140     ToStderr("Please give at least one of the parameters.")
141     return 1
142
143   if opts.disk_state:
144     disk_state = utils.FlatToDict(opts.disk_state)
145   else:
146     disk_state = {}
147
148   hv_state = dict(opts.hv_state)
149
150   diskparams = dict(opts.diskparams)
151   op = opcodes.OpGroupSetParams(group_name=args[0],
152                                 ndparams=opts.ndparams,
153                                 alloc_policy=opts.alloc_policy,
154                                 hv_state=hv_state,
155                                 disk_state=disk_state,
156                                 diskparams=diskparams)
157   result = SubmitOrSend(op, opts)
158
159   if result:
160     ToStdout("Modified node group %s", args[0])
161     for param, data in result:
162       ToStdout(" - %-5s -> %s", param, data)
163
164   return 0
165
166
167 def RemoveGroup(opts, args):
168   """Remove a node group from the cluster.
169
170   @param opts: the command line options selected by the user
171   @type args: list
172   @param args: a list of length 1 with the name of the group to remove
173   @rtype: int
174   @return: the desired exit code
175
176   """
177   (group_name,) = args
178   op = opcodes.OpGroupRemove(group_name=group_name)
179   SubmitOpCode(op, opts=opts)
180
181
182 def RenameGroup(opts, args):
183   """Rename a node group.
184
185   @param opts: the command line options selected by the user
186   @type args: list
187   @param args: a list of length 2, [old_name, new_name]
188   @rtype: int
189   @return: the desired exit code
190
191   """
192   group_name, new_name = args
193   op = opcodes.OpGroupRename(group_name=group_name, new_name=new_name)
194   SubmitOpCode(op, opts=opts)
195
196
197 def EvacuateGroup(opts, args):
198   """Evacuate a node group.
199
200   """
201   (group_name, ) = args
202
203   cl = GetClient()
204
205   op = opcodes.OpGroupEvacuate(group_name=group_name,
206                                iallocator=opts.iallocator,
207                                target_groups=opts.to,
208                                early_release=opts.early_release)
209   result = SubmitOpCode(op, cl=cl, opts=opts)
210
211   # Keep track of submitted jobs
212   jex = JobExecutor(cl=cl, opts=opts)
213
214   for (status, job_id) in result[constants.JOB_IDS_KEY]:
215     jex.AddJobId(None, status, job_id)
216
217   results = jex.GetResults()
218   bad_cnt = len([row for row in results if not row[0]])
219   if bad_cnt == 0:
220     ToStdout("All instances evacuated successfully.")
221     rcode = constants.EXIT_SUCCESS
222   else:
223     ToStdout("There were %s errors during the evacuation.", bad_cnt)
224     rcode = constants.EXIT_FAILURE
225
226   return rcode
227
228
229 commands = {
230   "add": (
231     AddGroup, ARGS_ONE_GROUP,
232     [DRY_RUN_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, DISK_PARAMS_OPT],
233     "<group_name>", "Add a new node group to the cluster"),
234   "assign-nodes": (
235     AssignNodes, ARGS_ONE_GROUP + ARGS_MANY_NODES, [DRY_RUN_OPT, FORCE_OPT],
236     "<group_name> <node>...", "Assign nodes to a group"),
237   "list": (
238     ListGroups, ARGS_MANY_GROUPS,
239     [NOHDR_OPT, SEP_OPT, FIELDS_OPT, VERBOSE_OPT, FORCE_FILTER_OPT],
240     "[<group_name>...]",
241     "Lists the node groups in the cluster. The available fields can be shown"
242     " using the \"list-fields\" command (see the man page for details)."
243     " The default list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
244   "list-fields": (
245     ListGroupFields, [ArgUnknown()], [NOHDR_OPT, SEP_OPT], "[fields...]",
246     "Lists all available fields for node groups"),
247   "modify": (
248     SetGroupParams, ARGS_ONE_GROUP,
249     [DRY_RUN_OPT, SUBMIT_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, HV_STATE_OPT,
250      DISK_STATE_OPT, DISK_PARAMS_OPT],
251     "<group_name>", "Alters the parameters of a node group"),
252   "remove": (
253     RemoveGroup, ARGS_ONE_GROUP, [DRY_RUN_OPT],
254     "[--dry-run] <group-name>",
255     "Remove an (empty) node group from the cluster"),
256   "rename": (
257     RenameGroup, [ArgGroup(min=2, max=2)], [DRY_RUN_OPT],
258     "[--dry-run] <group-name> <new-name>", "Rename a node group"),
259   "evacuate": (
260     EvacuateGroup, [ArgGroup(min=1, max=1)],
261     [TO_GROUP_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT],
262     "[-I <iallocator>] [--to <group>]",
263     "Evacuate all instances within a group"),
264   "list-tags": (
265     ListTags, ARGS_ONE_GROUP, [PRIORITY_OPT],
266     "<instance_name>", "List the tags of the given instance"),
267   "add-tags": (
268     AddTags, [ArgGroup(min=1, max=1), ArgUnknown()],
269     [TAG_SRC_OPT, PRIORITY_OPT],
270     "<instance_name> tag...", "Add tags to the given instance"),
271   "remove-tags": (
272     RemoveTags, [ArgGroup(min=1, max=1), ArgUnknown()],
273     [TAG_SRC_OPT, PRIORITY_OPT],
274     "<instance_name> tag...", "Remove tags from given instance"),
275   }
276
277
278 def Main():
279   return GenericMain(commands,
280                      override={"tag_type": constants.TAG_NODEGROUP},
281                      env_override=_ENV_OVERRIDE)