~0x44/nova/extdoc

« back to all changes in this revision

Viewing changes to bin/stack

  • Committer: NTT PF Lab.
  • Date: 2010-12-24 11:38:49 UTC
  • mto: This revision was merged to the branch mainline in revision 564.
  • Revision ID: openstack@lab.ntt.co.jp-20101224113849-z9nemzmki17bxnvw
SupportĀ IPv6

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python
2
 
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
 
 
4
 
# Copyright 2010 United States Government as represented by the
5
 
# Administrator of the National Aeronautics and Space Administration.
6
 
# All Rights Reserved.
7
 
#
8
 
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
9
 
#    not use this file except in compliance with the License. You may obtain
10
 
#    a copy of the License at
11
 
#
12
 
#         http://www.apache.org/licenses/LICENSE-2.0
13
 
#
14
 
#    Unless required by applicable law or agreed to in writing, software
15
 
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16
 
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17
 
#    License for the specific language governing permissions and limitations
18
 
#    under the License.
19
 
 
20
 
"""CLI for the Direct API."""
21
 
 
22
 
import eventlet
23
 
eventlet.monkey_patch()
24
 
 
25
 
import json
26
 
import os
27
 
import pprint
28
 
import sys
29
 
import textwrap
30
 
import urllib
31
 
import urllib2
32
 
 
33
 
# If ../nova/__init__.py exists, add ../ to Python search path, so that
34
 
# it will override what happens to be installed in /usr/(local/)lib/python...
35
 
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
36
 
                                   os.pardir,
37
 
                                   os.pardir))
38
 
if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')):
39
 
    sys.path.insert(0, possible_topdir)
40
 
 
41
 
import gflags
42
 
 
43
 
 
44
 
FLAGS = gflags.FLAGS
45
 
gflags.DEFINE_string('host', '127.0.0.1', 'Direct API host')
46
 
gflags.DEFINE_integer('port', 8001, 'Direct API host')
47
 
gflags.DEFINE_string('user', 'user1', 'Direct API username')
48
 
gflags.DEFINE_string('project', 'proj1', 'Direct API project')
49
 
 
50
 
 
51
 
USAGE = """usage: stack [options] <controller> <method> [arg1=value arg2=value]
52
 
 
53
 
  `stack help` should output the list of available controllers
54
 
  `stack <controller>` should output the available methods for that controller
55
 
  `stack help <controller>` should do the same
56
 
  `stack help <controller> <method>` should output info for a method
57
 
"""
58
 
 
59
 
 
60
 
def format_help(d):
61
 
    """Format help text, keys are labels and values are descriptions."""
62
 
    MAX_INDENT = 30
63
 
    indent = max([len(k) for k in d])
64
 
    if indent > MAX_INDENT:
65
 
        indent = MAX_INDENT - 6
66
 
 
67
 
    out = []
68
 
    for k, v in sorted(d.iteritems()):
69
 
        if (len(k) + 6) > MAX_INDENT:
70
 
            out.extend(['   %s' % k])
71
 
            initial_indent = ' ' * (indent + 6)
72
 
        else:
73
 
            initial_indent = '   %s   ' % k.ljust(indent)
74
 
        subsequent_indent = ' ' * (indent + 6)
75
 
        t = textwrap.TextWrapper(initial_indent=initial_indent,
76
 
                                 subsequent_indent=subsequent_indent)
77
 
        out.extend(t.wrap(v))
78
 
    return out
79
 
 
80
 
 
81
 
def help_all():
82
 
    rv = do_request('reflect', 'get_controllers')
83
 
    out = format_help(rv)
84
 
    return (USAGE + str(FLAGS.MainModuleHelp()) +
85
 
            '\n\nAvailable controllers:\n' +
86
 
            '\n'.join(out) + '\n')
87
 
 
88
 
 
89
 
def help_controller(controller):
90
 
    rv = do_request('reflect', 'get_methods')
91
 
    methods = dict([(k.split('/')[2], v) for k, v in rv.iteritems()
92
 
               if k.startswith('/%s' % controller)])
93
 
    return ('Available methods for %s:\n' % controller +
94
 
            '\n'.join(format_help(methods)))
95
 
 
96
 
 
97
 
def help_method(controller, method):
98
 
    rv = do_request('reflect',
99
 
                    'get_method_info',
100
 
                    {'method': '/%s/%s' % (controller, method)})
101
 
 
102
 
    sig = '%s(%s):' % (method, ', '.join(['='.join(x) for x in rv['args']]))
103
 
    out = textwrap.wrap(sig, subsequent_indent=' ' * len('%s(' % method))
104
 
    out.append('\n' + rv['doc'])
105
 
    return '\n'.join(out)
106
 
 
107
 
 
108
 
def do_request(controller, method, params=None):
109
 
    if params:
110
 
        data = urllib.urlencode(params)
111
 
    else:
112
 
        data = None
113
 
 
114
 
    url = 'http://%s:%s/%s/%s' % (FLAGS.host, FLAGS.port, controller, method)
115
 
    headers = {'X-OpenStack-User': FLAGS.user,
116
 
               'X-OpenStack-Project': FLAGS.project}
117
 
 
118
 
    req = urllib2.Request(url, data, headers)
119
 
    try:
120
 
        resp = urllib2.urlopen(req)
121
 
    except urllib2.HTTPError, e:
122
 
        print e.read()
123
 
        sys.exit(1)
124
 
    return json.loads(resp.read())
125
 
 
126
 
 
127
 
if __name__ == '__main__':
128
 
    args = FLAGS(sys.argv)
129
 
 
130
 
    cmd = args.pop(0)
131
 
    if not args:
132
 
        print help_all()
133
 
        sys.exit()
134
 
 
135
 
    first = args.pop(0)
136
 
    if first == 'help':
137
 
        action = help_all
138
 
        params = []
139
 
        if args:
140
 
            params.append(args.pop(0))
141
 
            action = help_controller
142
 
        if args:
143
 
            params.append(args.pop(0))
144
 
            action = help_method
145
 
        print action(*params)
146
 
        sys.exit(0)
147
 
 
148
 
    controller = first
149
 
    if not args:
150
 
        print help_controller(controller)
151
 
        sys.exit()
152
 
 
153
 
    method = args.pop(0)
154
 
    params = {}
155
 
    for x in args:
156
 
        key, value = x.split('=', 1)
157
 
        params[key] = value
158
 
 
159
 
    pprint.pprint(do_request(controller, method, params))