-
Notifications
You must be signed in to change notification settings - Fork 777
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
dbctl for dqlite backup and restore #1435
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
73a5e46
dbctl for dqlite backup and restore
ktsakalozos 6f4517f
Fix imports
ktsakalozos 2c58eb7
Adding basic tests
ktsakalozos b4900e8
Adding test-cluster fixes
ktsakalozos 5cb6b3b
More fixes on tests
ktsakalozos 4d716c9
Better help description
ktsakalozos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
#!/usr/bin/env bash | ||
|
||
set -eu | ||
|
||
export PATH="$SNAP/usr/sbin:$SNAP/usr/bin:$SNAP/sbin:$SNAP/bin:$PATH" | ||
ARCH="$($SNAP/bin/uname -m)" | ||
export IN_SNAP_LD_LIBRARY_PATH="$SNAP/lib:$SNAP/usr/lib:$SNAP/lib/$ARCH-linux-gnu:$SNAP/usr/lib/$ARCH-linux-gnu" | ||
export PYTHONNOUSERSITE=false | ||
|
||
source $SNAP/actions/common/utils.sh | ||
|
||
exit_if_no_permissions | ||
|
||
LD_LIBRARY_PATH=$IN_SNAP_LD_LIBRARY_PATH ${SNAP}/usr/bin/python3 ${SNAP}/scripts/wrappers/dbctl.py $@ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
#!/usr/bin/python3 | ||
import os | ||
import argparse | ||
|
||
import tempfile | ||
import datetime | ||
import subprocess | ||
import tarfile | ||
import os.path | ||
|
||
from common.utils import ( | ||
exit_if_no_permission, | ||
is_cluster_locked, | ||
is_ha_enabled, | ||
) | ||
|
||
|
||
def kine_exists(): | ||
""" | ||
Check the existence of the kine socket | ||
:return: True if the kine socket exists | ||
""" | ||
kine_socket = "/var/snap/microk8s/current/var/kubernetes/backend/kine.sock" | ||
return os.path.exists(kine_socket) | ||
|
||
|
||
def generate_backup_name(): | ||
""" | ||
Generate a filename based on the current time and date | ||
:return: a generated filename | ||
""" | ||
now = datetime.datetime.now() | ||
return "backup-{}".format(now.strftime("%Y-%m-%d-%H-%M-%S")) | ||
|
||
|
||
def run_command(command): | ||
""" | ||
Run a command while printing the output | ||
:param command: the command to run | ||
:return: the return code of the command | ||
""" | ||
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) | ||
while True: | ||
output = process.stdout.readline() | ||
if (not output or output == '') and process.poll() is not None: | ||
break | ||
if output: | ||
print(output.decode().strip()) | ||
rc = process.poll() | ||
return rc | ||
|
||
|
||
def backup(fname=None, debug=False): | ||
""" | ||
Backup the database to a provided file | ||
:param fname_tar: the tar file | ||
:param debug: show debug output | ||
""" | ||
snap_path = os.environ.get('SNAP') | ||
snapdata_path = os.environ.get('SNAP_DATA') | ||
# snap_path = '/snap/microk8s/current' | ||
# snapdata_path = '/var/snap/microk8s/current' | ||
|
||
if not fname: | ||
fname = generate_backup_name() | ||
if fname.endswith('.tar.gz'): | ||
fname = fname[:-7] | ||
fname_tar = '{}.tar.gz'.format(fname) | ||
|
||
with tempfile.TemporaryDirectory() as tmpdirname: | ||
backup_cmd = '{}/bin/migrator --mode backup-dqlite --db-dir {}'.format( | ||
snap_path, "{}/{}".format(tmpdirname, fname) | ||
) | ||
if debug: | ||
backup_cmd = "{} {}".format(backup_cmd, "--debug") | ||
try: | ||
rc = run_command(backup_cmd) | ||
if rc > 0: | ||
print("Backup process failed. {}".format(rc)) | ||
exit(1) | ||
with tarfile.open(fname_tar, "w:gz") as tar: | ||
tar.add( | ||
"{}/{}".format(tmpdirname, fname), | ||
arcname=os.path.basename("{}/{}".format(tmpdirname, fname)), | ||
) | ||
|
||
target_file = '{}/var/tmp/{}'.format(snapdata_path, fname_tar) | ||
print("The backup is: {}".format(fname_tar)) | ||
except subprocess.CalledProcessError as e: | ||
print("Backup process failed. {}".format(e)) | ||
exit(2) | ||
|
||
|
||
def restore(fname_tar, debug=False): | ||
""" | ||
Restore the database from the provided file | ||
:param fname_tar: the tar file | ||
:param debug: show debug output | ||
""" | ||
snap_path = os.environ.get('SNAP') | ||
# snap_path = '/snap/microk8s/current' | ||
with tempfile.TemporaryDirectory() as tmpdirname: | ||
with tarfile.open(fname_tar, "r:gz") as tar: | ||
tar.extractall(path=tmpdirname) | ||
if fname_tar.endswith('.tar.gz'): | ||
fname = fname_tar[:-7] | ||
else: | ||
fname = fname_tar | ||
fname = os.path.basename(fname) | ||
restore_cmd = '{}/bin/migrator --mode restore-to-dqlite --db-dir {}'.format( | ||
snap_path, "{}/{}".format(tmpdirname, fname) | ||
) | ||
if debug: | ||
restore_cmd = "{} {}".format(restore_cmd, "--debug") | ||
try: | ||
rc = run_command(restore_cmd) | ||
if rc > 0: | ||
print("Restore process failed. {}".format(rc)) | ||
exit(3) | ||
except subprocess.CalledProcessError as e: | ||
print("Restore process failed. {}".format(e)) | ||
exit(4) | ||
|
||
|
||
if __name__ == '__main__': | ||
exit_if_no_permission() | ||
is_cluster_locked() | ||
|
||
if not kine_exists() or not is_ha_enabled(): | ||
print("Please ensure the kubernetes apiserver is running and HA is enabled.") | ||
exit(10) | ||
|
||
# initiate the parser with a description | ||
parser = argparse.ArgumentParser( | ||
description="backup and restore the Kubernetes datastore.", prog='microk8s dbctl' | ||
) | ||
parser.add_argument('--debug', action='store_true', help='print debug output') | ||
commands = parser.add_subparsers(title='commands', help='backup and restore operations') | ||
restore_parser = commands.add_parser("restore") | ||
restore_parser.add_argument('backup-file', help='name of file with the backup') | ||
backup_parser = commands.add_parser("backup") | ||
backup_parser.add_argument('-o', metavar='backup-file', help='output filename') | ||
args = parser.parse_args() | ||
|
||
if 'backup-file' in args: | ||
fname = vars(args)['backup-file'] | ||
print("Restoring from {}".format(fname)) | ||
restore(fname, args.debug) | ||
elif 'o' in args: | ||
print("Backing up the datastore") | ||
backup(vars(args)['o'], args.debug) | ||
else: | ||
parser.print_help() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If you have time, can you please consider which plugs would be needed for strict?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we would need this https://snapcraft.io/docs/personal-files-interface to be able to write the backup file.
This is only by looking the code. I did not run any tests.