Skip to content

Commit

Permalink
Refactor so common elements between weewxd and weectl are in one spot
Browse files Browse the repository at this point in the history
  • Loading branch information
tkeffer committed May 4, 2024
1 parent ec6bb71 commit 3018721
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 130 deletions.
74 changes: 4 additions & 70 deletions src/weectllib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,9 @@
"""The 'weectllib' package."""

import datetime
import locale
import logging
import os
import platform
import sys

import configobj

import weecfg
import weeutil.logger
import weeutil.startup
import weewx
from weeutil.weeutil import bcolors


def parse_dates(date=None, from_date=None, to_date=None, as_datetime=False):
Expand Down Expand Up @@ -86,67 +76,11 @@ def dispatch(namespace):
"""All weectl commands come here. This function reads the configuration file, sets up logging,
then dispatches to the actual action.
"""
# Read the configuration file
try:
config_path, config_dict = weecfg.read_config(namespace.config)
except (IOError, configobj.ConfigObjError) as e:
print(f"Error parsing config file: {e}", file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
sys.exit(weewx.CONFIG_ERROR)

print(f"Using configuration file {bcolors.BOLD}{config_path}{bcolors.ENDC}")

try:
# Customize the logging with user settings.
weeutil.logger.setup('weectl', config_dict)
except Exception as e:
print(f"Unable to set up logger: {e}", file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
sys.exit(weewx.CONFIG_ERROR)

# Get a logger. This one will have the requested configuration.
log = logging.getLogger(__name__)
# Announce the startup
log.info("Initializing weectl version %s", weewx.__version__)
log.info("Command line: %s", ' '.join(sys.argv))

# Add USER_ROOT to PYTHONPATH, read user.extensions:
weewx_root, user_module = weeutil.startup.initialize(config_dict)

# Log key bits of information.
log.info("Using Python %s", sys.version)
log.info("Located at %s", sys.executable)
log.info("Platform %s", platform.platform())
log.info("Locale: '%s'", locale.setlocale(locale.LC_ALL))
log.info("Entry path: %s", __file__)
log.info("WEEWX_ROOT: %s", weewx_root)
log.info("Configuration file: %s", config_path)
log.info("User module: %s", user_module)
log.info("Debug: %s", weewx.debug)

# these try/except are because not every os will succeed here
try:
import pwd
euid = pwd.getpwuid(os.geteuid())[0]
log.info("User: %s", euid)
except Exception as ex:
log.info("User unavailable: %s", ex)

try:
import grp
egid = grp.getgrgid(os.getegid())[0]
log.info("Group: %s", egid)
group_list = os.getgroups()
mygroups = []
for group in group_list:
mygroups.append(grp.getgrgid(group)[0])
mygrouplist = ' '.join(mygroups)
log.info("Groups: %s", mygrouplist)
except Exception as ex:
log.info("Groups unavailable: %s", ex)

config_path, config_dict, log = weeutil.startup.start_app('weectl',
__name__,
namespace.config,
None)
# Note a dry-run, if applicable:
if hasattr(namespace, 'dry_run') and namespace.dry_run:
print("This is a dry run. Nothing will actually be done.")
Expand Down
74 changes: 74 additions & 0 deletions src/weeutil/startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@
import logging
import os.path
import sys
import platform
import locale

import configobj

import weewx
import weecfg
import weeutil.logger
from weeutil.weeutil import bcolors

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -69,3 +78,68 @@ def initialize(config_dict):
log.error("Cannot load user extensions: %s", e)

return config_dict['WEEWX_ROOT'], root_dict['USER_DIR']

def start_app(log_label, log_name, config_option, config_arg):
"""Read the config file and log various bits of information"""

try:
config_path, config_dict = weecfg.read_config(config_option, [config_arg])
except (IOError, configobj.ConfigObjError) as e:
print(f"Error parsing config file: {e}", file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
sys.exit(weewx.CONFIG_ERROR)

print(f"Using configuration file {bcolors.BOLD}{config_path}{bcolors.ENDC}")

# Customize the logging with user settings.
try:
weeutil.logger.setup(log_label, config_dict)
except Exception as e:
print(f"Unable to set up logger: {e}", file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
sys.exit(weewx.CONFIG_ERROR)

# Get a logger. This one will be customized with user settings
logger = logging.getLogger(log_name)
# Announce the startup
logger.info("Initializing %s version %s", log_label, weewx.__version__)
logger.info("Command line: %s", ' '.join(sys.argv))

# Add USER_ROOT to PYTHONPATH, read user.extensions:
weewx_root, user_module = initialize(config_dict)

# Log key bits of information.
logger.info("Using Python: %s", sys.version)
logger.info("Located at: %s", sys.executable)
logger.info("Platform: %s", platform.platform())
logger.info("Locale: '%s'", locale.setlocale(locale.LC_ALL))
logger.info("Entry path: %s", getattr(sys.modules['__main__'], '__file__', 'Unknown'))
logger.info("WEEWX_ROOT: %s", weewx_root)
logger.info("Config file: %s", config_path)
logger.info("User module: %s", user_module)
logger.info("Debug: %s", weewx.debug)

# these try/except are because not every os will succeed here
try:
import pwd
euid = pwd.getpwuid(os.geteuid())[0]
logger.info("User: %s", euid)
except Exception as ex:
logger.info("User unavailable: %s",ex)

try:
import grp
egid = grp.getgrgid(os.getegid())[0]
logger.info("Group: %s", egid)
group_list = os.getgroups()
mygroups = []
for group in group_list:
mygroups.append(grp.getgrgid(group)[0])
mygrouplist = ' '.join(mygroups)
logger.info("Groups: %s", mygrouplist)
except Exception as ex:
logger.info("Groups unavailable: %s", ex)

return config_path, config_dict, logger
64 changes: 4 additions & 60 deletions src/weewxd.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,66 +78,10 @@ def main():
print(epilog, file=sys.stderr)
sys.exit(weewx.CMD_ERROR)

# Read the configuration file
try:
config_path, config_dict = weecfg.read_config(namespace.config_arg,
[namespace.config_option])
except (IOError, configobj.ConfigObjError) as e:
print(f"Error parsing config file: {e}", file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
sys.exit(weewx.CONFIG_ERROR)

# Customize the logging with user settings.
try:
weeutil.logger.setup(namespace.log_label, config_dict)
except Exception as e:
print(f"Unable to set up logger: {e}", file=sys.stderr)
import traceback
traceback.print_exc(file=sys.stderr)
sys.exit(weewx.CONFIG_ERROR)

# Get a logger. This one will have the requested configuration.
log = logging.getLogger(__name__)
# Announce the startup
log.info("Initializing weewxd version %s", weewx.__version__)
log.info("Command line: %s", ' '.join(sys.argv))

# Add USER_ROOT to PYTHONPATH, read user.extensions:
weewx_root, user_module = weeutil.startup.initialize(config_dict)

# Log key bits of information.
log.info("Using Python %s", sys.version)
log.info("Located at %s", sys.executable)
log.info("Platform %s", platform.platform())
log.info("Locale: '%s'", locale.setlocale(locale.LC_ALL))
log.info("Entry path: %s", __file__)
log.info("WEEWX_ROOT: %s", weewx_root)
log.info("Configuration file: %s", config_path)
log.info("User module: %s", user_module)
log.info("Debug: %s", weewx.debug)

# these try/except are because not every os will succeed here
try:
import pwd
euid = pwd.getpwuid(os.geteuid())[0]
log.info("User: %s", euid)
except Exception as ex:
log.info("User unavailable: %s",ex)

try:
import grp
egid = grp.getgrgid(os.getegid())[0]
log.info("Group: %s", egid)
group_list = os.getgroups()
mygroups = []
for group in group_list:
mygroups.append(grp.getgrgid(group)[0])
mygrouplist = ' '.join(mygroups)
log.info("Groups: %s", mygrouplist)
except Exception as ex:
log.info("Groups unavailable: %s", ex)

config_path, config_dict, log = weeutil.startup.start_app(namespace.log_label,
__name__,
namespace.config_option,
namespace.config_arg)
# If no command line --loop-on-init was specified, look in the config file.
if not namespace.loop_on_init:
loop_on_init = to_bool(config_dict.get('loop_on_init', False))
Expand Down

0 comments on commit 3018721

Please sign in to comment.