Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_group.py @ 801bccba

History | View | Annotate | Download (11.4 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 ganeti.cli import *
28
from ganeti import constants
29
from ganeti import opcodes
30
from ganeti import utils
31
from ganeti import compat
32

    
33

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

    
37
_ENV_OVERRIDE = compat.UniqueFrozenset(["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
  ipolicy = CreateIPolicyFromOpts(
51
    ispecs_mem_size=opts.ispecs_mem_size,
52
    ispecs_cpu_count=opts.ispecs_cpu_count,
53
    ispecs_disk_count=opts.ispecs_disk_count,
54
    ispecs_disk_size=opts.ispecs_disk_size,
55
    ispecs_nic_count=opts.ispecs_nic_count,
56
    ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
57
    ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
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
  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(query=True)
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(query=True)
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.ispecs_mem_size, opts.ispecs_cpu_count,
163
             opts.ispecs_disk_count, opts.ispecs_disk_size,
164
             opts.ispecs_nic_count, opts.ipolicy_vcpu_ratio,
165
             opts.ipolicy_spindle_ratio, opts.diskparams]
166
  if allmods.count(None) == len(allmods):
167
    ToStderr("Please give at least one of the parameters.")
168
    return 1
169

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

    
175
  hv_state = dict(opts.hv_state)
176

    
177
  diskparams = dict(opts.diskparams)
178

    
179
  # set the default values
180
  to_ipolicy = [
181
    opts.ispecs_mem_size,
182
    opts.ispecs_cpu_count,
183
    opts.ispecs_disk_count,
184
    opts.ispecs_disk_size,
185
    opts.ispecs_nic_count,
186
    ]
187
  for ispec in to_ipolicy:
188
    for param in ispec:
189
      if isinstance(ispec[param], basestring):
190
        if ispec[param].lower() == "default":
191
          ispec[param] = constants.VALUE_DEFAULT
192
  # create ipolicy object
193
  ipolicy = CreateIPolicyFromOpts(
194
    ispecs_mem_size=opts.ispecs_mem_size,
195
    ispecs_cpu_count=opts.ispecs_cpu_count,
196
    ispecs_disk_count=opts.ispecs_disk_count,
197
    ispecs_disk_size=opts.ispecs_disk_size,
198
    ispecs_nic_count=opts.ispecs_nic_count,
199
    ipolicy_disk_templates=opts.ipolicy_disk_templates,
200
    ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
201
    ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
202
    group_ipolicy=True,
203
    allowed_values=[constants.VALUE_DEFAULT])
204

    
205
  op = opcodes.OpGroupSetParams(group_name=args[0],
206
                                ndparams=opts.ndparams,
207
                                alloc_policy=opts.alloc_policy,
208
                                hv_state=hv_state,
209
                                disk_state=disk_state,
210
                                diskparams=diskparams,
211
                                ipolicy=ipolicy)
212

    
213
  result = SubmitOrSend(op, opts)
214

    
215
  if result:
216
    ToStdout("Modified node group %s", args[0])
217
    for param, data in result:
218
      ToStdout(" - %-5s -> %s", param, data)
219

    
220
  return 0
221

    
222

    
223
def RemoveGroup(opts, args):
224
  """Remove a node group from the cluster.
225

226
  @param opts: the command line options selected by the user
227
  @type args: list
228
  @param args: a list of length 1 with the name of the group to remove
229
  @rtype: int
230
  @return: the desired exit code
231

232
  """
233
  (group_name,) = args
234
  op = opcodes.OpGroupRemove(group_name=group_name)
235
  SubmitOrSend(op, opts)
236

    
237

    
238
def RenameGroup(opts, args):
239
  """Rename a node group.
240

241
  @param opts: the command line options selected by the user
242
  @type args: list
243
  @param args: a list of length 2, [old_name, new_name]
244
  @rtype: int
245
  @return: the desired exit code
246

247
  """
248
  group_name, new_name = args
249
  op = opcodes.OpGroupRename(group_name=group_name, new_name=new_name)
250
  SubmitOrSend(op, opts)
251

    
252

    
253
def EvacuateGroup(opts, args):
254
  """Evacuate a node group.
255

256
  """
257
  (group_name, ) = args
258

    
259
  cl = GetClient()
260

    
261
  op = opcodes.OpGroupEvacuate(group_name=group_name,
262
                               iallocator=opts.iallocator,
263
                               target_groups=opts.to,
264
                               early_release=opts.early_release)
265
  result = SubmitOrSend(op, opts, cl=cl)
266

    
267
  # Keep track of submitted jobs
268
  jex = JobExecutor(cl=cl, opts=opts)
269

    
270
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
271
    jex.AddJobId(None, status, job_id)
272

    
273
  results = jex.GetResults()
274
  bad_cnt = len([row for row in results if not row[0]])
275
  if bad_cnt == 0:
276
    ToStdout("All instances evacuated successfully.")
277
    rcode = constants.EXIT_SUCCESS
278
  else:
279
    ToStdout("There were %s errors during the evacuation.", bad_cnt)
280
    rcode = constants.EXIT_FAILURE
281

    
282
  return rcode
283

    
284

    
285
def _FormatGroupInfo(group):
286
  (name, ndparams, custom_ndparams, diskparams, custom_diskparams,
287
   ipolicy, custom_ipolicy) = group
288
  return [
289
    ("Node group", name),
290
    ("Node parameters", FormatParamsDictInfo(custom_ndparams, ndparams)),
291
    ("Disk parameters", FormatParamsDictInfo(custom_diskparams, diskparams)),
292
    ("Instance policy", FormatPolicyInfo(custom_ipolicy, ipolicy, False)),
293
    ]
294

    
295

    
296
def GroupInfo(_, args):
297
  """Shows info about node group.
298

299
  """
300
  cl = GetClient(query=True)
301
  selected_fields = ["name",
302
                     "ndparams", "custom_ndparams",
303
                     "diskparams", "custom_diskparams",
304
                     "ipolicy", "custom_ipolicy"]
305
  result = cl.QueryGroups(names=args, fields=selected_fields,
306
                          use_locking=False)
307

    
308
  PrintGenericInfo([
309
    _FormatGroupInfo(group) for group in result
310
    ])
311

    
312

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

    
368

    
369
def Main():
370
  return GenericMain(commands,
371
                     override={"tag_type": constants.TAG_NODEGROUP},
372
                     env_override=_ENV_OVERRIDE)