summaryrefslogtreecommitdiffstats
path: root/keystone/cli.py
blob: 6575f2e9af2cb9d8cefe3a9c16f3ac1167c1d6dd (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
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2012 OpenStack LLC
#
# 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.

from __future__ import absolute_import

import grp
import os
import pwd

from migrate import exceptions

from oslo.config import cfg
import pbr.version

from keystone.common import openssl
from keystone.common.sql import migration
from keystone import config
from keystone import contrib
from keystone.openstack.common import importutils
from keystone.openstack.common import jsonutils
from keystone import token

CONF = config.CONF


class BaseApp(object):

    name = None

    @classmethod
    def add_argument_parser(cls, subparsers):
        parser = subparsers.add_parser(cls.name, help=cls.__doc__)
        parser.set_defaults(cmd_class=cls)
        return parser


class DbSync(BaseApp):
    """Sync the database."""

    name = 'db_sync'

    @classmethod
    def add_argument_parser(cls, subparsers):
        parser = super(DbSync, cls).add_argument_parser(subparsers)
        parser.add_argument('version', default=None, nargs='?',
                            help=('Migrate the database up to a specified '
                                  'version. If not provided, db_sync will '
                                  'migrate the database to the latest known '
                                  'version.'))
        parser.add_argument('--extension', default=None,
                            help=('Migrate the database for the specified '
                                  'extension. If not provided, db_sync will '
                                  'migrate the common repository.'))

        return parser

    @staticmethod
    def main():
        version = CONF.command.version
        extension = CONF.command.extension
        if not extension:
            migration.db_sync(version=version)
        else:
            package_name = "%s.%s.migrate_repo" % (contrib.__name__, extension)
            try:
                package = importutils.import_module(package_name)
                repo_path = os.path.abspath(os.path.dirname(package.__file__))
            except ImportError:
                print(_("This extension does not provide migrations."))
                exit(0)
            try:
                # Register the repo with the version control API
                # If it already knows about the repo, it will throw
                # an exception that we can safely ignore
                migration.db_version_control(version=None, repo_path=repo_path)
            except exceptions.DatabaseAlreadyControlledError:
                pass
            migration.db_sync(version=None, repo_path=repo_path)


class DbVersion(BaseApp):
    """Print the current migration version of the database."""

    name = 'db_version'

    @classmethod
    def add_argument_parser(cls, subparsers):
        parser = super(DbVersion, cls).add_argument_parser(subparsers)
        parser.add_argument('--extension', default=None,
                            help=('Migrate the database for the specified '
                                  'extension. If not provided, db_sync will '
                                  'migrate the common repository.'))

    @staticmethod
    def main():
        extension = CONF.command.extension
        if extension:
            try:
                package_name = ("%s.%s.migrate_repo" %
                                (contrib.__name__, extension))
                package = importutils.import_module(package_name)
                repo_path = os.path.abspath(os.path.dirname(package.__file__))
                print(migration.db_version(repo_path))
            except ImportError:
                print(_("This extension does not provide migrations."))
                exit(1)
        else:
            print(migration.db_version())


class BaseCertificateSetup(BaseApp):
    """Common user/group setup for PKI and SSL generation."""

    @classmethod
    def add_argument_parser(cls, subparsers):
        parser = super(BaseCertificateSetup,
                       cls).add_argument_parser(subparsers)
        running_as_root = (os.geteuid() == 0)
        parser.add_argument('--keystone-user', required=running_as_root)
        parser.add_argument('--keystone-group', required=running_as_root)
        return parser

    @staticmethod
    def get_user_group():
        keystone_user_id = None
        keystone_group_id = None

        try:
            a = CONF.command.keystone_user
            if a:
                keystone_user_id = pwd.getpwnam(a).pw_uid
        except KeyError:
            raise ValueError("Unknown user '%s' in --keystone-user" % a)

        try:
            a = CONF.command.keystone_group
            if a:
                keystone_group_id = grp.getgrnam(a).gr_gid
        except KeyError:
            raise ValueError("Unknown group '%s' in --keystone-group" % a)

        return keystone_user_id, keystone_group_id


class PKISetup(BaseCertificateSetup):
    """Set up Key pairs and certificates for token signing and verification."""

    name = 'pki_setup'

    @classmethod
    def main(cls):
        keystone_user_id, keystone_group_id = cls.get_user_group()
        conf_pki = openssl.ConfigurePKI(keystone_user_id, keystone_group_id)
        conf_pki.run()


class SSLSetup(BaseCertificateSetup):
    """Create key pairs and certificates for HTTPS connections."""

    name = 'ssl_setup'

    @classmethod
    def main(cls):
        keystone_user_id, keystone_group_id = cls.get_user_group()
        conf_ssl = openssl.ConfigureSSL(keystone_user_id, keystone_group_id)
        conf_ssl.run()


class TokenFlush(BaseApp):
    """Flush expired tokens from the backend."""

    name = 'token_flush'

    @classmethod
    def main(cls):
        token_manager = token.Manager()
        token_manager.driver.flush_expired_tokens()


class ImportLegacy(BaseApp):
    """Import a legacy database."""

    name = 'import_legacy'

    @classmethod
    def add_argument_parser(cls, subparsers):
        parser = super(ImportLegacy, cls).add_argument_parser(subparsers)
        parser.add_argument('old_db')
        return parser

    @staticmethod
    def main():
        from keystone.common.sql import legacy
        migration = legacy.LegacyMigration(CONF.command.old_db)
        migration.migrate_all()


class ExportLegacyCatalog(BaseApp):
    """Export the service catalog from a legacy database."""

    name = 'export_legacy_catalog'

    @classmethod
    def add_argument_parser(cls, subparsers):
        parser = super(ExportLegacyCatalog,
                       cls).add_argument_parser(subparsers)
        parser.add_argument('old_db')
        return parser

    @staticmethod
    def main():
        from keystone.common.sql import legacy
        migration = legacy.LegacyMigration(CONF.command.old_db)
        print('\n'.join(migration.dump_catalog()))


class ImportNovaAuth(BaseApp):
    """Import a dump of nova auth data into keystone."""

    name = 'import_nova_auth'

    @classmethod
    def add_argument_parser(cls, subparsers):
        parser = super(ImportNovaAuth, cls).add_argument_parser(subparsers)
        parser.add_argument('dump_file')
        return parser

    @staticmethod
    def main():
        from keystone.common.sql import nova
        dump_data = jsonutils.loads(open(CONF.command.dump_file).read())
        nova.import_auth(dump_data)


CMDS = [
    DbSync,
    DbVersion,
    ExportLegacyCatalog,
    ImportLegacy,
    ImportNovaAuth,
    PKISetup,
    SSLSetup,
    TokenFlush,
]


def add_command_parsers(subparsers):
    for cmd in CMDS:
        cmd.add_argument_parser(subparsers)


command_opt = cfg.SubCommandOpt('command',
                                title='Commands',
                                help='Available commands',
                                handler=add_command_parsers)


def main(argv=None, config_files=None):
    CONF.register_cli_opt(command_opt)
    CONF(args=argv[1:],
         project='keystone',
         version=pbr.version.VersionInfo('keystone').version_string(),
         usage='%(prog)s [' + '|'.join([cmd.name for cmd in CMDS]) + ']',
         default_config_files=config_files)
    config.setup_logging(CONF)
    CONF.command.cmd_class.main()