config.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. # -*- coding:utf-8 -*-
  2. from argparse import Action, ArgumentParser, Namespace, RawTextHelpFormatter
  3. from json import load as loadjson, dump as dumpjson
  4. from os import stat, environ, path
  5. from logging import critical, error, getLevelName
  6. from ast import literal_eval
  7. import platform
  8. import sys
  9. __cli_args = Namespace()
  10. __config = {} # type: dict
  11. log_levels = [
  12. "CRITICAL", # 50
  13. "ERROR", # 40
  14. "WARNING", # 30
  15. "INFO", # 20
  16. "DEBUG", # 10
  17. "NOTSET", # 0
  18. ]
  19. # 支持数组的参数列表
  20. ARRAY_PARAMS = ["index4", "index6", "ipv4", "ipv6", "proxy"]
  21. # 简单数组,支持’,’, ‘;’ 分隔的参数列表
  22. SIMPLE_ARRAY_PARAMS = ["ipv4", "ipv6", "proxy"]
  23. def str2bool(v):
  24. """
  25. parse string to boolean
  26. """
  27. if isinstance(v, bool):
  28. return v
  29. if v.lower() in ("yes", "true", "t", "y", "1"):
  30. return True
  31. elif v.lower() in ("no", "false", "f", "n", "0"):
  32. return False
  33. else:
  34. return v
  35. def log_level(value):
  36. """
  37. parse string to log level
  38. or getattr(logging, value.upper())
  39. """
  40. return getLevelName(value.upper())
  41. def parse_array_string(value, enable_simple_split):
  42. """
  43. 解析数组字符串
  44. 仅当 trim 之后以 '[' 开头以 ']' 结尾时,才尝试使用 ast.literal_eval 解析
  45. 默认返回原始字符串
  46. """
  47. if not hasattr(value, "strip"): # 非字符串
  48. return value
  49. trimmed = value.strip()
  50. if trimmed.startswith("[") and trimmed.endswith("]"):
  51. try:
  52. # 尝试使用 ast.literal_eval 解析数组
  53. parsed_value = literal_eval(trimmed)
  54. # 确保解析结果是列表或元组
  55. if isinstance(parsed_value, (list, tuple)):
  56. return list(parsed_value)
  57. except (ValueError, SyntaxError) as e:
  58. # 解析失败时返回原始字符串
  59. error("Failed to parse array string: %s. Exception: %s", value, e)
  60. elif enable_simple_split:
  61. # 尝试使用逗号或分号分隔符解析
  62. sep = None
  63. if "," in trimmed:
  64. sep = ","
  65. elif ";" in trimmed:
  66. sep = ";"
  67. if sep:
  68. return [item.strip() for item in trimmed.split(sep) if item.strip()]
  69. return value
  70. def get_system_info_str():
  71. system = platform.system()
  72. release = platform.release()
  73. machine = platform.machine()
  74. arch = platform.architecture()
  75. return "{}-{} {} {}".format(system, release, machine, arch)
  76. def get_python_info_str():
  77. version = platform.python_version()
  78. branch, py_build_date = platform.python_build()
  79. return "Python-{} {} ({})".format(version, branch, py_build_date)
  80. def init_config(description, doc, version, date):
  81. """
  82. 配置
  83. """
  84. global __cli_args
  85. parser = ArgumentParser(description=description, epilog=doc, formatter_class=RawTextHelpFormatter)
  86. sysinfo = get_system_info_str()
  87. pyinfo = get_python_info_str()
  88. version_str = "v{} ({})\n{}\n{}".format(version, date, pyinfo, sysinfo)
  89. parser.add_argument("-v", "--version", action="version", version=version_str)
  90. parser.add_argument("-c", "--config", metavar="FILE", help="load config file [配置文件路径]")
  91. parser.add_argument("--debug", action="store_true", help="debug mode [开启调试模式]")
  92. # 参数定义
  93. parser.add_argument(
  94. "--dns",
  95. help="DNS provider [DNS服务提供商]",
  96. choices=[
  97. "alidns",
  98. "cloudflare",
  99. "dnscom",
  100. "dnspod",
  101. "dnspod_com",
  102. "he",
  103. "huaweidns",
  104. "callback",
  105. "debug",
  106. ],
  107. )
  108. parser.add_argument("--id", help="API ID or email [对应账号ID或邮箱]")
  109. parser.add_argument("--token", help="API token or key [授权凭证或密钥]")
  110. parser.add_argument(
  111. "--index4",
  112. nargs="*",
  113. action=ExtendAction,
  114. metavar="RULE",
  115. help="IPv4 rules [获取IPv4方式, 多次可配置多规则]",
  116. )
  117. parser.add_argument(
  118. "--index6",
  119. nargs="*",
  120. action=ExtendAction,
  121. metavar="RULE",
  122. help="IPv6 rules [获取IPv6方式, 多次可配置多规则]",
  123. )
  124. parser.add_argument(
  125. "--ipv4",
  126. nargs="*",
  127. action=ExtendAction,
  128. metavar="DOMAIN",
  129. help="IPv4 domains [IPv4域名列表, 可配置多个域名]",
  130. )
  131. parser.add_argument(
  132. "--ipv6",
  133. nargs="*",
  134. action=ExtendAction,
  135. metavar="DOMAIN",
  136. help="IPv6 domains [IPv6域名列表, 可配置多个域名]",
  137. )
  138. parser.add_argument("--ttl", type=int, help="DNS TTL(s) [设置域名解析过期时间]")
  139. parser.add_argument(
  140. "--proxy",
  141. nargs="*",
  142. action=ExtendAction,
  143. help="HTTP proxy [设置http代理,可配多个代理连接]",
  144. )
  145. parser.add_argument(
  146. "--cache",
  147. type=str2bool,
  148. nargs="?",
  149. const=True,
  150. help="set cache [启用缓存开关,或传入保存路径]",
  151. )
  152. parser.add_argument(
  153. "--no-cache",
  154. dest="cache",
  155. action="store_const",
  156. const=False,
  157. help="disable cache [关闭缓存等效 --cache=false]",
  158. )
  159. parser.add_argument(
  160. "--ssl",
  161. help="SSL certificate verification [SSL证书验证方式]: "
  162. "true(强制验证), false(禁用验证), auto(自动降级), /path/to/cert.pem(自定义证书)",
  163. )
  164. parser.add_argument("--log.file", metavar="FILE", help="log file [日志文件,默认标准输出]")
  165. parser.add_argument("--log.level", type=log_level, metavar="|".join(log_levels))
  166. parser.add_argument("--log.format", metavar="FORMAT", help="log format [设置日志打印格式]")
  167. parser.add_argument("--log.datefmt", metavar="FORMAT", help="date format [日志时间打印格式]")
  168. __cli_args = parser.parse_args()
  169. is_debug = getattr(__cli_args, "debug", False)
  170. if is_debug:
  171. # 如果启用调试模式,则强制设置日志级别为 DEBUG
  172. setattr(__cli_args, "log.level", log_level("DEBUG"))
  173. if not hasattr(__cli_args, "cache"):
  174. setattr(__cli_args, "cache", False) # 禁用缓存
  175. config_required = not get_config("token") and not get_config("id")
  176. config_file = get_config("config") # type: str | None # type: ignore
  177. if not config_file:
  178. # 未指定配置文件且需要读取文件时,依次查找
  179. cfgs = [
  180. path.abspath("config.json"),
  181. path.expanduser("~/.ddns/config.json"),
  182. "/etc/ddns/config.json",
  183. ]
  184. config_file = next((cfg for cfg in cfgs if path.isfile(cfg)), cfgs[0])
  185. if path.isfile(config_file):
  186. __load_config(config_file)
  187. __cli_args.config = config_file
  188. elif config_required:
  189. error("Config file is required, but not found: %s", config_file)
  190. # 如果需要配置文件但没有指定,则自动生成
  191. if generate_config(config_file):
  192. sys.stdout.write("Default configure file %s is generated.\n" % config_file)
  193. sys.exit(1)
  194. else:
  195. sys.exit("fail to load config from file: %s\n" % config_file)
  196. def __load_config(config_path):
  197. """
  198. 加载配置
  199. """
  200. global __config
  201. try:
  202. with open(config_path, "r") as configfile:
  203. __config = loadjson(configfile)
  204. __config["config_modified_time"] = stat(config_path).st_mtime
  205. if "log" in __config:
  206. if "level" in __config["log"] and __config["log"]["level"] is not None:
  207. __config["log.level"] = log_level(__config["log"]["level"])
  208. if "file" in __config["log"]:
  209. __config["log.file"] = __config["log"]["file"]
  210. if "format" in __config["log"]:
  211. __config["log.format"] = __config["log"]["format"]
  212. if "datefmt" in __config["log"]:
  213. __config["log.datefmt"] = __config["log"]["datefmt"]
  214. elif "log.level" in __config:
  215. __config["log.level"] = log_level(__config["log.level"])
  216. except Exception as e:
  217. critical("Failed to load config file `%s`: %s", config_path, e)
  218. raise
  219. # 重新抛出异常
  220. def get_config(key, default=None):
  221. """
  222. 读取配置
  223. 1. 命令行参数
  224. 2. 配置文件
  225. 3. 环境变量
  226. """
  227. if hasattr(__cli_args, key) and getattr(__cli_args, key) is not None:
  228. return getattr(__cli_args, key)
  229. if key in __config:
  230. return __config.get(key)
  231. # 检查环境变量
  232. env_name = "DDNS_" + key.replace(".", "_") # type:str
  233. variations = [env_name, env_name.upper(), env_name.lower()]
  234. value = next((environ.get(v) for v in variations if v in environ), None)
  235. # 如果找到环境变量值且参数支持数组,尝试解析为数组
  236. if value is not None and key in ARRAY_PARAMS:
  237. return parse_array_string(value, key in SIMPLE_ARRAY_PARAMS)
  238. return value if value is not None else default
  239. class ExtendAction(Action):
  240. """
  241. 兼容 Python <3.8 的 extend action
  242. """
  243. def __call__(self, parser, namespace, values, option_string=None):
  244. items = getattr(namespace, self.dest, None)
  245. if items is None:
  246. items = []
  247. # values 可能是单个值或列表
  248. if isinstance(values, list):
  249. items.extend(values)
  250. else:
  251. items.append(values)
  252. setattr(namespace, self.dest, items)
  253. def generate_config(config_path):
  254. """
  255. 生成配置文件
  256. """
  257. configure = {
  258. "$schema": "https://ddns.newfuture.cc/schema/v4.0.json",
  259. "id": "YOUR ID or EMAIL for DNS Provider",
  260. "token": "YOUR TOKEN or KEY for DNS Provider",
  261. "dns": "debug", # DNS Provider, default is print
  262. "ipv4": ["newfuture.cc", "ddns.newfuture.cc"],
  263. "ipv6": ["newfuture.cc", "ipv6.ddns.newfuture.cc"],
  264. "index4": "default",
  265. "index6": "default",
  266. "ttl": None,
  267. "proxy": None,
  268. "ssl": "auto",
  269. "log": {"level": "INFO"},
  270. }
  271. try:
  272. with open(config_path, "w") as f:
  273. dumpjson(configure, f, indent=2, sort_keys=True)
  274. return True
  275. except IOError:
  276. critical("Cannot open config file to write: `%s`!", config_path)
  277. return False
  278. except Exception as e:
  279. critical("Failed to write config file `%s`: %s", config_path, e)
  280. return False