bash_completion: Move common code into function
[ganeti-local] / scripts / gnt-debug
1 #!/usr/bin/python
2 #
3
4 # Copyright (C) 2006, 2007 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
22 # pylint: disable-msg=W0401,W0614
23 # W0401: Wildcard import ganeti.cli
24 # W0614: Unused import %s from wildcard import (since we need cli)
25
26 import sys
27 import simplejson
28 import time
29
30 from ganeti.cli import *
31 from ganeti import cli
32 from ganeti import opcodes
33 from ganeti import constants
34 from ganeti import utils
35 from ganeti import errors
36
37
38 def Delay(opts, args):
39   """Sleeps for a while
40
41   @param opts: the command line options selected by the user
42   @type args: list
43   @param args: should contain only one element, the duration
44       the sleep
45   @rtype: int
46   @return: the desired exit code
47
48   """
49   delay = float(args[0])
50   op = opcodes.OpTestDelay(duration=delay,
51                            on_master=opts.on_master,
52                            on_nodes=opts.on_nodes)
53   SubmitOpCode(op)
54
55   return 0
56
57
58 def GenericOpCodes(opts, args):
59   """Send any opcode to the master.
60
61   @todo: The function is broken and needs to be converted to the
62       current job queue API
63   @param opts: the command line options selected by the user
64   @type args: list
65   @param args: should contain only one element, the path of
66       the file with the opcode definition
67   @rtype: int
68   @return: the desired exit code
69
70   """
71   cl = cli.GetClient()
72   jex = cli.JobExecutor(cl=cl, verbose=opts.verbose)
73
74   job_cnt = 0
75   op_cnt = 0
76   if opts.timing_stats:
77     ToStdout("Loading...")
78   for job_idx in range(opts.rep_job):
79     for fname in args:
80       op_data = simplejson.loads(utils.ReadFile(fname))
81       op_list = [opcodes.OpCode.LoadOpCode(val) for val in op_data]
82       op_list = op_list * opts.rep_op
83       jex.QueueJob("file %s/%d" % (fname, job_idx), *op_list)
84       op_cnt += len(op_list)
85       job_cnt += 1
86
87   if opts.timing_stats:
88     t1 = time.time()
89     ToStdout("Submitting...")
90
91   jex.SubmitPending()
92
93   if opts.timing_stats:
94     t2 = time.time()
95     ToStdout("Executing...")
96
97   jex.GetResults()
98   if opts.timing_stats:
99     t3 = time.time()
100     ToStdout("C:op     %4d" % op_cnt)
101     ToStdout("C:job    %4d" % job_cnt)
102     ToStdout("T:submit %4.4f" % (t2-t1))
103     ToStdout("T:exec   %4.4f" % (t3-t2))
104     ToStdout("T:total  %4.4f" % (t3-t1))
105   return 0
106
107
108 def TestAllocator(opts, args):
109   """Runs the test allocator opcode.
110
111   @param opts: the command line options selected by the user
112   @type args: list
113   @param args: should contain only one element, the iallocator name
114   @rtype: int
115   @return: the desired exit code
116
117   """
118   try:
119     disks = [{"size": utils.ParseUnit(val), "mode": 'w'}
120              for val in opts.disks.split(",")]
121   except errors.UnitParseError, err:
122     ToStderr("Invalid disks parameter '%s': %s", opts.disks, err)
123     return 1
124
125   nics = [val.split("/") for val in opts.nics.split(",")]
126   for row in nics:
127     while len(row) < 3:
128       row.append(None)
129     for i in range(3):
130       if row[i] == '':
131         row[i] = None
132   nic_dict = [{"mac": v[0], "ip": v[1], "bridge": v[2]} for v in nics]
133
134   if opts.tags is None:
135     opts.tags = []
136   else:
137     opts.tags = opts.tags.split(",")
138
139   op = opcodes.OpTestAllocator(mode=opts.mode,
140                                name=args[0],
141                                mem_size=opts.mem,
142                                disks=disks,
143                                disk_template=opts.disk_template,
144                                nics=nic_dict,
145                                os=opts.os,
146                                vcpus=opts.vcpus,
147                                tags=opts.tags,
148                                direction=opts.direction,
149                                allocator=opts.iallocator,
150                                )
151   result = SubmitOpCode(op)
152   ToStdout("%s" % result)
153   return 0
154
155
156 commands = {
157   'delay': (
158     Delay, [ArgUnknown(min=1, max=1)],
159     [cli_option("--no-master", dest="on_master", default=True,
160                 action="store_false", help="Do not sleep in the master code"),
161      cli_option("-n", dest="on_nodes", default=[],
162                 action="append", help="Select nodes to sleep on"),
163      ],
164     "[opts...] <duration>", "Executes a TestDelay OpCode"),
165   'submit-job': (
166     GenericOpCodes, [ArgFile(min=1)],
167     [VERBOSE_OPT,
168      cli_option("--op-repeat", type="int", default="1", dest="rep_op",
169                 help="Repeat the opcode sequence this number of times"),
170      cli_option("--job-repeat", type="int", default="1", dest="rep_job",
171                 help="Repeat the job this number of times"),
172      cli_option("--timing-stats", default=False,
173                 action="store_true", help="Show timing stats"),
174      ],
175     "<op_list_file...>", "Submits jobs built from json files"
176     " containing a list of serialized opcodes"),
177   'allocator': (
178     TestAllocator, ARGS_ONE_INSTANCE,
179     [cli_option("--dir", dest="direction",
180                 default="in", choices=["in", "out"],
181                 help="Show allocator input (in) or allocator"
182                 " results (out)"),
183      IALLOCATOR_OPT,
184      cli_option("-m", "--mode", default="relocate",
185                 choices=["relocate", "allocate"],
186                 help="Request mode, either allocate or relocate"),
187      cli_option("--mem", default=128, type="unit",
188                 help="Memory size for the instance (MiB)"),
189      cli_option("--disks", default="4096,4096",
190                 help="Comma separated list of disk sizes (MiB)"),
191      DISK_TEMPLATE_OPT,
192      cli_option("--nics", default="00:11:22:33:44:55",
193                 help="Comma separated list of nics, each nic"
194                 " definition is of form mac/ip/bridge, if"
195                 " missing values are replace by None"),
196      OS_OPT,
197      cli_option("-p", "--vcpus", default=1, type="int",
198                 help="Select number of VCPUs for the instance"),
199      cli_option("--tags", default=None,
200                 help="Comma separated list of tags"),
201      ],
202     "{opts...} <instance>", "Executes a TestAllocator OpCode"),
203   }
204
205
206 if __name__ == '__main__':
207   sys.exit(GenericMain(commands))