summaryrefslogtreecommitdiff
path: root/troveclient/compat/mcli.py
blob: f151ab7669252b63e8f31a6b892a7387eaac8da3 (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
#!/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 Management Command line tool
"""

import json
import os
import sys

from troveclient.compat import common

# 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.compat',
                               '__init__.py')):
    sys.path.insert(0, possible_topdir)


oparser = None


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


class HostCommands(common.AuthedCommandsBase):
    """Commands to list info on hosts."""

    params = [
        'name',
    ]

    def update_all(self):
        """Update all instances on a host."""
        self._require('name')
        self.dbaas.hosts.update_all(self.name)

    def get(self):
        """List details for the specified host."""
        self._require('name')
        self._pretty_print(self.dbaas.hosts.get, self.name)

    def list(self):
        """List all compute hosts."""
        self._pretty_list(self.dbaas.hosts.index)


class QuotaCommands(common.AuthedCommandsBase):
    """List and update quota limits for a tenant."""

    params = ['id',
              'instances',
              'volumes',
              'backups']

    def list(self):
        """List all quotas for a tenant."""
        self._require('id')
        self._pretty_print(self.dbaas.quota.show, self.id)

    def update(self):
        """Update quota limits for a tenant."""
        self._require('id')
        self._pretty_print(self.dbaas.quota.update, self.id,
                           dict((param, getattr(self, param))
                                for param in self.params if param != 'id'))


class RootCommands(common.AuthedCommandsBase):
    """List details about the root info for an instance."""

    params = [
        'id',
    ]

    def history(self):
        """List root history for the instance."""
        self._require('id')
        self._pretty_print(self.dbaas.management.root_enabled_history, self.id)


class AccountCommands(common.AuthedCommandsBase):
    """Commands to list account info."""

    params = [
        'id',
    ]

    def list(self):
        """List all accounts with non-deleted instances."""
        self._pretty_print(self.dbaas.accounts.index)

    def get(self):
        """List details for the account provided."""
        self._require('id')
        self._pretty_print(self.dbaas.accounts.show, self.id)


class InstanceCommands(common.AuthedCommandsBase):
    """List details about an instance."""

    params = [
        'deleted',
        'id',
        'limit',
        'marker',
        'host',
    ]

    def get(self):
        """List details for the instance."""
        self._require('id')
        self._pretty_print(self.dbaas.management.show, self.id)

    def list(self):
        """List all instances for account."""
        deleted = None
        if self.deleted is not None:
            if self.deleted.lower() in ['true']:
                deleted = True
            elif self.deleted.lower() in ['false']:
                deleted = False
        self._pretty_paged(self.dbaas.management.index, deleted=deleted)

    def hwinfo(self):
        """Show hardware information details about an instance."""
        self._require('id')
        self._pretty_print(self.dbaas.hwinfo.get, self.id)

    def diagnostic(self):
        """List diagnostic details about an instance."""
        self._require('id')
        self._pretty_print(self.dbaas.diagnostics.get, self.id)

    def stop(self):
        """Stop MySQL on the given instance."""
        self._require('id')
        self._pretty_print(self.dbaas.management.stop, self.id)

    def reboot(self):
        """Reboot the instance."""
        self._require('id')
        self._pretty_print(self.dbaas.management.reboot, self.id)

    def migrate(self):
        """Migrate the instance."""
        self._require('id')
        self._pretty_print(self.dbaas.management.migrate, self.id, self.host)

    def reset_task_status(self):
        """Set the instance's task status to NONE."""
        self._require('id')
        self._pretty_print(self.dbaas.management.reset_task_status, self.id)


class StorageCommands(common.AuthedCommandsBase):
    """Commands to list devices info."""

    params = []

    def list(self):
        """List details for the storage device."""
        self._pretty_list(self.dbaas.storage.index)


def config_options(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 = {
    'account': AccountCommands,
    'host': HostCommands,
    'instance': InstanceCommands,
    'root': RootCommands,
    'storage': StorageCommands,
    'quota': QuotaCommands,
}


def main():
    # Parse arguments
    oparser = common.CliOptions.create_optparser(True)
    for k, v in COMMANDS.items():
        v._prepare_parser(oparser)
    (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 = None
        try:
            command_object = fn(oparser)
        except Exception as ex:
            if options.debug:
                raise
            print(ex)

        # 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:
            try:
                getattr(command_object, action)()
            except Exception as ex:
                if options.debug:
                    raise
                print(ex)
        else:
            common.print_actions(cmd, actions)
    else:
        common.print_commands(COMMANDS)


if __name__ == '__main__':
    main()