github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/acceptancetests/repository/xenial/mysql/hooks/db-admin-relation-joined (about)

     1  #!/usr/bin/env python
     2  
     3  from common import *
     4  
     5  import urllib
     6  import subprocess
     7  import os
     8  import sys
     9  import string
    10  import random
    11  import pickle
    12  
    13  cursor = get_db_cursor()
    14  
    15  admin = os.path.basename(sys.argv[0]) == 'db-admin-relation-joined'
    16  
    17  def runsql(sql):
    18  	print "[%s]" % sql
    19  	cursor.execute(sql)
    20  
    21  runsql(
    22      "grant replication client on *.* to `%s` identified by '%s'"  % (
    23      user,
    24      service_password))
    25  
    26  if slave and not admin:
    27      try:
    28          runsql(
    29              "revoke all on `%s`.* from `%s`"  % (
    30              database_name,   
    31              user))
    32      except:
    33          print "revoke failed, ignoring error"
    34      runsql(
    35          "grant select on `%s`.* to `%s`"  % (
    36          database_name,   
    37          user))
    38  else:
    39      if admin:
    40          runsql(
    41              "grant all privileges on *.* to `%s` identified by '%s'" % (
    42              user,
    43              service_password))
    44      else:
    45          runsql(
    46              "grant all on `%s`.* to `%s` identified by '%s'" % (
    47              database_name,
    48              user,
    49              service_password))
    50  
    51  hostname = subprocess.check_output(['unit-get','private-address']).strip()
    52  
    53  print str(["relation-set",
    54   "database=%s" % database_name,
    55   "user=%s" % user,
    56   "password=%s" % service_password,
    57   'host=%s' % hostname,
    58   'slave=%s' % slave])
    59  
    60  # Create new database or touch slave.configured file
    61  if slave:
    62      open(slave_configured_path,'w').close()
    63  elif not broken and not admin:
    64    # Find existing databases
    65    cursor.execute("show databases")
    66    databases = [i[0] for i in cursor.fetchall()]
    67    if database_name in databases:
    68        print "database exists already"
    69    else:
    70        if not broken and not admin:
    71            runsql("create database `%s` character set utf8" % database_name)
    72            with open(database_name_file, 'w') as dbname:
    73                dbname.write(database_name)
    74  
    75  if broken:
    76      os.unlink(broken_path)
    77  
    78  cursor.close()
    79  
    80  # Store new values in relation settings.
    81  subprocess.call(
    82      ["relation-set",
    83       "database=%s" % database_name,
    84       "user=%s" % user,
    85       "password=%s" % service_password,
    86       'host=%s' % hostname,
    87       'slave=%s' % slave,])