summaryrefslogtreecommitdiff
path: root/bin/trove-cli
blob: 04d8c934924d6a793c95da9be5bc1eb61134d793 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python

#    Copyright 2011 OpenStack Foundation
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Trove Command line tool
"""

import json
import optparse
import os
import sys


# If ../trove/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
                                   os.pardir,
                                   os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'troveclient',
                               '__init__.py')):
    sys.path.insert(0, possible_topdir)
if os.path.exists(os.path.join(possible_topdir, 'nova', '__init__.py')):
    sys.path.insert(0, possible_topdir)


from troveclient import common


oparser = None


def _pretty_print(info):
    print json.dumps(info, sort_keys=True, indent=4)


class InstanceCommands(object):
    """Commands to perform various instances operations and actions"""

    def __init__(self):
        pass

    def create(self, name, volume_size,
               flavorRef="http://localhost:8775/v1.0/flavors/1"):
        """Create a new instance"""
        dbaas = common.get_client()
        volume = {"size": volume_size}
        try:
            result = dbaas.instances.create(name, flavorRef, volume)
            _pretty_print(result._info)
        except:
            print sys.exc_info()[1]

    def delete(self, id):
        """Delete the specified instance"""
        dbaas = common.get_client()
        try:
            result = dbaas.instances.delete(id)
            if result:
                print result
        except:
            print sys.exc_info()[1]

    def get(self, id):
        """Get details for the specified instance"""
        dbaas = common.get_client()
        try:
            _pretty_print(dbaas.instances.get(id)._info)
        except:
            print sys.exc_info()[1]

    def list(self):
        """List all instances for account"""
        dbaas = common.get_client()
        try:
            for instance in dbaas.instances.list():
                _pretty_print(instance._info)
        except:
            print sys.exc_info()[1]

    def resize(self, id, size):
        """Resize an instance volume"""
        dbaas = common.get_client()
        try:
            result = dbaas.instances.resize(id, size)
            if result:
                print result
        except:
            print sys.exc_info()[1]

    def restart(self, id):
        """Restart the database"""
        dbaas = common.get_client()
        try:
            result = dbaas.instances.restart(id)
            if result:
                print result
        except:
            print sys.exc_info()[1]


class FlavorsCommands(object):
    """Commands for listing Flavors"""

    def __init__(self):
        pass

    def list(self):
        """List the available flavors"""
        dbaas = common.get_client()
        try:
            for flavor in dbaas.flavors.list():
                _pretty_print(flavor._info)
        except:
            print sys.exc_info()[1]


class DatabaseCommands(object):
    """Database CRUD operations on an instance"""

    def __init__(self):
        pass

    def create(self, id, dbname):
        """Create a database"""
        dbaas = common.get_client()
        try:
            databases = [{'name': dbname}]
            dbaas.databases.create(id, databases)
        except:
            print sys.exc_info()[1]

    def delete(self, id, dbname):
        """Delete a database"""
        dbaas = common.get_client()
        try:
            dbaas.databases.delete(id, dbname)
        except:
            print sys.exc_info()[1]

    def list(self, id):
        """List the databases"""
        dbaas = common.get_client()
        try:
            for database in dbaas.databases.list(id):
                _pretty_print(database._info)
        except:
            print sys.exc_info()[1]


class UserCommands(object):
    """User CRUD operations on an instance"""

    def __init__(self):
        pass

    def create(self, id, username, password, dbname, *args):
        """Create a user in instance, with access to one or more databases"""
        dbaas = common.get_client()
        try:
            databases = [{'name': dbname}]
            [databases.append({"name": db}) for db in args]
            users = [{'name': username, 'password': password,
                      'databases': databases}]
            dbaas.users.create(id, users)
        except:
            print sys.exc_info()[1]

    def delete(self, id, user):
        """Delete the specified user"""
        dbaas = common.get_client()
        try:
            dbaas.users.delete(id, user)
        except:
            print sys.exc_info()[1]

    def list(self, id):
        """List all the users for an instance"""
        dbaas = common.get_client()
        try:
            for user in dbaas.users.list(id):
                _pretty_print(user._info)
        except:
            print sys.exc_info()[1]


class RootCommands(object):
    """Root user related operations on an instance"""

    def __init__(self):
        pass

    def create(self, id):
        """Enable the instance's root user."""
        dbaas = common.get_client()
        try:
            user, password = dbaas.root.create(id)
            print "User:\t\t%s\nPassword:\t%s" % (user, password)
        except:
            print sys.exc_info()[1]

    def enabled(self, id):
        """Check the instance for root access"""
        dbaas = common.get_client()
        try:
            _pretty_print(dbaas.root.is_root_enabled(id))
        except:
            print sys.exc_info()[1]


class VersionCommands(object):
    """List available versions"""

    def __init__(self):
        pass

    def list(self, url):
        """List all the supported versions"""
        dbaas = common.get_client()
        try:
            versions = dbaas.versions.index(url)
            for version in versions:
                _pretty_print(version._info)
        except:
            print sys.exc_info()[1]


def config_options():
    global oparser
    oparser.add_option("-u", "--url", default="http://localhost:5000/v1.1",
                       help="Auth API endpoint URL with port and version. \
                            Default: http://localhost:5000/v1.1")


COMMANDS = {'auth': common.Auth,
            'instance': InstanceCommands,
            'flavor': FlavorsCommands,
            'database': DatabaseCommands,
            'user': UserCommands,
            'root': RootCommands,
            'version': VersionCommands}


def main():
    # Parse arguments
    global oparser
    oparser = optparse.OptionParser("%prog [options] <cmd> <action> <args>",
                                    version='1.0')
    config_options()
    (options, args) = oparser.parse_args()

    if not args:
        common.print_commands(COMMANDS)

    # Pop the command and check if it's in the known commands
    cmd = args.pop(0)
    if cmd in COMMANDS:
        fn = COMMANDS.get(cmd)
        command_object = fn()

        # Get a list of supported actions for the command
        actions = common.methods_of(command_object)

        if len(args) < 1:
            common.print_actions(cmd, actions)

        # Check for a valid action and perform that action
        action = args.pop(0)
        if action in actions:
            fn = actions.get(action)

            try:
                fn(*args)
                sys.exit(0)
            except TypeError as err:
                print "Possible wrong number of arguments supplied."
                print "%s %s: %s" % (cmd, action, fn.__doc__)
                print "\t\t", [fn.func_code.co_varnames[i] for i in
                                            range(fn.func_code.co_argcount)]
                print "ERROR: %s" % err
            except Exception:
                print "Command failed, please check the log for more info."
                raise
        else:
            common.print_actions(cmd, actions)
    else:
        common.print_commands(COMMANDS)


if __name__ == '__main__':
    main()