Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_group.py @ e0e44476

History | View | Annotate | Download (11.6 kB)

1
#
2
#
3

    
4
# Copyright (C) 2010, 2011, 2012, 2013 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

    
35

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

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

    
41

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

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

51
  """
52
  ipolicy = CreateIPolicyFromOpts(
53
    minmax_ispecs=opts.ipolicy_bounds_specs,
54
    ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
55
    ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
56
    ipolicy_disk_templates=opts.ipolicy_disk_templates,
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
  SubmitOrSend(op, 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
  SubmitOrSend(op, 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
  cl = GetClient(query=True)
126

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

    
132

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

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

142
  """
143
  cl = GetClient(query=True)
144

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

    
148

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

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

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

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

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

    
173
  hv_state = dict(opts.hv_state)
174

    
175
  diskparams = dict(opts.diskparams)
176

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

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

    
194
  result = SubmitOrSend(op, opts)
195

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

    
201
  return 0
202

    
203

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

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

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

    
218

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

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

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

    
233

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

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

    
240
  cl = GetClient()
241

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

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

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

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

    
263
  return rcode
264

    
265

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

    
276

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

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

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

    
293

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

    
303

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

307
  Currently it works only for ipolicy specs.
308

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

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

    
322

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

    
384

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