Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_group.py @ 087f5520

History | View | Annotate | Download (11.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2010, 2011, 2012, 2013, 2014 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 cStringIO import StringIO
28

    
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
34
from ganeti.client import base
35

    
36

    
37
#: default list of fields for L{ListGroups}
38
_LIST_DEF_FIELDS = ["name", "node_cnt", "pinst_cnt", "alloc_policy", "ndparams"]
39

    
40
_ENV_OVERRIDE = compat.UniqueFrozenset(["list"])
41

    
42

    
43
def AddGroup(opts, args):
44
  """Add a node group to the cluster.
45

46
  @param opts: the command line options selected by the user
47
  @type args: list
48
  @param args: a list of length 1 with the name of the group to create
49
  @rtype: int
50
  @return: the desired exit code
51

52
  """
53
  ipolicy = CreateIPolicyFromOpts(
54
    minmax_ispecs=opts.ipolicy_bounds_specs,
55
    ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
56
    ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
57
    ipolicy_disk_templates=opts.ipolicy_disk_templates,
58
    group_ipolicy=True)
59

    
60
  (group_name,) = args
61
  diskparams = dict(opts.diskparams)
62

    
63
  if opts.disk_state:
64
    disk_state = utils.FlatToDict(opts.disk_state)
65
  else:
66
    disk_state = {}
67
  hv_state = dict(opts.hv_state)
68

    
69
  op = opcodes.OpGroupAdd(group_name=group_name, ndparams=opts.ndparams,
70
                          alloc_policy=opts.alloc_policy,
71
                          diskparams=diskparams, ipolicy=ipolicy,
72
                          hv_state=hv_state,
73
                          disk_state=disk_state)
74
  return base.GetResult(None, opts, SubmitOrSend(op, opts))
75

    
76

    
77
def AssignNodes(opts, args):
78
  """Assign nodes to a group.
79

80
  @param opts: the command line options selected by the user
81
  @type args: list
82
  @param args: args[0]: group to assign nodes to; args[1:]: nodes to assign
83
  @rtype: int
84
  @return: the desired exit code
85

86
  """
87
  group_name = args[0]
88
  node_names = args[1:]
89

    
90
  op = opcodes.OpGroupAssignNodes(group_name=group_name, nodes=node_names,
91
                                  force=opts.force)
92
  SubmitOrSend(op, opts)
93

    
94

    
95
def _FmtDict(data):
96
  """Format dict data into command-line format.
97

98
  @param data: The input dict to be formatted
99
  @return: The formatted dict
100

101
  """
102
  if not data:
103
    return "(empty)"
104

    
105
  return utils.CommaJoin(["%s=%s" % (key, value)
106
                          for key, value in data.items()])
107

    
108

    
109
def ListGroups(opts, args):
110
  """List node groups and their properties.
111

112
  @param opts: the command line options selected by the user
113
  @type args: list
114
  @param args: groups to list, or empty for all
115
  @rtype: int
116
  @return: the desired exit code
117

118
  """
119
  desired_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
120
  fmtoverride = {
121
    "node_list": (",".join, False),
122
    "pinst_list": (",".join, False),
123
    "ndparams": (_FmtDict, False),
124
    }
125

    
126
  cl = GetClient()
127

    
128
  return GenericList(constants.QR_GROUP, desired_fields, args, None,
129
                     opts.separator, not opts.no_headers,
130
                     format_override=fmtoverride, verbose=opts.verbose,
131
                     force_filter=opts.force_filter, cl=cl)
132

    
133

    
134
def ListGroupFields(opts, args):
135
  """List node fields.
136

137
  @param opts: the command line options selected by the user
138
  @type args: list
139
  @param args: fields to list, or empty for all
140
  @rtype: int
141
  @return: the desired exit code
142

143
  """
144
  cl = GetClient()
145

    
146
  return GenericListFields(constants.QR_GROUP, args, opts.separator,
147
                           not opts.no_headers, cl=cl)
148

    
149

    
150
def SetGroupParams(opts, args):
151
  """Modifies a node group's parameters.
152

153
  @param opts: the command line options selected by the user
154
  @type args: list
155
  @param args: should contain only one element, the node group name
156

157
  @rtype: int
158
  @return: the desired exit code
159

160
  """
161
  allmods = [opts.ndparams, opts.alloc_policy, opts.diskparams, opts.hv_state,
162
             opts.disk_state, opts.ipolicy_bounds_specs,
163
             opts.ipolicy_vcpu_ratio, opts.ipolicy_spindle_ratio,
164
             opts.diskparams, opts.ipolicy_disk_templates]
165
  if allmods.count(None) == len(allmods):
166
    ToStderr("Please give at least one of the parameters.")
167
    return 1
168

    
169
  if opts.disk_state:
170
    disk_state = utils.FlatToDict(opts.disk_state)
171
  else:
172
    disk_state = {}
173

    
174
  hv_state = dict(opts.hv_state)
175

    
176
  diskparams = dict(opts.diskparams)
177

    
178
  # create ipolicy object
179
  ipolicy = CreateIPolicyFromOpts(
180
    minmax_ispecs=opts.ipolicy_bounds_specs,
181
    ipolicy_disk_templates=opts.ipolicy_disk_templates,
182
    ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
183
    ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
184
    group_ipolicy=True,
185
    allowed_values=[constants.VALUE_DEFAULT])
186

    
187
  op = opcodes.OpGroupSetParams(group_name=args[0],
188
                                ndparams=opts.ndparams,
189
                                alloc_policy=opts.alloc_policy,
190
                                hv_state=hv_state,
191
                                disk_state=disk_state,
192
                                diskparams=diskparams,
193
                                ipolicy=ipolicy)
194

    
195
  result = SubmitOrSend(op, opts)
196

    
197
  if result:
198
    ToStdout("Modified node group %s", args[0])
199
    for param, data in result:
200
      ToStdout(" - %-5s -> %s", param, data)
201

    
202
  return 0
203

    
204

    
205
def RemoveGroup(opts, args):
206
  """Remove a node group from the cluster.
207

208
  @param opts: the command line options selected by the user
209
  @type args: list
210
  @param args: a list of length 1 with the name of the group to remove
211
  @rtype: int
212
  @return: the desired exit code
213

214
  """
215
  (group_name,) = args
216
  op = opcodes.OpGroupRemove(group_name=group_name)
217
  SubmitOrSend(op, opts)
218

    
219

    
220
def RenameGroup(opts, args):
221
  """Rename a node group.
222

223
  @param opts: the command line options selected by the user
224
  @type args: list
225
  @param args: a list of length 2, [old_name, new_name]
226
  @rtype: int
227
  @return: the desired exit code
228

229
  """
230
  group_name, new_name = args
231
  op = opcodes.OpGroupRename(group_name=group_name, new_name=new_name)
232
  SubmitOrSend(op, opts)
233

    
234

    
235
def EvacuateGroup(opts, args):
236
  """Evacuate a node group.
237

238
  """
239
  (group_name, ) = args
240

    
241
  cl = GetClient()
242

    
243
  op = opcodes.OpGroupEvacuate(group_name=group_name,
244
                               iallocator=opts.iallocator,
245
                               target_groups=opts.to,
246
                               early_release=opts.early_release)
247
  result = SubmitOrSend(op, opts, cl=cl)
248

    
249
  # Keep track of submitted jobs
250
  jex = JobExecutor(cl=cl, opts=opts)
251

    
252
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
253
    jex.AddJobId(None, status, job_id)
254

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

    
264
  return rcode
265

    
266

    
267
def _FormatGroupInfo(group):
268
  (name, ndparams, custom_ndparams, diskparams, custom_diskparams,
269
   ipolicy, custom_ipolicy) = group
270
  return [
271
    ("Node group", name),
272
    ("Node parameters", FormatParamsDictInfo(custom_ndparams, ndparams)),
273
    ("Disk parameters", FormatParamsDictInfo(custom_diskparams, diskparams)),
274
    ("Instance policy", FormatPolicyInfo(custom_ipolicy, ipolicy, False)),
275
    ]
276

    
277

    
278
def GroupInfo(_, args):
279
  """Shows info about node group.
280

281
  """
282
  cl = GetClient()
283
  selected_fields = ["name",
284
                     "ndparams", "custom_ndparams",
285
                     "diskparams", "custom_diskparams",
286
                     "ipolicy", "custom_ipolicy"]
287
  result = cl.QueryGroups(names=args, fields=selected_fields,
288
                          use_locking=False)
289

    
290
  PrintGenericInfo([
291
    _FormatGroupInfo(group) for group in result
292
    ])
293

    
294

    
295
def _GetCreateCommand(group):
296
  (name, ipolicy) = group
297
  buf = StringIO()
298
  buf.write("gnt-group add")
299
  PrintIPolicyCommand(buf, ipolicy, True)
300
  buf.write(" ")
301
  buf.write(name)
302
  return buf.getvalue()
303

    
304

    
305
def ShowCreateCommand(opts, args):
306
  """Shows the command that can be used to re-create a node group.
307

308
  Currently it works only for ipolicy specs.
309

310
  """
311
  cl = GetClient()
312
  selected_fields = ["name"]
313
  if opts.include_defaults:
314
    selected_fields += ["ipolicy"]
315
  else:
316
    selected_fields += ["custom_ipolicy"]
317
  result = cl.QueryGroups(names=args, fields=selected_fields,
318
                          use_locking=False)
319

    
320
  for group in result:
321
    ToStdout(_GetCreateCommand(group))
322

    
323

    
324
commands = {
325
  "add": (
326
    AddGroup, ARGS_ONE_GROUP,
327
    [DRY_RUN_OPT, ALLOC_POLICY_OPT, NODE_PARAMS_OPT, DISK_PARAMS_OPT,
328
     HV_STATE_OPT, DISK_STATE_OPT, PRIORITY_OPT]
329
    + SUBMIT_OPTS + INSTANCE_POLICY_OPTS,
330
    "<group_name>", "Add a new node group to the cluster"),
331
  "assign-nodes": (
332
    AssignNodes, ARGS_ONE_GROUP + ARGS_MANY_NODES,
333
    [DRY_RUN_OPT, FORCE_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
334
    "<group_name> <node>...", "Assign nodes to a group"),
335
  "list": (
336
    ListGroups, ARGS_MANY_GROUPS,
337
    [NOHDR_OPT, SEP_OPT, FIELDS_OPT, VERBOSE_OPT, FORCE_FILTER_OPT],
338
    "[<group_name>...]",
339
    "Lists the node groups in the cluster. The available fields can be shown"
340
    " using the \"list-fields\" command (see the man page for details)."
341
    " The default list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS)),
342
  "list-fields": (
343
    ListGroupFields, [ArgUnknown()], [NOHDR_OPT, SEP_OPT], "[fields...]",
344
    "Lists all available fields for node groups"),
345
  "modify": (
346
    SetGroupParams, ARGS_ONE_GROUP,
347
    [DRY_RUN_OPT] + SUBMIT_OPTS +
348
    [ALLOC_POLICY_OPT, NODE_PARAMS_OPT, HV_STATE_OPT, DISK_STATE_OPT,
349
     DISK_PARAMS_OPT, PRIORITY_OPT]
350
    + INSTANCE_POLICY_OPTS,
351
    "<group_name>", "Alters the parameters of a node group"),
352
  "remove": (
353
    RemoveGroup, ARGS_ONE_GROUP, [DRY_RUN_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
354
    "[--dry-run] <group-name>",
355
    "Remove an (empty) node group from the cluster"),
356
  "rename": (
357
    RenameGroup, [ArgGroup(min=2, max=2)],
358
    [DRY_RUN_OPT] + SUBMIT_OPTS + [PRIORITY_OPT],
359
    "[--dry-run] <group-name> <new-name>", "Rename a node group"),
360
  "evacuate": (
361
    EvacuateGroup, [ArgGroup(min=1, max=1)],
362
    [TO_GROUP_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT] + SUBMIT_OPTS,
363
    "[-I <iallocator>] [--to <group>]",
364
    "Evacuate all instances within a group"),
365
  "list-tags": (
366
    ListTags, ARGS_ONE_GROUP, [],
367
    "<group_name>", "List the tags of the given group"),
368
  "add-tags": (
369
    AddTags, [ArgGroup(min=1, max=1), ArgUnknown()],
370
    [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
371
    "<group_name> tag...", "Add tags to the given group"),
372
  "remove-tags": (
373
    RemoveTags, [ArgGroup(min=1, max=1), ArgUnknown()],
374
    [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
375
    "<group_name> tag...", "Remove tags from the given group"),
376
  "info": (
377
    GroupInfo, ARGS_MANY_GROUPS, [], "[<group_name>...]",
378
    "Show group information"),
379
  "show-ispecs-cmd": (
380
    ShowCreateCommand, ARGS_MANY_GROUPS, [INCLUDEDEFAULTS_OPT],
381
    "[--include-defaults] [<group_name>...]",
382
    "Show the command line to re-create a group"),
383
  }
384

    
385

    
386
def Main():
387
  return GenericMain(commands,
388
                     override={"tag_type": constants.TAG_NODEGROUP},
389
                     env_override=_ENV_OVERRIDE)