Skip to content

Commit

Permalink
fix makemysql so that easywp might work (#154)
Browse files Browse the repository at this point in the history
This commit consists 18 commits in total, earliest one dating back to May 2020, intended to fix chain reactions caused by #129.
This commit:
1. Changed `makemysql-real`, allowing it to output only the password and nothing else if a specific argument is given
2. Changed `makemysql`, allowing it to correctly fetch password printed by `makemysql-real`, allowing it to be silent if no wordpress installation is found, allowing it to not change wordpress password if a specific argument is given, and allowing it to output only the password and nothing else if a specific argument is given.
3. Changed `easywp` so that it is compatible with the updated `makemysql`.
Hopefully, this will not break ocf infra.

18 commits:
* rewrote so that it might work
* idk wat autopep8 changed/suggested i followed its advice
* forgot to add the messages
* Added argument parsing and non-human-friendly output
* Squashed two commits
redirected some stuff to stderr
fix stupid mistakes for makemysql-real
* updated all three scripts so that they support some silent arguments and make things fancy but they might not work as I didn't test it
* fix stupid bugs made in 3cac9d4
* fix pre-commit problem made in 3cac9d4
* Wrapper for if silent
* Fixed a stupid logical mistake and added some stuff in bash scripts; did not run pre commit yet
* Applied @kpengboy's suggestions
1. Changed --silent to --quiet
2. Disable `set -e` at places where error-handling exists
3. Added some more instructions
4. Removed some redundant stuff, but idk if this will blow stuff up
* Bug: if quite is specified, do not ask if user wants to proceed.
* Indentation Errors
* Fix, silent should be global variable
* Fixed some bugs in easywp
* fix comment
* fix so precommit pass
* more to squash
  • Loading branch information
axmmisaka authored and Justin Zhang committed Mar 12, 2022
1 parent 1f7a1d6 commit 1acf9bd
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 39 deletions.
11 changes: 9 additions & 2 deletions makeservices/easywp
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,18 @@ fi

# Get SQL password
echo "Resetting database password..."
sqlpass=$(echo "yes" | makemysql | tail -n 1 | grep -Po '(?<=: )([0-9a-zA-Z]){24,}$')
if [[ -z "$sqlpass" ]]; then
# Do not exit immediately if makemysql fails, as we need to display some error message...
set +e
sqlpass=$(makemysql --quiet)
# I don't know if this will work... Just make sure no abnormal exit code first!
if [ $? ] || [[ -z "$sqlpass" ]]; then
echo -e "\\033[31mError:\\033[00m Could not retrieve database password. Run makemysql to see the issue."
exit 1
fi
# Only have the aforementioned behaviour when running makemysql
# Note also technically if should be below this set statement
# but set messes up with $? as well...
set -e
echo "SQL set up and the password can be found in wp-config.php ..."

# Install WordPress and create config file
Expand Down
52 changes: 48 additions & 4 deletions makeservices/makemysql
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,52 @@ if [[ "$(hostname)" != "tsunami" && "$(hostname)" != "dev-tsunami" ]]; then
exit 1
fi

PASS=$(sudo -u mysql /opt/share/utils/makeservices/makemysql-real | tee /dev/tty | tail -n 1 | grep -Po '(?<=: )([0-9a-zA-Z]){24,}$')
IGNORE_WP=false
QUIET=false

echo 'Changing WordPress database password'
cd ~/public_html/
wp config set DB_PASSWORD "$PASS" > /dev/null
# Parse arguments down below
while (( "$#" )); do
case "$1" in
-i|--ignore-wp)
IGNORE_WP=true
shift
;;
-q|--quiet)
QUIET=true
shift
;;
-*)
# Output to stderr
echo "Error: Unsupported flag $1" >&2
exit 1
;;
esac
done

# The correctness of this line relies on the fact that
# makemysql-real will output the new password ONLY on the
# last line. The --quiet will also make sure it only output the password...
PASS=$(sudo -u mysql /opt/share/utils/makeservices/makemysql-real --quiet)

if [ $? ] ; then
echo 'makemysql-real did not exit properly.'
echo 'Run "sudo -u mysql /opt/share/utils/makeservices/makemysql-real" for a more verbose output.'
echo 'Additionally, you may contact staff members for help. This script will stop.'
exit 1
fi

# Check if wp is installed, wp-cli cannot be used as it verifies DB password as well
# And change password if installed with easywp
# Use --ignore-wp flag to skip this process
if ! $IGNORE_WP && [ -f "$HOME/public_html/wp-config.php" ] ; then
if ! $QUIET; then
echo "WordPress installation detected, changing WordPress mysql password for you."
fi
wp config set DB_PASSWORD "$PASS" --path="$HOME/public_html" > /dev/null 2>&1
fi

if $QUIET; then
echo "$PASS"
else
echo "Your MySQL database password is: $PASS"
fi
80 changes: 47 additions & 33 deletions makeservices/makemysql-real
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ MYSQL_HOST = 'mysql.ocf.berkeley.edu'

PW_LENGTH = 24

quiet = False


def read_config():
"""Fetches the MySQL hostname and root password from the config in
Expand All @@ -47,6 +49,11 @@ def read_config():
return mysql_host, mysql_root_pw


def print_if_not_quiet(*args, **kwargs):
if not quiet:
print(*args, **kwargs)


def intro_prompt():
print(dedent(
"""
Expand All @@ -69,6 +76,8 @@ def intro_prompt():


def main():
# Without this quiet below will be local variable
global quiet
try:
username = os.environ.get('SUDO_USER')

Expand All @@ -78,43 +87,45 @@ def main():
# Read config file.
mysql_host, mysql_root_pw = read_config()

# Added a simple and stupid argument parsing so that other scripts can use it without tunneling in yes.
if len(sys.argv) > 1 and sys.argv[1] in ['-q', '--quiet']:
quiet = True
# Check whether the script should proceed.
if not intro_prompt():
print('>>> Aborted by user request.')
return

if not quiet:
if not intro_prompt():
print_if_not_quiet('>>> Aborted by user request.', file=sys.stderr)
return
# Connect to the MySQL server.
try:
print('>>> Connecting to MySQL database server...')
print_if_not_quiet('>>> Connecting to MySQL database server...')
connection = MySQLdb.connect(host=mysql_host,
user='root',
passwd=mysql_root_pw)
except MySQLdb.MySQLError:
print('>>> Error: Failed to connect to MySQL server.')
raise
raise ConnectionError('>>> Error: Failed to connect to MySQL server.')

# Check if the database already exists.
try:
print(">>> Checking if database '{}' already exists...".format(username))
print_if_not_quiet(">>> Checking if database '{}' already exists...".format(username))
connection.select_db(username)

# The database already exists, so skip the creation step.
print('yes.')
print_if_not_quiet('yes.')
db_create = False
print(dedent("""
The MySQL database '{}' already exists.
The database password will be reset.
print_if_not_quiet(dedent("""
The MySQL database '{}' already exists.
The database password will be reset.
If you are unsure how to access or use your database, please visit
If you are unsure how to access or use your database, please visit
https://www.ocf.berkeley.edu/docs/services/mysql/
https://www.ocf.berkeley.edu/docs/services/mysql/
If you run into trouble trying to use your database, contact us at
If you run into trouble trying to use your database, contact us at
[email protected]
""").format(username))
[email protected]
""").format(username))
except MySQLdb.OperationalError:
print('no.')
print_if_not_quiet('no.')
db_create = True

# Add or update user database privileges.
Expand All @@ -128,37 +139,39 @@ def main():
# Result should be "Query OK, 0 rows affected",
# but we'll assume no exception means success.
except MySQLdb.MySQLError:
print('>>> Error: Failed to grant database privileges.')
raise
raise ConnectionError('>>> Error: Failed to grant database privileges.')

# Create new database, if necessary.
if db_create:
try:
print(">>> Creating new database '{}'...".format(username))
print_if_not_quiet(">>> Creating new database '{}'...".format(username))
query = CREATE_QUERY.format(username)
connection.query(query)
connection.store_result()
# Result should be "Query OK, 1 row affected",
# but we'll assume no exception means success.
except MySQLdb.MySQLError:
print('>>> Error: Failed to create database.')
raise
raise IOError('>>> Error: Failed to create database.')

# Database is ready for use.
if db_create:
print(dedent("""
Your MySQL database has been created.
print_if_not_quiet(dedent("""
Your MySQL database has been created.
For instructions on accessing and using your database, please visit
For instructions on accessing and using your database, please visit
https://www.ocf.berkeley.edu/docs/services/mysql/
https://www.ocf.berkeley.edu/docs/services/mysql/
If you run into trouble trying to use your database, contact us at
If you run into trouble trying to use your database, contact us at
[email protected]
"""))

[email protected]
"""))
print_if_not_quiet('>>> Your MySQL database password is: ')

print('>>> Your MySQL database password is: {}'.format(userpass))
# This line to be printed, no matter quiet or not.
# The userpass will always be on the last line.
print(userpass)
except Exception as ex:
send_problem_report(dedent(
"""\
Expand All @@ -171,8 +184,9 @@ def main():
"""
A fatal error was encountered during program execution.
OCF staff have been notified of the problem.
"""
))
Error for staff: {}: {}.
""".format(ex.__class__.__name__, ex)
), file=sys.stderr)
sys.exit(1)


Expand Down

0 comments on commit 1acf9bd

Please sign in to comment.