File cinder-migrate-volume-names-to-cluster of Package openstack-cinder-doc

#!/usr/bin/python

# Copyright (c) 2016 SUSE GmbH.
#
# 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 print_function
import glob
import platform
import sys

import psycopg2
from six.moves.urllib_parse import urlparse


def read_value(filenames, option):
    value = None
    for filename in filenames:
        try:
            with open(filename, 'r') as f:
                for line in f:
                    if not line.startswith(option):
                        continue
                    value = line.split('=', 1)[1].strip()
                    break
        except IOError:
            pass
    return value


def main():
    conf_files = ['/etc/cinder/cinder.conf']
    conf_files.extend(glob.glob('/etc/cinder/cinder.conf.d/*.conf'))
    connection_str = read_value(conf_files, 'connection')
    if connection_str is None:
        print("Couldn't determine connection string from cinder.conf!")
        return 1
    conf_files = ['/etc/cinder/cinder-volume.conf']
    conf_files.extend(glob.glob('/etc/cinder/cinder-volume.conf.d/*.conf'))
    cluster_name = read_value(conf_files, 'host')
    if cluster_name is None:
        print("Couldn't determine cluster name!")
        return 1
    parsed = urlparse(connection_str)
    cluster = "%s@" % cluster_name
    nodename_pattern = platform.node() + '@%'
    conn = psycopg2.connect(database='cinder', user=parsed.username,
                            password=parsed.password, host=parsed.hostname)
    cur = conn.cursor()
    cur.execute("""UPDATE volumes SET host = %s || split_part(host, '@', 2)
                WHERE host LIKE %s""", (cluster, nodename_pattern))
    print("%d volumes updated." % cur.rowcount)
    conn.commit()
    return 0


if __name__ == '__main__':
    sys.exit(main())
openSUSE Build Service is sponsored by