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