Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix makemysql so that easywp might work #154

Merged
merged 18 commits into from
Oct 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should these be if [[ $? -ne 0 ]]? Since we are checking if the return code was abnormal (0 is success)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see you inverted this in 051e0387350c67f0fd6cf976da25ad8511ad46bb to make precommit pass. What was the issue?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know why but pre-commit say I should use if [ $? ] instead of if [[ $? -ne 0 ]] so I accepted this recommendation

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

help@ocf.berkeley.edu
""").format(username))
help@ocf.berkeley.edu
""").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
help@ocf.berkeley.edu
"""))

help@ocf.berkeley.edu
"""))
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