~gandelman-a/charms/quantal/mysql/trunk

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
#!/usr/bin/env python

from common import *

import urllib
import subprocess
import os
import sys
import string
import random
import pickle

cursor = get_db_cursor()

admin = os.path.basename(sys.argv[0]) == 'db-admin-relation-joined'

def runsql(sql):
	print "[%s]" % sql
	cursor.execute(sql)

# Determine if we need to create a new database
if slave and slave_configured and not broken:
  print "%s exists, assuming configuration done" % slave_configured_path
  sys.exit(0)

if not slave and not broken and not admin:
  # Find existing databases
  cursor.execute("show databases")
  databases = [i[0] for i in cursor.fetchall()]
  if database_name in databases:
    print "database exists, assuming configuration has happened already"
    sys.exit(0)

# Database is created just before relation-set in case other steps fail

# Create database user and grant access
service_password = "".join(random.sample(string.letters, 10))

runsql(
    "grant replication client on *.* to `%s` identified by '%s'"  % (
    user,
    service_password))

if slave and not admin:
    try:
        runsql(
            "revoke all on `%s`.* from `%s`"  % (
            database_name,   
            user))
    except:
        print "revoke failed, ignoring error"
    runsql(
        "grant select on `%s`.* to `%s`"  % (
        database_name,   
        user))
else:
    if admin:
        runsql(
            "grant all privileges on *.* to `%s` identified by '%s'" % (
            user,
            service_password))
    else:
        runsql(
            "grant all on `%s`.* to `%s` identified by '%s'" % (
            database_name,
            user,
            service_password))

hostname = subprocess.check_output(['unit-get','private-address']).strip()

print str(["relation-set",
 "database=%s" % database_name,
 "user=%s" % user,
 "password=%s" % service_password,
 'host=%s' % hostname,
 'slave=%s' % slave])

# Create new database or touch slave.configured file
if slave:
    open(slave_configured_path,'w').close()
else:
    if not broken and not admin:
        runsql("create database `%s` character set utf8" % database_name)

if broken:
    os.unlink(broken_path)

cursor.close()

# Store new values in relation settings.
subprocess.call(
    ["relation-set",
     "database=%s" % database_name,
     "user=%s" % user,
     "password=%s" % service_password,
     'host=%s' % hostname,
     'slave=%s' % slave,])