Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_group.py @ fb644e77

History | View | Annotate | Download (10.3 kB)

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 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
  for key in ipolicy.keys():
59
    utils.ForceDictType(ipolicy[key], constants.ISPECS_PARAMETER_TYPES)
60

    
61
  (group_name,) = args
62
  diskparams = dict(opts.diskparams)
63
  op = opcodes.OpGroupAdd(group_name=group_name, ndparams=opts.ndparams,
64
                          alloc_policy=opts.alloc_policy,
65
                          diskparams=diskparams, ipolicy=ipolicy)
66
  SubmitOpCode(op, opts=opts)
67

    
68

    
69
def AssignNodes(opts, args):
70
  """Assign nodes to a group.
71

72
  @param opts: the command line options selected by the user
73
  @type args: list
74
  @param args: args[0]: group to assign nodes to; args[1:]: nodes to assign
75
  @rtype: int
76
  @return: the desired exit code
77

78
  """
79
  group_name = args[0]
80
  node_names = args[1:]
81

    
82
  op = opcodes.OpGroupAssignNodes(group_name=group_name, nodes=node_names,
83
                                  force=opts.force)
84
  SubmitOpCode(op, opts=opts)
85

    
86

    
87
def _FmtDict(data):
88
  """Format dict data into command-line format.
89

90
  @param data: The input dict to be formatted
91
  @return: The formatted dict
92

93
  """
94
  if not data:
95
    return "(empty)"
96

    
97
  return utils.CommaJoin(["%s=%s" % (key, value)
98
                          for key, value in data.items()])
99

    
100

    
101
def ListGroups(opts, args):
102
  """List node groups and their properties.
103

104
  @param opts: the command line options selected by the user
105
  @type args: list
106
  @param args: groups to list, or empty for all
107
  @rtype: int
108
  @return: the desired exit code
109

110
  """
111
  desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
112
  fmtoverride = {
113
    "node_list": (",".join, False),
114
    "pinst_list": (",".join, False),
115
    "ndparams": (_FmtDict, False),
116
    }
117

    
118
  return GenericList(constants.QR_GROUP, desired_fields, args, None,
119
                     opts.separator, not opts.no_headers,
120
                     format_override=fmtoverride, verbose=opts.verbose,
121
                     force_filter=opts.force_filter)
122

    
123

    
124
def ListGroupFields(opts, args):
125
  """List node fields.
126

127
  @param opts: the command line options selected by the user
128
  @type args: list
129
  @param args: fields to list, or empty for all
130
  @rtype: int
131
  @return: the desired exit code
132

133
  """
134
  return GenericListFields(constants.QR_GROUP, args, opts.separator,
135
                           not opts.no_headers)
136

    
137

    
138
def SetGroupParams(opts, args):
139
  """Modifies a node group's parameters.
140

141
  @param opts: the command line options selected by the user
142
  @type args: list
143
  @param args: should contain only one element, the node group name
144

145
  @rtype: int
146
  @return: the desired exit code
147

148
  """
149
  allmods = [opts.ndparams, opts.alloc_policy, opts.diskparams, opts.hv_state,
150
             opts.disk_state, opts.ispecs_mem_size, opts.ispecs_cpu_count,
151
             opts.ispecs_disk_count, opts.ispecs_disk_size,
152
             opts.ispecs_nic_count, opts.diskparams]
153
  if allmods.count(None) == len(allmods):
154
    ToStderr("Please give at least one of the parameters.")
155
    return 1
156

    
157
  if opts.disk_state:
158
    disk_state = utils.FlatToDict(opts.disk_state)
159
  else:
160
    disk_state = {}
161

    
162
  hv_state = dict(opts.hv_state)
163

    
164
  diskparams = dict(opts.diskparams)
165

    
166
  # set the default values
167
  to_ipolicy = [
168
    opts.ispecs_mem_size,
169
    opts.ispecs_cpu_count,
170
    opts.ispecs_disk_count,
171
    opts.ispecs_disk_size,
172
    opts.ispecs_nic_count,
173
    ]
174
  for ispec in to_ipolicy:
175
    for param in ispec:
176
      if isinstance(ispec[param], basestring):
177
        if ispec[param].lower() == "default":
178
          ispec[param] = constants.VALUE_DEFAULT
179
  # create ipolicy object
180
  ipolicy = objects.CreateIPolicyFromOpts(\
181
    ispecs_mem_size=opts.ispecs_mem_size,
182
    ispecs_cpu_count=opts.ispecs_cpu_count,
183
    ispecs_disk_count=opts.ispecs_disk_count,
184
    ispecs_disk_size=opts.ispecs_disk_size,
185
    ispecs_nic_count=opts.ispecs_nic_count,
186
    group_ipolicy=True,
187
    allowed_values=[constants.VALUE_DEFAULT])
188
  for key in ipolicy.keys():
189
    utils.ForceDictType(ipolicy[key], constants.ISPECS_PARAMETER_TYPES,
190
                        allowed_values=[constants.VALUE_DEFAULT])
191

    
192
  op = opcodes.OpGroupSetParams(group_name=args[0],
193
                                ndparams=opts.ndparams,
194
                                alloc_policy=opts.alloc_policy,
195
                                hv_state=hv_state,
196
                                disk_state=disk_state,
197
                                diskparams=diskparams,
198
                                ipolicy=ipolicy)
199

    
200
  result = SubmitOrSend(op, opts)
201

    
202
  if result:
203
    ToStdout("Modified node group %s", args[0])
204
    for param, data in result:
205
      ToStdout(" - %-5s -> %s", param, data)
206

    
207
  return 0
208

    
209

    
210
def RemoveGroup(opts, args):
211
  """Remove a node group from the cluster.
212

213
  @param opts: the command line options selected by the user
214
  @type args: list
215
  @param args: a list of length 1 with the name of the group to remove
216
  @rtype: int
217
  @return: the desired exit code
218

219
  """
220
  (group_name,) = args
221
  op = opcodes.OpGroupRemove(group_name=group_name)
222
  SubmitOpCode(op, opts=opts)
223

    
224

    
225
def RenameGroup(opts, args):
226
  """Rename a node group.
227

228
  @param opts: the command line options selected by the user
229
  @type args: list
230
  @param args: a list of length 2, [old_name, new_name]
231
  @rtype: int
232
  @return: the desired exit code
233

234
  """
235
  group_name, new_name = args
236
  op = opcodes.OpGroupRename(group_name=group_name, new_name=new_name)
237
  SubmitOpCode(op, opts=opts)
238

    
239

    
240
def EvacuateGroup(opts, args):
241
  """Evacuate a node group.
242

243
  """
244
  (group_name, ) = args
245

    
246
  cl = GetClient()
247

    
248
  op = opcodes.OpGroupEvacuate(group_name=group_name,
249
                               iallocator=opts.iallocator,
250
                               target_groups=opts.to,
251
                               early_release=opts.early_release)
252
  result = SubmitOpCode(op, cl=cl, opts=opts)
253

    
254
  # Keep track of submitted jobs
255
  jex = JobExecutor(cl=cl, opts=opts)
256

    
257
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
258
    jex.AddJobId(None, status, job_id)
259

    
260
  results = jex.GetResults()
261
  bad_cnt = len([row for row in results if not row[0]])
262
  if bad_cnt == 0:
263
    ToStdout("All instances evacuated successfully.")
264
    rcode = constants.EXIT_SUCCESS
265
  else:
266
    ToStdout("There were %s errors during the evacuation.", bad_cnt)
267
    rcode = constants.EXIT_FAILURE
268

    
269
  return rcode
270

    
271
INSTANCE_POLICY_OPTS = [
272
  SPECS_CPU_COUNT_OPT,
273
  SPECS_DISK_COUNT_OPT,
274
  SPECS_DISK_SIZE_OPT,
275
  SPECS_MEM_SIZE_OPT,
276
  SPECS_NIC_COUNT_OPT,
277
  ]
278

    
279
commands = {
280
  "add": (
281
    AddGroup, ARGS_ONE_GROUP,
282
    [DRY_RUN_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, DISK_PARAMS_OPT] +
283
    INSTANCE_POLICY_OPTS,
284
    "<group_name>", "Add a new node group to the cluster"),
285
  "assign-nodes": (
286
    AssignNodes, ARGS_ONE_GROUP + ARGS_MANY_NODES, [DRY_RUN_OPT, FORCE_OPT],
287
    "<group_name> <node>...", "Assign nodes to a group"),
288
  "list": (
289
    ListGroups, ARGS_MANY_GROUPS,
290
    [NOHDR_OPT, SEP_OPT, FIELDS_OPT, VERBOSE_OPT, FORCE_FILTER_OPT],
291
    "[<group_name>...]",
292
    "Lists the node groups in the cluster. The available fields can be shown"
293
    " using the \"list-fields\" command (see the man page for details)."
294
    " The default list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
295
  "list-fields": (
296
    ListGroupFields, [ArgUnknown()], [NOHDR_OPT, SEP_OPT], "[fields...]",
297
    "Lists all available fields for node groups"),
298
  "modify": (
299
    SetGroupParams, ARGS_ONE_GROUP,
300
    [DRY_RUN_OPT, SUBMIT_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, HV_STATE_OPT,
301
     DISK_STATE_OPT, DISK_PARAMS_OPT] + INSTANCE_POLICY_OPTS,
302
    "<group_name>", "Alters the parameters of a node group"),
303
  "remove": (
304
    RemoveGroup, ARGS_ONE_GROUP, [DRY_RUN_OPT],
305
    "[--dry-run] <group-name>",
306
    "Remove an (empty) node group from the cluster"),
307
  "rename": (
308
    RenameGroup, [ArgGroup(min=2, max=2)], [DRY_RUN_OPT],
309
    "[--dry-run] <group-name> <new-name>", "Rename a node group"),
310
  "evacuate": (
311
    EvacuateGroup, [ArgGroup(min=1, max=1)],
312
    [TO_GROUP_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT],
313
    "[-I <iallocator>] [--to <group>]",
314
    "Evacuate all instances within a group"),
315
  "list-tags": (
316
    ListTags, ARGS_ONE_GROUP, [PRIORITY_OPT],
317
    "<instance_name>", "List the tags of the given instance"),
318
  "add-tags": (
319
    AddTags, [ArgGroup(min=1, max=1), ArgUnknown()],
320
    [TAG_SRC_OPT, PRIORITY_OPT],
321
    "<instance_name> tag...", "Add tags to the given instance"),
322
  "remove-tags": (
323
    RemoveTags, [ArgGroup(min=1, max=1), ArgUnknown()],
324
    [TAG_SRC_OPT, PRIORITY_OPT],
325
    "<instance_name> tag...", "Remove tags from given instance"),
326
  }
327

    
328

    
329
def Main():
330
  return GenericMain(commands,
331
                     override={"tag_type": constants.TAG_NODEGROUP},
332
                     env_override=_ENV_OVERRIDE)