Merge remote-tracking branch 'fonfon/pagekite-augeas-new'

This commit is contained in:
James Valleroy committed 2015-05-16 10:35:58 -04:00
commit 44b045fef7
21 files changed
+1402 -524

No files matched your search

+257
View File
@@ -0,0 +1,257 @@
#!/usr/bin/python2
# -*- mode: python -*-
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Configuration helper for Plinth PageKite interface
Unfortunately there is no python3 package for augeas yet
"""
import argparse
import augeas
import json
import os
import subprocess
import util
from pagekite_util import SERVICE_PARAMS, convert_service_to_string, \
get_augeas_servicefile_path, load_service, CONF_PATH
aug = augeas.Augeas()
PATHS = {
'service_on': os.path.join(CONF_PATH, '*', 'service_on', '*'),
'kitename': os.path.join(CONF_PATH, '10_account.rc', 'kitename'),
'kitesecret': os.path.join(CONF_PATH, '10_account.rc', 'kitesecret'),
'abort_not_configured': os.path.join(CONF_PATH, '10_account.rc',
'abort_not_configured'),
'defaults': os.path.join(CONF_PATH, '20_frontends.rc', 'defaults'),
'frontend': os.path.join(CONF_PATH, '20_frontends.rc', 'frontend'),
}
def parse_arguments():
"""Return parsed command line arguments as dictionary"""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subcommand', help='Sub command')
# Enable/disable the pagekite service
subparsers.add_parser('is-running', help='Get whether PakeKite is running')
subparsers.add_parser('start-and-enable', help='Enable PageKite service')
subparsers.add_parser('stop-and-disable', help='Disable PageKite service')
subparsers.add_parser('restart', help='Restart PageKite service')
# Frontend
subparsers.add_parser('get-frontend', help='Get pagekite frontend')
set_frontend = subparsers.add_parser('set-frontend',
help='Set pagekite frontend')
set_frontend.add_argument('url', help='frontend url')
# Kite details (name + secret)
subparsers.add_parser('get-kite',
help='Get configured kite name and secret')
set_kite = subparsers.add_parser('set-kite',
help='Configure kite name and its secret')
set_kite.add_argument('--kite-name',
help='Name of the kite (eg: mybox.pagekite.me)')
set_kite.add_argument('--kite-secret', help='Secret for the kite')
# Add/remove pagekite services (service_on entries)
subparsers.add_parser('get-services', help='Get list of enabled services')
add_service = subparsers.add_parser('add-service',
help='Add a pagekite service')
add_service.add_argument('--service', help='json service dictionary')
remove_service = subparsers.add_parser('remove-service',
help='Remove a pagekite service')
remove_service.add_argument('--service', help='json service dictionary')
return parser.parse_args()
def _service(action):
"""Start/stop/restart the pagekite service"""
error = subprocess.call(['service', 'pagekite', action])
if error:
raise Exception('Unable to %s PageKite server' % action)
def subcommand_is_running(_):
"""Print whether pagekite is enabled (yes or no)"""
print 'yes' if util.service_is_running('pagekite') else 'no'
def subcommand_restart(_):
"""Restart the pagekite service"""
_service('restart')
print 'restarted'
def subcommand_start_and_enable(_):
aug.remove(PATHS['abort_not_configured'])
aug.save()
# 'start' alone sometimes fails, even if the service is not running
_service('restart')
print 'enabled'
def subcommand_stop_and_disable(_):
_service('stop')
aug.set(PATHS['abort_not_configured'], '')
aug.save()
print 'disabled'
def subcommand_get_frontend(_):
"""Get pagekite frontend url"""
if aug.match(PATHS['defaults']):
print "pagekite.net"
else:
url = aug.get(PATHS['frontend'])
print url if url else ""
def subcommand_set_frontend(arguments):
"""Set pagekite frontend url, taking care of defaults and pagekite.net"""
if arguments.url in ('pagekite.net', 'defaults', 'default'):
enable_pagekitenet_frontend()
else:
aug.remove(PATHS['defaults'])
aug.set(PATHS['frontend'], arguments.url)
aug.save()
def enable_pagekitenet_frontend():
"""Enable using default pageket.net frontend
This disables any other frontends.
"""
aug.set(PATHS['defaults'], '')
aug.remove(PATHS['frontend'])
aug.save()
print "enabled"
def subcommand_get_services(arguments):
""" lists all available (enabled) services """
for match in aug.match(PATHS['service_on']):
service = dict([(param, aug.get(os.path.join(match, param)))
for param in SERVICE_PARAMS])
print json.dumps(service)
def subcommand_remove_service(arguments):
"""Searches and removes the service(s) that match all given parameters"""
service = load_service(arguments.service)
paths = get_existing_service_paths(service)
# TODO: theoretically, everything to do here is:
# [aug.remove(path) for path in paths]
# but augeas won't let you save the changed files and doesn't say why
for path in paths:
filepath = convert_augeas_path_to_filepath(path)
service_found = False
with open(filepath, 'r') as file:
lines = file.readlines()
for i, line in enumerate(lines):
if line.startswith('service_on') and \
all(param in line for param in service.values()):
lines[i] = ""
service_found = True
break
if service_found:
with open(filepath, 'w') as file:
file.writelines(lines)
# abort to only allow deleting one service
break
_service('restart')
def get_existing_service_paths(service):
"""Return paths of existing services that match the given service params"""
# construct an augeas query path with patterns like:
# */service_on/*[protocol='http']
path = PATHS['service_on']
for param, value in service.items():
path += "[%s='%s']" % (param, value)
return aug.match(path)
def subcommand_add_service(arguments):
"""Add one service"""
service = load_service(arguments.service)
if get_existing_service_paths(service):
msg = "Service with the parameters %s already exists"
raise RuntimeError(msg % service)
root = get_new_service_path(service['protocol'])
# TODO: after adding a service, augeas fails writing the config;
# so add the service_on entry manually instead
path = convert_augeas_path_to_filepath(root)
with open(path, 'a') as servicefile:
line = "\nservice_on = %s\n" % convert_service_to_string(service)
servicefile.write(line)
_service('restart')
def convert_augeas_path_to_filepath(augpath, prefix='/files',
suffix='service_on'):
"""Convert an augeas service_on path to the actual file path"""
if augpath.startswith(prefix):
augpath = augpath.replace(prefix, "", 1)
index = augpath.rfind(suffix)
if index:
augpath = augpath[:index]
return augpath.rstrip('/')
def get_new_service_path(protocol):
"""Get the augeas path of a new service for a protocol
This takes care of existing services using a /service_on/*/ query"""
root = get_augeas_servicefile_path(protocol)
new_index = len(aug.match(root + '/*')) + 1
return os.path.join(root, str(new_index))
def subcommand_get_kite(_):
"""Print details of the currently configured kite"""
kitename = aug.get(PATHS['kitename'])
kitesecret = aug.get(PATHS['kitesecret'])
print kitename if kitename else ''
print kitesecret if kitesecret else ''
def subcommand_set_kite(arguments):
"""Set details of the kite"""
aug.set(PATHS['kitename'], arguments.kite_name)
aug.set(PATHS['kitesecret'], arguments.kite_secret)
aug.save()
def main():
"""Parse arguments and perform all duties"""
arguments = parse_arguments()
subcommand = arguments.subcommand.replace('-', '_')
subcommand_method = globals()['subcommand_' + subcommand]
subcommand_method(arguments)
if __name__ == "__main__":
main()
-290
View File
@@ -1,290 +0,0 @@
#!/usr/bin/python3
# -*- mode: python -*-
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Configuration helper for Plint PageKite inteface
TODO: Use augeas for manipulating /etc/pagekite.d/* files
"""
# Disable warning about invalid module name # pylint: disable-msg=C0103
import argparse
import os
import re
import subprocess
CONFIG_DIR = '/etc/pagekite.d'
SERVICE_FILE_MAP = {
'http': {
'file': '80_httpd.rc',
'match': 'http:',
'line': 'service_on = http:@kitename : localhost:80 : @kitesecret'},
'ssh': {
'file': '80_sshd.rc',
'match': 'raw/22:',
'line': 'service_on = raw/22:@kitename : localhost:22 : @kitesecret'}}
def parse_arguments():
"""Return parsed command line arguments as dictionary"""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subcommand', help='Sub command')
# Start PageKite
subparsers.add_parser('start', help='Start PageKite service')
# Stop PageKite
subparsers.add_parser('stop', help='Stop PageKite service')
# Get status
subparsers.add_parser('get-status', help='Get whether PakeKite is enabled')
# Set status
set_status = subparsers.add_parser('set-status',
help='Enable/disable PageKite')
set_status.add_argument('enable', choices=['enable', 'disable'])
# Get kite details
subparsers.add_parser('get-kite',
help='Get configured kite name and secret')
# Set kite details
set_kite = subparsers.add_parser('set-kite',
help='Configure kite name and its secret')
set_kite.add_argument('--kite-name',
help='Name of the kite (eg: mybox.pagekite.me)')
set_kite.add_argument('--kite-secret', help='Secret for the kite')
# Get service status
get_service = subparsers.add_parser('get-service-status',
help='Get whether service is enabled')
get_service.add_argument('service', choices=['http', 'ssh'])
# Set service status
set_service = subparsers.add_parser('set-service-status',
help='Enable/disable a service')
set_service.add_argument('service', choices=['http', 'ssh'])
set_service.add_argument('enable', choices=['enable', 'disable'])
return parser.parse_args()
def subcommand_start(_):
"""Start PageKite service"""
status = subprocess.call(['service', 'pagekite', 'start'])
if status:
raise Exception('Unable to start PageKite server')
def subcommand_stop(_):
"""Stop PageKite service"""
status = subprocess.call(['service', 'pagekite', 'stop'])
if status:
raise Exception('Unable to stop PageKite server')
def subcommand_get_status(_):
"""Print status of the pagekite service"""
is_enabled = is_pagekite_enabled()
print('enabled' if is_enabled else 'disabled')
def is_pagekite_enabled():
"""Return if pagekite is enabled"""
service_file_path = os.path.join(CONFIG_DIR, '10_account.rc')
try:
with open(service_file_path, 'r') as file_object:
for line in file_object:
regex = r'^[ \t]*abort_not_configured'
if re.match(regex, line):
return False
except Exception:
return True
return True
def subcommand_set_status(arguments):
"""Enable/disable the pagekite service"""
enable = arguments.enable == 'enable'
is_enabled = is_pagekite_enabled()
if enable and is_enabled:
print('already enabled')
return
if not enable and not is_enabled:
print('already disabled')
return
if enable:
pagekite_enable()
print('enabled')
else:
pagekite_disable()
print('disabled')
def pagekite_enable():
"""Enable the pagekite daemon"""
file_path = os.path.join(CONFIG_DIR, '10_account.rc')
file_path_new = os.path.join(CONFIG_DIR, '10_account.rc.new')
with open(file_path, 'r') as read_file_object, \
open(file_path_new, 'w') as write_file_object:
for line in read_file_object:
if not re.match('^[ \t]*abort_not_configured', line):
write_file_object.write(line)
os.rename(file_path_new, file_path)
def pagekite_disable():
"""Disable the pagekite daemon"""
file_path = os.path.join(CONFIG_DIR, '10_account.rc')
with open(file_path, 'a') as file_object:
file_object.write('abort_not_configured\n')
def subcommand_get_kite(_):
"""Print details of the currently configure kite"""
kite_name = ''
kite_secret = ''
file_path = os.path.join(CONFIG_DIR, '10_account.rc')
with open(file_path, 'r') as file_object:
for line in file_object:
match = re.match(r'[ \t]*kitename[ \t]*=[ \t]*(.*)', line)
if match:
kite_name = match.group(1)
continue
match = re.match(r'[ \t]*kitesecret[ \t]*=[ \t]*(.*)', line)
if match:
kite_secret = match.group(1)
continue
print(kite_name)
print(kite_secret)
def subcommand_set_kite(arguments):
"""Set details of the kite"""
kite_name = arguments.kite_name
kite_secret = arguments.kite_secret
file_path = os.path.join(CONFIG_DIR, '10_account.rc')
file_path_new = os.path.join(CONFIG_DIR, '10_account.rc.new')
with open(file_path, 'r') as read_file_object, \
os.fdopen(os.open(file_path_new, os.O_WRONLY | os.O_CREAT,
0o400), 'w') as write_file_object:
for line in read_file_object:
if re.match(r'[ \t]*kitename[ \t]*=.*', line):
write_file_object.write(
'kitename = {kite_name}\n'.format(kite_name=kite_name))
continue
if re.match(r'[ \t]*kitesecret[ \t]*=.*', line):
write_file_object.write('kitesecret = {kite_secret}\n'
.format(kite_secret=kite_secret))
continue
write_file_object.write(line)
os.rename(file_path_new, file_path)
def subcommand_get_service_status(arguments):
"""Print status of the pagekite service"""
is_enabled = is_service_enabled(arguments.service)
print('enabled' if is_enabled else 'disabled')
def is_service_enabled(service):
"""Return if a service is enabled"""
service = SERVICE_FILE_MAP[service]
service_file_path = os.path.join(CONFIG_DIR, service['file'])
if not os.path.isfile(service_file_path):
return False
try:
with open(service_file_path, 'r') as file_object:
for line in file_object:
regex = '[ \t]*service_on[ \t]*=[ \t]*{match}'
regex = regex.format(match=service['match'])
if re.match(regex, line):
return True
except Exception:
return False
return False
def subcommand_set_service_status(arguments):
"""Enable/disable a pagekite service"""
enable = arguments.enable == 'enable'
is_enabled = is_service_enabled(arguments.service)
if enable and is_enabled:
print('already enabled')
return
if not enable and not is_enabled:
print('already disabled')
return
if enable:
service_enable(arguments.service)
print('enabled')
else:
service_disable(arguments.service)
print('disabled')
def service_enable(service_name):
"""Enable a service"""
service = SERVICE_FILE_MAP[service_name]
service_file_path = os.path.join(CONFIG_DIR, service['file'])
with open(service_file_path, 'w') as file_object:
file_object.write('''
# Expose the local {service_name} daemon
# File auto-generated by Plinth
{line}
'''.format(service_name=service_name, line=service['line']))
def service_disable(service_name):
"""Disable a service"""
service = SERVICE_FILE_MAP[service_name]
service_file_path = os.path.join(CONFIG_DIR, service['file'])
service_file_path_new = os.path.join(CONFIG_DIR,
service['file'] + '.plinthbak')
os.rename(service_file_path, service_file_path_new)
def main():
"""Parse arguments and perform all duties"""
arguments = parse_arguments()
subcommand = arguments.subcommand.replace('-', '_')
subcommand_method = globals()['subcommand_' + subcommand]
subcommand_method(arguments)
if __name__ == "__main__":
main()
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/python2
# -*- mode: python -*-
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Utilities for configuring PageKite.
"""
# TODO:
# Once python-augeas is available for python3 import the following things
# from plinth.modules.pagekite.util (instead of having a copy in here):
#
# SERVICE_PARAMS, convert_service_to_string
#
# until then, this file is python2 and python3 compatible for the unittests
import os
import json
CONF_PATH = '/files/etc/pagekite.d'
# parameters that get stored in configuration service_on entries
SERVICE_PARAMS = ['protocol', 'kitename', 'backend_host', 'backend_port',
'secret']
def convert_service_to_string(service):
""" Convert service dict into a ":"-separated parameter string
>>> convert_service_to_string({'kitename': '@kitename', \
'backend_host': 'localhost', 'secret': '@kitesecret', \
'protocol': 'https/443', 'backend_port': '443'})
'https/443:@kitename:localhost:443:@kitesecret'
"""
try:
service_string = ":".join([service[param] for param in SERVICE_PARAMS])
except KeyError:
raise ValueError("Could not parse params: %s " % service)
return service_string
def load_service(json_service):
""" create a service out of json command-line argument
1) parse json
2) only use the parameters that we need (SERVICE_PARAMS)
3) convert unicode to strings
"""
service = json.loads(json_service)
return dict((str(key), str(service[key])) for key in SERVICE_PARAMS)
def get_augeas_servicefile_path(protocol):
"""Get the augeas path where a service for a protocol should be stored
TODO: Once we use python3 switch from doctests to unittests
>>> get_augeas_servicefile_path('http')
'/files/etc/pagekite.d/80_http.rc/service_on'
>>> get_augeas_servicefile_path('https')
'/files/etc/pagekite.d/443_https.rc/service_on'
>>> get_augeas_servicefile_path('http/80')
'/files/etc/pagekite.d/80_http.rc/service_on'
>>> get_augeas_servicefile_path('http/8080')
'/files/etc/pagekite.d/8080_http.rc/service_on'
>>> get_augeas_servicefile_path('raw/22')
'/files/etc/pagekite.d/22_raw.rc/service_on'
>>> get_augeas_servicefile_path('xmpp')
Traceback (most recent call last):
...
ValueError: Unsupported protocol: xmpp
"""
if not protocol.startswith(("http", "https", "raw")):
raise ValueError('Unsupported protocol: %s' % protocol)
try:
_protocol, port = protocol.split('/')
except ValueError:
if protocol == 'http':
relpath = '80_http.rc'
elif protocol == 'https':
relpath = '443_https.rc'
else:
raise ValueError('Unsupported protocol: %s' % protocol)
else:
relpath = '%s_%s.rc' % (port, _protocol)
return os.path.join(CONF_PATH, relpath, 'service_on')
if __name__ == "__main__":
import doctest
doctest.testmod()
+3 -14
View File
@@ -25,6 +25,8 @@ import argparse
import os
import subprocess
import util
SERVICE_CONFIG = '/etc/default/tor'
TOR_CONFIG = '/etc/tor/torrc'
@@ -57,20 +59,7 @@ def parse_arguments():
def subcommand_is_running(_):
"""Get whether Tor is running"""
try:
output = subprocess.check_output(['service', 'tor', 'status'])
except subprocess.CalledProcessError:
# If Tor is not running we get a status code != 0 and a
# CalledProcessError
print('no')
else:
running = False
for line in output.decode().split('\n'):
if 'Active' in line and 'running' in line:
running = True
break
print('yes' if running else 'no')
print('yes' if util.service_is_running('tor') else 'no')
def subcommand_start(_):
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/python3
# -*- mode: python -*-
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Python action utility functions
"""
import subprocess
def service_is_running(servicename):
"""Evaluates whether a service is currently running. Returns boolean"""
try:
output = subprocess.check_output(['service', servicename, 'status'])
except subprocess.CalledProcessError:
# Usually if a service is not running we get a status code != 0 and
# thus a CalledProcessError
return False
else:
running = False # default value
for line in output.decode('utf-8').split('\n'):
if 'Active' in line and 'running' in line:
running = True
break
return running