summaryrefslogtreecommitdiff
path: root/glance_manage
blob: b88c9b64c0de2a357c37bae070e961b32f1fc2e1 (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
#!/usr/bin/python
# -*- coding: utf-8 -*-

DOCUMENTATION = '''
---
module: glance_manage
short_description: Initialize OpenStack Image (glance) database
description: Create the tables for the database backend used by glance
options:
  action:
    description:
      - action to perform. Currently only dbsync is supported.
    required: true
  conf:
    description:
      - path to glance-registry config file.
    required: false
    default: /etc/glance/glance-registry.conf
requirements: [ glance ]
author: Lorin Hochstein
'''

EXAMPLES = '''
glance_manage: action=dbsync
'''

import glance
# this is necessary starting from havana release due to bug 885529
# https://bugs.launchpad.net/glance/+bug/885529
from glance.openstack.common import gettextutils
gettextutils.install('glance')
import glance.db.sqlalchemy.api

glance_found = True
try:
    from glance.db.sqlalchemy import migration
    from glance.common.exception import DatabaseMigrationError
    from migrate.versioning import api as versioning_api
except ImportError:
    try:
        # Icehouse imports
        from glance.openstack.common.db.sqlalchemy import migration
        from glance.openstack.common.db import options
        migration.CONF = options.CONF
        from migrate.versioning import api as versioning_api

        # Dummy class to make sure that the rest of the code can work whether
        # we're using icehouse or not
        class DatabaseMigrationError:
            pass
    except ImportError:
        glance_found = False


import os
import subprocess

import sqlalchemy

def is_under_version_control(conf):
    """ Return true if the database is under version control"""
    migration.CONF(project='glance', default_config_files=[conf])
    try:
        migration.db_version()
    except DatabaseMigrationError:
        return False
    # db_version() will fail with TypeError on icehouse. Icehouse uses db
    # migration so we're good.
    finally:
        return True


def will_db_change(conf):
    """ Check if the database version will change after the sync """
    # Load the config file options
    if not is_under_version_control(conf):
        return True
    migration.CONF(project='glance', default_config_files=[conf])
    try:
        repo_path = migration.get_migrate_repo_path()
        current_version = migration.db_version()
    except AttributeError:
        # icehouse
        repo_path = os.path.join(os.path.dirname(glance.__file__),
                                 'db', 'sqlalchemy', 'migrate_repo')
        engine = sqlalchemy.create_engine(migration.CONF.database.connection)
        current_version = migration.db_version(engine, repo_path, 0)
    repo_version = versioning_api.repository.Repository(repo_path).latest
    return current_version != repo_version


def put_under_version_control():
    """ Create the initial sqlalchemy migrate database tables. """
    args = ['glance-manage', 'version_control', '0']

    call = subprocess.Popen(args, shell=False,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = call.communicate()
    return (call.returncode, out, err)


def do_dbsync():
    """ Do a database migration """
    args = ['glance-manage', 'db_sync']

    call = subprocess.Popen(args, shell=False,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = call.communicate()
    return (call.returncode, out, err)


def main():

    module = AnsibleModule(
        argument_spec=dict(
            action=dict(required=True),
            conf=dict(required=False,
                      default="/etc/glance/glance-registry.conf")
        ),
        supports_check_mode=True
    )
    if not glance_found:
        module.fail_json(msg="glance package could not be found")

    action = module.params['action']
    if action not in ['dbsync', 'db_sync']:
        module.fail_json(msg="Only supported action is 'dbsync'")

    conf = module.params['conf']

    changed = will_db_change(conf)
    if module.check_mode:
        module.exit_json(changed=changed)

    if not is_under_version_control(conf):
        (res, stdout, stderr) = put_under_version_control()
        if res != 0:
            msg = "failed to put glance db under version control"
            module.fail_json(msg=msg, stdout=stdout, stderr=stderr)

    (res, stdout, stderr) = do_dbsync()
    if res != 0:
        msg = "failed to synchronize glance db with repository"
        module.fail_json(msg=msg, stdout=stdout, stderr=stderr)

    module.exit_json(changed=changed)

#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()