Skip to content

Commit

Permalink
Merge pull request #2 from GoogleCloudPlatform/use_argparse
Browse files Browse the repository at this point in the history
Replacing absl flags and logging.
  • Loading branch information
halleysouza authored Nov 24, 2022
2 parents 1fd241b + 9af1a6e commit 3d5ab86
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 56 deletions.
64 changes: 36 additions & 28 deletions gce_rescue/bin/rescue.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,44 +17,55 @@
""" Main script to be used to set/reset rescue mode. """

from datetime import datetime
import argparse
import logging

from absl import app, flags, logging
from gce_rescue import messages
from gce_rescue.rescue import Instance
from gce_rescue.tasks.actions import call_tasks
from gce_rescue.utils import log_to_file, read_input

FLAGS = flags.FLAGS
flags.DEFINE_string('project', None, 'The project-id that has the instance.')
flags.DEFINE_string('zone', None, 'Zone where the instance is created.')
flags.DEFINE_string('name', None, 'Instance name.')
flags.DEFINE_boolean('debug', False, 'Print to the log file in debug level.')
flags.DEFINE_boolean('force', False, 'Don\'t ask for confirmation.')
flags.mark_flag_as_required('zone')
flags.mark_flag_as_required('name')


def main(argv):
del argv

if FLAGS.debug:
from gce_rescue.utils import read_input, set_logging

def usage():
""" Print usage options. """
parser = argparse.ArgumentParser(description='GCE Rescue v0.0.2 - Set/Reset\
GCE instances to boot in rescue mode.')
parser.add_argument('-p', '--project',
help='The project-id that has the instance.')
parser.add_argument('-z', '--zone', help='Zone where the instance \
is created.',
required=True)
parser.add_argument('-n', '--name', help='Instance name.', required=True)
parser.add_argument('-d', '--debug', action='store_true',
help='Print to the log file in debug leve')
parser.add_argument('-f', '--force', action='store_true',
help='Don\'t ask for confirmation.')

return parser

def main():
""" Main script function. """
parser = usage()
args = parser.parse_args()

if args.debug:
log_level = 'DEBUG'
else:
log_level = 'INFO'
log_to_file(log_file_name=FLAGS.name, level=log_level)

set_logging(vm_name=args.name, level=log_level)

parse_kwargs = {
'zone': FLAGS.zone,
'name': FLAGS.name,
'zone': args.zone,
'name': args.name,
}

if FLAGS.project:
parse_kwargs['project'] = FLAGS.project
if args.project:
parse_kwargs['project'] = args.project

vm = Instance(test_mode=False, **parse_kwargs)
rescue_on = vm.rescue_mode_status['rescue-mode']
if not rescue_on:
if not FLAGS.force:
if not args.force:
info = (f'This option will boot the instance {vm.name} in '
'RESCUE MODE. \nIf your instance is running it will be rebooted. '
'\nDo you want to continue [y/N]: ')
Expand All @@ -70,7 +81,7 @@ def main(argv):
rescue_ts = vm.rescue_mode_status['ts']
rescue_date = datetime.fromtimestamp(int(rescue_ts))

if not FLAGS.force:
if not args.force:
info = (f'The instance \"{vm.name}\" is currently configured '
f'to boot as rescue mode since {rescue_date}.\nWould you like to'
' restore the original configuration ? [y/N]: ')
Expand All @@ -83,9 +94,6 @@ def main(argv):
call_tasks(vm=vm, action=action)
print(msg)

def run_script():
""" Function to be called as script. """
app.run(main)

if __name__ == '__main__':
run_script()
main()
4 changes: 2 additions & 2 deletions gce_rescue/tasks/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
""" List of ordered tasks to be executed when set/reset VM rescue mode. """

from typing import Dict
from absl import logging
import logging

from gce_rescue.rescue import Instance
from gce_rescue.tasks.disks import (
Expand All @@ -33,7 +33,7 @@
)
from gce_rescue.utils import Tracker

_logger = logging
_logger = logging.getLogger(__name__)

def _list_tasks(vm: Instance, action: str) -> Dict:
""" List tasks, by order, per operation
Expand Down
4 changes: 2 additions & 2 deletions gce_rescue/tasks/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@

from gce_rescue.utils import wait_for_operation
from typing import Dict, List
from absl import logging
import logging

_logger = logging
_logger = logging.getLogger(__name__)

def backup_metadata_items(data: Dict) -> List:
""" Returns the "items" content (ssh-keys, scripts, etc) to be restored
Expand Down
4 changes: 2 additions & 2 deletions gce_rescue/tasks/disks.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
""" Compilations of all disks tasks related. """

from typing import Dict
from absl import logging
import logging

import googleapiclient.errors

from gce_rescue.utils import wait_for_operation
from gce_rescue.tasks.backup import backup
from gce_rescue.multitasks import Handler

_logger = logging
_logger = logging.getLogger(__name__)

def _create_rescue_disk(vm, source_disk: str) -> Dict:
""" Create new temporary rescue disk based on source_disk.
Expand Down
4 changes: 2 additions & 2 deletions gce_rescue/tasks/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
from gce_rescue.config import get_config
from gce_rescue.utils import wait_for_operation, wait_for_os_boot
from typing import Dict
from absl import logging
import logging

_logger = logging
_logger = logging.getLogger(__name__)

def set_metadata(vm) -> Dict:
"""Configure Instance custom metadata.
Expand Down
4 changes: 2 additions & 2 deletions gce_rescue/tasks/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@

from gce_rescue.rescue import Instance
from gce_rescue.utils import wait_for_operation
from absl import logging
import logging

_logger = logging
_logger = logging.getLogger(__name__)

def start_instance(vm: Instance) -> str:
"""Start instance."""
Expand Down
20 changes: 12 additions & 8 deletions gce_rescue/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@
from time import time, sleep
from typing import Dict
from gce_rescue.config import get_config
from absl import logging
import logging
import multiprocessing
import sys
import json

_logger = logging
_logger = logging.getLogger(__name__)

class Tracker():
""" Track tasks using multiprocessing and print progress bar. """
Expand Down Expand Up @@ -187,14 +187,18 @@ def wait_for_os_boot(vm: googleapiclient.discovery.Resource) -> bool:
return False


def log_to_file(log_file_name: str, level: str = 'INFO') -> None:
""" Set logfile and verbosity """
def set_logging(vm_name: str, level: str ='INFO') -> None:
""" Set logfile and verbosity. """

log_level = getattr(logging, level.upper())
logging.set_verbosity(log_level)
logging.use_absl_handler()
logging.get_absl_handler().use_absl_log_file(log_file_name, './')

file_name = f'{vm_name}.log'
logging.basicConfig(
filename=file_name,
filemode='a',
format='%(asctime)s,%(msecs)03d %(levelname)-8s [%(filename)s:%(lineno)d]\
%(message)s',
datefmt='%Y-%m-%d:%H:%M:%S',
level=log_level)

def read_input(msg: str) -> None:
"""Read user input if --force is not provided."""
Expand Down
20 changes: 10 additions & 10 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,18 @@
include_package_data = True,
entry_points={
'console_scripts': [
'gce-rescue = gce_rescue.bin.rescue:run_script',
'gce-rescue = gce_rescue.bin.rescue:main',
],
},
classifiers = [
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Topic :: System :: Boot",
"Topic :: System :: Boot :: Init",
"Topic :: System :: Recovery Tools",
"Topic :: System :: System Shells",
"Topic :: System :: Systems Administration",
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Topic :: System :: Boot',
'Topic :: System :: Boot :: Init',
'Topic :: System :: Recovery Tools',
'Topic :: System :: System Shells',
'Topic :: System :: Systems Administration',
]
)

0 comments on commit 3d5ab86

Please sign in to comment.