· 7 years ago · Sep 17, 2018, 02:12 PM
1#!/usr/bin/env python3
2
3"""
4This is a helper script that semi-automates the process
5of configuring/editing systemd services.
6
7Examples --
8Create a service using a short preset configuration:
9sudo ./service-config.py --short some_service_name
10
11Create a service using a custom preset configuration template:
12sudo ./service-config.py -c some_schema some_service_name
13
14Edit an existing service:
15sudo ./service-config.py --edit some_service_name
16
17# To do list:
181. Document the script.
192. Fix permission issues with some of the arguments.
203. Add a configuration file for the script for
21 some of the default values and options. (?)
224. Allow the user to choose an editor.
23
24NOTES:
251. This script requires root privileges for most use-cases.
262. Skipping a configuration option (just pressing enter) without
27 supplying any value will just tell the script to skip that option.
28"""
29
30# IMPORTS:
31
32import argparse
33import configparser
34import datetime
35import os
36import subprocess
37import sys
38import time
39
40from collections import OrderedDict
41
42# DEFINING CONSTANTS:
43
44VERSION = "0.4"
45MAINTAINER_NICK = "..."
46MAINTAINER_EMAIL = "...@gmail.com"
47TRACE = True
48SCHEMA = "schemas/service-config"
49SCHEMA_SHORT = "schemas/short_service-config"
50SCHEMA_EXTENDED = "schemas/extended_service-config"
51CONFIG = None # for future uses
52OUTPUT_DIR = "/etc/systemd/system"
53
54# ERRORS:
55
56USER_ABORT = 5
57ARGPARSE_ERR = 6
58CONFIGURATION_ERR = 7
59GLOBAL_ERR = 8
60SCHEMA_ERR = 9
61SYSTEMD_ERR = 10
62UID_ERROR = 11
63FINISH_ERROR = 12
64
65# DEFAULTS:
66
67DEFAULT_EDITOR = "vim"
68DEFAULT_BUILD_SCHEMA = "schemas/default-schema"
69
70DEFAULT_DESCRIPTION = "Example"
71DEFAULT_AFTER = "network.target"
72DEFAULT_TYPE = "simple"
73DEFAULT_USER = "root"
74DEFAULT_GROUP = "root"
75DEFAULT_EXEC_START = "/bin/true"
76DEFAULT_EXEC_STOP = "/bin/true"
77DEFAULT_KILL_MODE = "control-group"
78DEFAULT_KILL_SIGNAL = "SIGTERM"
79DEFAULT_PID_FILE = "/run/service.pid"
80DEFAULT_RESTART = "on-failure"
81DEFAULT_RESTART_SEC = "2"
82DEFAULT_TIMEOUT_STOP_SEC = "5"
83DEFAULT_DYNAMIC_USER = "no"
84DEFAULT_ENVIRONMENT_FILE = "/etc/service/env"
85DEFAULT_STANDARD_OUTPUT = "journal"
86DEFAULT_STANDARD_ERROR = "journal"
87DEFAULT_WANTED_BY = "multi-user.target"
88
89# COLORS AND Formatting:
90
91def tty_supports_ansi():
92 """Checks whether the terminal used supports ANSI codes."""
93
94 for handle in [sys.stdout, sys.stderr]:
95 if ((hasattr(handle, "isatty") and handle.isatty()) or
96 ('TERM' in os.environ and os.environ['TERM'] == "ANSI")):
97 return True
98 else:
99 return False
100
101class Formatting:
102 """
103 A class containing constants with most Formatting/basic colors
104 for Unix-based terminals and vtys.
105 Does NOT work on Windows cmd, PowerShell, and their varieties!
106 """
107
108 RESET = "