config.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. from argparse import Action, ArgumentParser, Namespace, RawTextHelpFormatter
  4. from json import load as loadjson, dump as dumpjson
  5. from os import stat, environ, path
  6. from logging import error, getLevelName
  7. from ast import literal_eval
  8. import sys
  9. __cli_args = Namespace()
  10. __config = {} # type: dict
  11. log_levels = ['CRITICAL', 'FATAL', 'ERROR',
  12. 'WARN', 'WARNING', 'INFO', 'DEBUG', 'NOTSET']
  13. # 支持数组的参数列表
  14. ARRAY_PARAMS = ['index4', 'index6', 'ipv4', 'ipv6', 'proxy']
  15. # 简单数组,支持’,’, ‘;’ 分隔的参数列表
  16. SIMPLE_ARRAY_PARAMS = ['ipv4', 'ipv6', 'proxy']
  17. def str2bool(v):
  18. """
  19. parse string to boolean
  20. """
  21. if isinstance(v, bool):
  22. return v
  23. if v.lower() in ('yes', 'true', 't', 'y', '1'):
  24. return True
  25. elif v.lower() in ('no', 'false', 'f', 'n', '0'):
  26. return False
  27. else:
  28. return v
  29. def log_level(value):
  30. """
  31. parse string to log level
  32. """
  33. return getLevelName(value.upper())
  34. def parse_array_string(value, enable_simple_split):
  35. """
  36. 解析数组字符串
  37. 仅当 trim 之后以 '[' 开头以 ']' 结尾时,才尝试使用 ast.literal_eval 解析
  38. 默认返回原始字符串
  39. """
  40. if not isinstance(value, str):
  41. return value
  42. trimmed = value.strip()
  43. if trimmed.startswith('[') and trimmed.endswith(']'):
  44. try:
  45. # 尝试使用 ast.literal_eval 解析数组
  46. parsed_value = literal_eval(trimmed)
  47. # 确保解析结果是列表或元组
  48. if isinstance(parsed_value, (list, tuple)):
  49. return list(parsed_value)
  50. except (ValueError, SyntaxError) as e:
  51. # 解析失败时返回原始字符串
  52. error('Failed to parse array string: %s. Exception: %s', value, e)
  53. elif enable_simple_split and ',' in trimmed:
  54. # 尝试使用逗号或分号分隔符解析
  55. return [item.strip() for item in trimmed.split(',') if item.strip()]
  56. return value
  57. def init_config(description, doc, version):
  58. """
  59. 配置
  60. """
  61. global __cli_args
  62. parser = ArgumentParser(description=description,
  63. epilog=doc, formatter_class=RawTextHelpFormatter)
  64. parser.add_argument('-v', '--version',
  65. action='version', version=version)
  66. parser.add_argument('-c', '--config', help='run with config file [配置文件路径]')
  67. # 参数定义
  68. parser.add_argument('--dns', help='DNS Provider [DNS服务提供商]', choices=[
  69. 'alidns', 'cloudflare', 'dnscom', 'dnspod', 'dnspod_com', 'he', 'huaweidns', 'callback'])
  70. parser.add_argument('--id', help='api ID [授权账户]')
  71. parser.add_argument('--token', help='api token or Secret key [授权访问凭证或密钥]')
  72. parser.add_argument('--index4', nargs='*', action=ExtendAction,
  73. help='list to get ipv4 [IPV4 获取方式]')
  74. parser.add_argument('--index6', nargs='*', action=ExtendAction,
  75. help='list to get ipv6 [IPV6获取方式]')
  76. parser.add_argument('--ipv4', nargs='*', action=ExtendAction,
  77. help='ipv4 domain list [IPV4域名列表]')
  78. parser.add_argument('--ipv6', nargs='*', action=ExtendAction,
  79. help='ipv6 domain list [IPV6域名列表]')
  80. parser.add_argument('--ttl', type=int, help='ttl for DNS [DNS 解析 TTL 时间]')
  81. parser.add_argument('--proxy', nargs='*', action=ExtendAction,
  82. help='https proxy [设置http 代理,多代理逐个尝试直到成功]')
  83. parser.add_argument('--cache', type=str2bool, nargs='?',
  84. const=True, help='cache flag [启用缓存,可配配置路径或开关]')
  85. parser.add_argument('--debug', action='store_true',
  86. help='debug mode [调试模式,等同log.level=DEBUG]')
  87. parser.add_argument('--log.file', metavar='LOG_FILE',
  88. help='log file [日志文件,默认标准输出]')
  89. parser.add_argument('--log.level', type=log_level,
  90. metavar='|'.join(log_levels))
  91. parser.add_argument('--log.format', metavar='LOG_FORMAT',
  92. help='log format [日志格式字符串]')
  93. parser.add_argument('--log.datefmt', metavar='DATE_FORMAT',
  94. help='date format [日期格式字符串]')
  95. __cli_args = parser.parse_args()
  96. if __cli_args.debug:
  97. # 如果启用调试模式,则设置日志级别为 DEBUG
  98. setattr(__cli_args, 'log.level', log_level('DEBUG'))
  99. is_configfile_required = not get_config("token") and not get_config("id")
  100. config_file = get_config("config")
  101. if not config_file:
  102. # 未指定配置文件且需要读取文件时,依次查找
  103. cfgs = [
  104. path.abspath('config.json'),
  105. path.expanduser('~/.ddns/config.json'),
  106. '/etc/ddns/config.json'
  107. ]
  108. config_file = next((cfg for cfg in cfgs if path.isfile(cfg)), cfgs[0])
  109. if path.isfile(config_file):
  110. __load_config(config_file)
  111. __cli_args.config = config_file
  112. elif is_configfile_required:
  113. error('Config file is required, but not found: %s', config_file)
  114. # 如果需要配置文件但没有指定,则自动生成
  115. if generate_config(config_file):
  116. sys.stdout.write(
  117. 'Default configure file %s is generated.\n' % config_file)
  118. sys.exit(1)
  119. else:
  120. sys.exit('fail to load config from file: %s\n' % config_file)
  121. def __load_config(config_path):
  122. """
  123. 加载配置
  124. """
  125. global __config
  126. try:
  127. with open(config_path, 'r') as configfile:
  128. __config = loadjson(configfile)
  129. __config["config_modified_time"] = stat(config_path).st_mtime
  130. if 'log' in __config:
  131. if 'level' in __config['log'] and __config['log']['level'] is not None:
  132. __config['log.level'] = log_level(__config['log']['level'])
  133. if 'file' in __config['log']:
  134. __config['log.file'] = __config['log']['file']
  135. if 'format' in __config['log']:
  136. __config['log.format'] = __config['log']['format']
  137. if 'datefmt' in __config['log']:
  138. __config['log.datefmt'] = __config['log']['datefmt']
  139. elif 'log.level' in __config:
  140. __config['log.level'] = log_level(__config['log.level'])
  141. except Exception as e:
  142. error('Failed to load config file `%s`: %s', config_path, e)
  143. raise
  144. # 重新抛出异常
  145. def get_config(key, default=None):
  146. """
  147. 读取配置
  148. 1. 命令行参数
  149. 2. 配置文件
  150. 3. 环境变量
  151. """
  152. if hasattr(__cli_args, key) and getattr(__cli_args, key) is not None:
  153. return getattr(__cli_args, key)
  154. if key in __config:
  155. return __config.get(key)
  156. # 检查环境变量
  157. env_name = 'DDNS_' + key.replace('.', '_') # type:str
  158. variations = [env_name, env_name.upper(), env_name.lower()]
  159. value = next((environ.get(v) for v in variations if v in environ), None)
  160. # 如果找到环境变量值且参数支持数组,尝试解析为数组
  161. if value is not None and key in ARRAY_PARAMS:
  162. return parse_array_string(value, key in SIMPLE_ARRAY_PARAMS)
  163. return value if value is not None else default
  164. class ExtendAction(Action):
  165. """
  166. 兼容 Python <3.8 的 extend action
  167. """
  168. def __call__(self, parser, namespace, values, option_string=None):
  169. items = getattr(namespace, self.dest, None)
  170. if items is None:
  171. items = []
  172. # values 可能是单个值或列表
  173. if isinstance(values, list):
  174. items.extend(values)
  175. else:
  176. items.append(values)
  177. setattr(namespace, self.dest, items)
  178. def generate_config(config_path):
  179. """
  180. 生成配置文件
  181. """
  182. configure = {
  183. '$schema': 'https://ddns.newfuture.cc/schema/v4.0.json',
  184. 'id': 'YOUR ID or EMAIL for DNS Provider',
  185. 'token': 'YOUR TOKEN or KEY for DNS Provider',
  186. 'dns': 'dnspod',
  187. 'ipv4': [
  188. 'newfuture.cc',
  189. 'ddns.newfuture.cc'
  190. ],
  191. 'ipv6': [
  192. 'newfuture.cc',
  193. 'ipv6.ddns.newfuture.cc'
  194. ],
  195. 'index4': 'default',
  196. 'index6': 'default',
  197. 'ttl': None,
  198. 'proxy': None,
  199. 'log': {
  200. 'level': 'INFO'
  201. }
  202. }
  203. try:
  204. with open(config_path, 'w') as f:
  205. dumpjson(configure, f, indent=2, sort_keys=True)
  206. return True
  207. except IOError:
  208. error('Cannot open config file to write: `%s`!', config_path)
  209. return False
  210. except Exception as e:
  211. error('Failed to write config file `%s`: %s', config_path, e)
  212. return False