net-connector 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +13 -0
  3. data/docs/architecture.md +16 -6
  4. data/docs/netdisco.md +8 -4
  5. data/docs/netdisco.zh-CN.md +10 -6
  6. data/docs/usage.md +1 -1
  7. data/docs/usage.zh-CN.md +2 -2
  8. data/lib/net/connector/collect/progress.rb +70 -0
  9. data/lib/net/connector/config.rb +367 -0
  10. data/lib/net/connector/device/interfaces/audit.rb +3 -3
  11. data/lib/net/connector/device/interfaces/{interface_blocks.rb → blocks.rb} +1 -1
  12. data/lib/net/connector/device/interfaces/{interface_description.rb → description.rb} +6 -6
  13. data/lib/net/connector/device/interfaces/immediate_strategy.rb +2 -2
  14. data/lib/net/connector/device/interfaces/{interface_name.rb → name.rb} +1 -1
  15. data/lib/net/connector/device/interfaces/stages.rb +2 -2
  16. data/lib/net/connector/device/interfaces/strategy.rb +3 -3
  17. data/lib/net/connector/device/interfaces.rb +5 -5
  18. data/lib/net/connector/engine/errors.rb +4 -4
  19. data/lib/net/connector/engine/result.rb +2 -2
  20. data/lib/net/connector/netdisco/cli/backup.rb +17 -13
  21. data/lib/net/connector/netdisco/cli/help.rb +1 -1
  22. data/lib/net/connector/netdisco/cli/options.rb +49 -16
  23. data/lib/net/connector/netdisco/cli/setup.rb +32 -12
  24. data/lib/net/connector/netdisco/cli/topology.rb +14 -7
  25. data/lib/net/connector/netdisco/cli.rb +27 -8
  26. data/lib/net/connector/netdisco/config/defaults.rb +1 -1
  27. data/lib/net/connector/netdisco/config/initializer.rb +17 -11
  28. data/lib/net/connector/netdisco/config.rb +49 -1
  29. data/lib/net/connector/netdisco/fleet.rb +1 -1
  30. data/lib/net/connector/netdisco/operation.rb +3 -3
  31. data/lib/net/connector/netdisco/progress.rb +41 -283
  32. data/lib/net/connector/netdisco/settings.rb +11 -2
  33. data/lib/net/connector/netdisco/topology/options.rb +3 -3
  34. data/lib/net/connector/parallel/pool.rb +3 -4
  35. data/lib/net/connector/progress.rb +288 -0
  36. data/lib/net/connector/resources.rb +40 -0
  37. data/lib/net/connector/vendor/cisco/topology.rb +1 -1
  38. data/lib/net/connector/vendor/h3c/topology.rb +1 -1
  39. data/lib/net/connector/vendor/hillstone/topology.rb +1 -1
  40. data/lib/net/connector/vendor/huawei/topology.rb +2 -2
  41. data/lib/net/connector/version.rb +1 -1
  42. metadata +23 -6
  43. data/lib/net/connector/netdisco/resources.rb +0 -36
@@ -4,6 +4,7 @@ require "optparse"
4
4
  require_relative "../settings"
5
5
  require_relative "../planner"
6
6
  require_relative "../config"
7
+ require_relative "../../config"
7
8
  require_relative "help"
8
9
 
9
10
  module Net
@@ -119,31 +120,61 @@ module Net
119
120
  end
120
121
  end
121
122
 
122
- # 公开 CLI 参数进入 overrides,凭据留在 environment;内部键不会重新开放已移除环境设置。
123
- def self.settings(options, env: ENV, load_env: false)
123
+ PATH_FIELDS = %w[netdisco.cache_directory netdisco.db_sslrootcert ssh.known_hosts ssh.log_directory backup.directory
124
+ topology.directory tftp.verification_root tftp.verification_roots.*].freeze
125
+ ENV_PATH_KEYS = %w[ND_CACHE_DIRECTORY ND_DB_SSLROOTCERT NC_KNOWN_HOSTS NC_LOG_DIRECTORY NC_BACKUP_DIRECTORY
126
+ NC_TOPOLOGY_DIRECTORY NC_TFTP_ROOT].freeze
127
+
128
+ PATH_LITERALS = { "netdisco.db_sslrootcert" => ["system"].freeze,
129
+ "ND_DB_SSLROOTCERT" => ["system"].freeze }.freeze
130
+
131
+ # 构造宿主配置发现器;帮助解析不调用本方法,不读取用户文件。
132
+ def self.configuration(options, env: ENV, mode: :backup, **context)
133
+ Net::Connector::Config.new(name: mode == :topology ? "topology" : "backup", env: env,
134
+ config: options.fetch(:environment)["NC_CONFIG"], env_file: options[:env_file],
135
+ config_env: "NC_CONFIG", path_fields: PATH_FIELDS, env_path_keys: ENV_PATH_KEYS, path_literals: PATH_LITERALS, **context)
136
+ end
137
+
138
+ # CLI > 原进程环境 > YAML > .env;公开环境字段转为内部策略,凭据仍独立读取。
139
+ def self.settings(options, env: ENV, mode: :backup, configuration: nil, defaults: {})
124
140
  raise ArgumentError, "--all 不能与抽样同时使用" if options[:all] && options[:limit]
125
141
  if options[:host] && options.fetch(:environment).key?("NC_INCLUDE_HOSTS")
126
142
  raise ArgumentError, "--host cannot be combined with --hosts"
127
143
  end
128
144
 
129
- environment = environment(options, env: env)
130
- path = environment["NC_CONFIG"]
131
- defaults = path && !path.empty? ? Config.load(path) : {}
132
- keys = Config::FIELDS.values.flat_map { |fields| fields.values.map(&:first) }
133
- if load_env
134
- # 显式启用时,公开环境值只填补 YAML;CLI 覆盖与凭据来源仍分开处理。
135
- defaults = env.to_h.slice(*keys).merge(defaults)
136
- environment = environment.reject { |key, _| keys.include?(key) }
137
- end
138
- overrides = options.fetch(:environment).slice(*keys)
139
- environment = environment.reject { |key, _| overrides.key?(key) && !Settings::ENVIRONMENT_KEYS.include?(key) }
145
+ files = (configuration || self.configuration(options, env: env, mode: mode)).load
146
+ yaml = Config.parse(files.data)
147
+ public_keys = Config::FIELDS.values.flat_map { |fields| fields.values.map(&:first) }
148
+ overrides = options.fetch(:environment).slice(*public_keys)
140
149
  { source: "ND_SOURCE", query: "ND_QUERY", query_params: "ND_QUERY_PARAMS",
141
150
  max_script_output_bytes: "NC_MAX_SCRIPT_OUTPUT_BYTES", host: "NC_INCLUDE_HOSTS",
142
151
  limit: "NC_SAMPLE_PER_VENDOR", tftp_root: "NC_TFTP_ROOT" }.each do |option, key|
143
152
  overrides[key] = options[option].to_s if options.key?(option)
144
153
  end
145
154
  overrides["NC_SAMPLE_PER_VENDOR"] = nil if options[:all]
146
- Settings.new(env: environment, defaults: defaults, overrides: overrides)
155
+ process = public_environment(files.process_environment)
156
+ if mode == :topology
157
+ process["NC_TOPOLOGY_PARALLEL"] ||= process["NC_PARALLEL"] if process.key?("NC_PARALLEL")
158
+ overrides["NC_TOPOLOGY_PARALLEL"] = overrides["NC_PARALLEL"] if overrides.key?("NC_PARALLEL")
159
+ end
160
+ overrides = process.except(*overrides.keys).merge(overrides)
161
+ file_values = files.file_environment.except(*yaml.keys, *overrides.keys)
162
+ environment = environment(options, env: files.environment).reject { |key, _| public_keys.include?(key) }
163
+ Settings.new(env: environment, defaults: defaults.merge(public_environment(file_values)).merge(yaml), overrides: overrides)
164
+ end
165
+
166
+ # 环境文本已是 Settings 的编码格式;由当前执行模式验证实际使用的字段。
167
+ def self.public_environment(environment)
168
+ keys = Config::FIELDS.values.flat_map { |fields| fields.values.map(&:first) }
169
+ environment.slice(*keys)
170
+ end
171
+
172
+ # 配置来源只包含路径及来源标记;不展开凭据环境或文件正文。
173
+ def self.sources(configuration, options)
174
+ configuration.sources.merge("overrides" => {
175
+ "process_environment" => configuration.process_environment.keys & Config::FIELDS.values.flat_map { |fields| fields.values.map(&:first) },
176
+ "command_line" => options.fetch(:environment).keys.grep_v(/PASSWORD|USERNAME|API_KEY/)
177
+ })
147
178
  end
148
179
 
149
180
  # 共用配置与凭据参数登记;具体入口决定后续预览、执行或导出。
@@ -156,8 +187,8 @@ module Net
156
187
  "--netdisco-url URL" => ["ND_URL", "Netdisco 地址"],
157
188
  "--netdisco-username USER" => ["ND_USERNAME", "Netdisco 用户名"],
158
189
  "--netdisco-password PASSWORD" => ["ND_PASSWORD", "Netdisco 密码"],
159
- "--directory DIR" => ["NC_BACKUP_DIRECTORY", "#{mode == :topology ? "拓扑报告" : "备份"}目录,相对项目根目录"],
160
- "--config FILE" => ["NC_CONFIG", "YAML 配置,相对项目根目录"]
190
+ "--directory DIR" => ["NC_BACKUP_DIRECTORY", "#{mode == :topology ? "拓扑报告" : "备份"}目录,相对启动目录"],
191
+ "--config FILE" => ["NC_CONFIG", "YAML 配置,相对启动目录"]
161
192
  }.each do |flag, (key, description)|
162
193
  opts.on(flag, description) do |value|
163
194
  raise OptionParser::InvalidArgument if value.empty?
@@ -165,6 +196,8 @@ module Net
165
196
  values[:environment][key] = value
166
197
  end
167
198
  end
199
+ opts.on("--env-file FILE", "最后叠加的环境文件,相对启动目录") { |path| values[:env_file] = path }
200
+ opts.on("--show-config", "显示生效的非敏感设置与配置来源") { values[:show_config] = true }
168
201
  opts.on("--host-key-policy POLICY", %w[strict accept_new replace], "主机密钥策略:strict / accept_new / replace(变化时自动替换)") do |policy|
169
202
  values[:environment]["NC_HOST_KEY_POLICY"] = policy
170
203
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "fileutils"
3
4
  require_relative "../config/initializer"
4
5
  require_relative "../config/defaults"
5
6
 
@@ -10,7 +11,7 @@ module Net
10
11
  # 首次运行的文件检查和创建问答;完成初始化后必须退出,不触发设备任务。
11
12
  class Setup
12
13
  ENVIRONMENT_TEMPLATE = <<~TEXT.freeze
13
- # 进程环境优先于此文件;命令行参数 > YAML > 环境默认值 > 内置默认值。
14
+ # 进程环境优先于此文件;命令行参数 > 原进程环境 > YAML > .env > 内置默认值。
14
15
  # 下列凭据按实际认证方式取消注释并填写;不自动保存当前进程中的密码。
15
16
  # ND_URL=
16
17
  # ND_USERNAME=
@@ -28,19 +29,24 @@ module Net
28
29
  # 密码含 # 或 $ 时请用单引号包裹,例如 KEY='your-password'。
29
30
  # NC_TFTP_SSH_PASSWORD=
30
31
  # 公共参数优先写入各入口 YAML;可在运行时使用 -p / --config / --directory。
31
- # NC_CONFIG 不设置时分别使用 examples/backup.yml 和 examples/topology.yml。
32
+ # 未设置 NC_CONFIG 时按系统、用户、入口目录及启动目录逐层发现配置。
32
33
  TEXT
33
34
 
34
35
  # 保存调用方 IO 与路径;不读取标准输入、不加载凭据、不创建文件。
35
- def initialize(mode:, options:, env:, input:, output:, env_path: nil, directory: nil, load_env: false)
36
- @mode, @options, @env, @input, @output = mode, options, env, input, output
37
- @env_path, @directory, @load_env = env_path, directory, load_env
36
+ def initialize(mode:, options:, input:, output:, configuration:, directory: nil)
37
+ @mode, @options, @input, @output = mode, options, input, output
38
+ @directory = directory
39
+ @configuration = configuration
38
40
  @initializer = Config::Initializer.new(input: input, output: output)
39
41
  end
40
42
 
41
43
  # 先确认所有缺失文件的创建意愿,再独占发布;非终端仅接受显式 --init。
42
44
  def initialize_files?
43
- path = @options.fetch(:environment)["NC_CONFIG"] || @env["NC_CONFIG"]
45
+ @configuration.load_environment(allow_missing: !!(@options[:init] || @options[:interactive]))
46
+ path = @configuration.init_config
47
+ @env_path = @configuration.init_env_file
48
+ return false unless @options[:init] || @options[:interactive] == true
49
+
44
50
  missing_config = path && missing?(path)
45
51
  missing_env = @env_path && missing?(@env_path)
46
52
  return !!@options[:init] unless missing_config || missing_env
@@ -48,12 +54,9 @@ module Net
48
54
 
49
55
  create_config = missing_config && approved?(path, required: true)
50
56
  create_env = missing_env && approved?(@env_path, required: false)
51
- document = Config::Defaults.document(mode: @mode, values: public_values, directory: @directory) if create_config
52
- if create_config
53
- @initializer.create(path: path, document: document, interactive: questionnaire?, mode: @mode)
54
- @output.puts "已初始化配置:#{path}"
55
- end
57
+ document = create_configuration(path) if create_config
56
58
  if create_env
59
+ FileUtils.mkdir_p(File.dirname(File.expand_path(@env_path)), mode: 0o700)
57
60
  @initializer.create_environment(path: @env_path, contents: ENVIRONMENT_TEMPLATE)
58
61
  @output.puts "已初始化环境模板:#{@env_path}(未写入密码)"
59
62
  end
@@ -66,6 +69,23 @@ module Net
66
69
 
67
70
  private
68
71
 
72
+ # 先验证有效值;继承并发只用于提示,CLI 或问答的明确选择才写入 YAML。
73
+ def create_configuration(path)
74
+ document = Config::Defaults.document(mode: @mode, values: public_values, directory: @directory)
75
+ policy = Settings.new(env: {}, defaults: Config.parse(document)).snapshot(mode: :show_config)
76
+ inherited_parallel = @mode == :topology ? policy.topology_options.parallel : policy.parallel
77
+ parallel_section = @mode == :topology ? "topology" : "backup"
78
+ %w[backup topology].each do |section|
79
+ next if section == parallel_section && @options.fetch(:environment).key?("NC_PARALLEL")
80
+
81
+ document[section]&.delete("parallel")
82
+ end
83
+ FileUtils.mkdir_p(File.dirname(File.expand_path(path)), mode: 0o700)
84
+ @initializer.create(path: path, document: document, interactive: questionnaire?, mode: @mode, inherited_parallel: inherited_parallel)
85
+ @output.puts "已初始化配置:#{path}"
86
+ document
87
+ end
88
+
69
89
  # 缺失与无效文件分开处理,拒绝符号链接、目录及不可读取文件。
70
90
  def missing?(path)
71
91
  stat = File.lstat(path)
@@ -116,7 +136,7 @@ module Net
116
136
 
117
137
  # CLI 参数覆盖已加载的公共环境值;敏感变量不在字段允许列表内。
118
138
  def public_values
119
- values = (@load_env ? @env.to_h : {}).merge(@options.fetch(:environment))
139
+ values = @configuration.environment.merge(@options.fetch(:environment))
120
140
  { source: "ND_SOURCE", query: "ND_QUERY", query_params: "ND_QUERY_PARAMS", host: "NC_INCLUDE_HOSTS",
121
141
  limit: "NC_SAMPLE_PER_VENDOR", topology_limit: "NC_TOPOLOGY_LIMIT", tftp_root: "NC_TFTP_ROOT" }.each do |option, key|
122
142
  values[key] = @options[option].to_s if @options.key?(option)
@@ -8,7 +8,7 @@ require_relative "../fleet"
8
8
  require_relative "../progress"
9
9
  require_relative "setup"
10
10
  require_relative "../../storage/batch_directory"
11
- require_relative "../resources"
11
+ require_relative "../../resources"
12
12
  require_relative "../topology/files"
13
13
  require_relative "../topology/presentation"
14
14
 
@@ -20,10 +20,11 @@ module Net
20
20
  class Topology
21
21
  # 保存拓扑入口默认配置、输入输出和连接器工厂,暂不访问清单。
22
22
  def initialize(default_config: nil, default_directory: nil, argv: ARGV, env: ENV, input: $stdin,
23
- output: $stdout, error: $stderr, connector_factory: nil, default_env: nil, load_env: false)
23
+ output: $stdout, error: $stderr, connector_factory: nil, default_env: nil, configuration_options: {})
24
24
  @default_config, @default_directory = default_config, default_directory
25
25
  @argv, @env, @input, @output, @error = argv, env, input, output, error
26
- @load_env, @default_env = load_env, default_env
26
+ @default_env = default_env
27
+ @configuration_options = configuration_options
27
28
  @connector_factory = connector_factory || ->(device, options) { device.build_connector(**options) }
28
29
  end
29
30
 
@@ -37,6 +38,10 @@ module Net
37
38
  settings = settings_for(options)
38
39
  return 0 if @initialized
39
40
 
41
+ if options[:show_config]
42
+ @output.puts JSON.pretty_generate(settings.public_config.merge(sources: CLI::Options.sources(@configuration, options)))
43
+ return 0
44
+ end
40
45
  policy = settings.topology_options
41
46
  raise ArgumentError, "应用配置必须显式传入 --apply;--plan 仅生成计划,--discover 只读发现" if policy.mode == :apply && !options[:apply]
42
47
 
@@ -74,10 +79,12 @@ module Net
74
79
  def settings_for(options)
75
80
  environment = options.fetch(:environment)
76
81
  environment["NC_CONFIG"] ||= @default_config if @default_config && !@env["NC_CONFIG"]
77
- @initialized = Setup.new(mode: :topology, options: options, env: @env, input: @input, output: @error,
78
- env_path: @default_env, directory: @default_directory, load_env: @load_env).initialize_files?
82
+ options[:env_file] ||= @default_env if @default_env
83
+ @configuration = CLI::Options.configuration(options, env: @env, mode: :topology, **@configuration_options)
84
+ @initialized = Setup.new(mode: :topology, options: options, input: @input, output: @error,
85
+ directory: @default_directory || File.expand_path("topologys"), configuration: @configuration).initialize_files?
79
86
  return if @initialized
80
- settings = CLI::Options.settings(options, env: @env, load_env: @load_env)
87
+ settings = CLI::Options.settings(options, env: @env, mode: :topology, configuration: @configuration)
81
88
  policy = settings.topology_options
82
89
  overrides = topology_overrides(options, policy)
83
90
  @settings = settings.with_overrides(overrides).for_run(mode: :topology)
@@ -89,7 +96,7 @@ module Net
89
96
  values["NC_TOPOLOGY_MODE"] = options[:topology_mode].to_s if options[:topology_mode]
90
97
  values["NC_TOPOLOGY_LIMIT"] = options[:topology_limit].to_s if options[:topology_limit]
91
98
  explicit = options.fetch(:environment)
92
- values["NC_TOPOLOGY_DIRECTORY"] = explicit["NC_BACKUP_DIRECTORY"] || policy.directory || @default_directory
99
+ values["NC_TOPOLOGY_DIRECTORY"] = explicit["NC_BACKUP_DIRECTORY"] || policy.directory || @default_directory || File.expand_path("topologys")
93
100
  values.delete("NC_TOPOLOGY_DIRECTORY") unless values["NC_TOPOLOGY_DIRECTORY"]
94
101
  values["NC_TOPOLOGY_PARALLEL"] = explicit["NC_PARALLEL"] if explicit["NC_PARALLEL"]
95
102
  values["ND_CACHE_MODE"] = explicit["ND_CACHE_MODE"] if explicit["ND_CACHE_MODE"]
@@ -6,19 +6,22 @@ require "optparse"
6
6
  require_relative "../version"
7
7
  require_relative "fleet"
8
8
  require_relative "cli/options"
9
+ require_relative "cli/setup"
9
10
 
10
11
  module Net
11
12
  module Connector
12
13
  module Netdisco
13
14
  class CLI
14
15
  # 保存命令行输入输出和清单任务工厂。
15
- def initialize(argv: ARGV, env: ENV, output: $stdout, error: $stderr,
16
- fleet_factory: ->(settings) { Fleet.new(settings: settings) })
16
+ def initialize(argv: ARGV, env: ENV, input: $stdin, output: $stdout, error: $stderr,
17
+ fleet_factory: ->(settings) { Fleet.new(settings: settings) }, configuration_options: {})
17
18
  @argv = argv.dup
18
19
  @env = env
20
+ @input = input
19
21
  @output = output
20
22
  @error = error
21
23
  @fleet_factory = fleet_factory
24
+ @configuration_options = configuration_options
22
25
  end
23
26
 
24
27
  # 解析参数并执行预览、导出或批量备份。
@@ -27,12 +30,10 @@ module Net
27
30
  return 0 if options[:done]
28
31
 
29
32
  validate_options!(options)
33
+ return 0 if initialize_config?(options)
30
34
  settings = settings_for(options)
31
35
 
32
- if options[:show_config]
33
- @output.puts JSON.pretty_generate(settings.public_config)
34
- return 0
35
- end
36
+ return show_config(settings, options) if options[:show_config]
36
37
  if options[:export]
37
38
  export_config(settings, options)
38
39
  return 0
@@ -71,10 +72,26 @@ module Net
71
72
 
72
73
  private
73
74
 
75
+ # 非敏感设置与来源在创建清单之前输出。
76
+ def show_config(settings, options)
77
+ @output.puts JSON.pretty_generate(settings.public_config.merge(sources: Options.sources(@configuration, options)))
78
+ 0
79
+ end
80
+
81
+ # 初始化仅发布用户配置,不读取清单或进入设备执行。
82
+ def initialize_config?(options)
83
+ @configuration = Options.configuration(options, env: @env, **@configuration_options)
84
+ return false unless options[:init] || options[:interactive]
85
+
86
+ mode = options[:tftp] ? :tftp : :backup
87
+ Setup.new(mode: mode, options: options, input: @input, output: @error,
88
+ configuration: @configuration, directory: File.expand_path("backups")).initialize_files?
89
+ end
90
+
74
91
  # CLI 覆盖支持的环境变量与 YAML;设备凭据按环境或显式 CLI 参数解析。
75
92
  def settings_for(options)
76
93
  mode = options[:export] ? :export : (options[:tftp] ? :tftp : :backup)
77
- Options.settings(options, env: @env).for_run(mode: mode)
94
+ Options.settings(options, env: @env, configuration: @configuration).for_run(mode: mode)
78
95
  end
79
96
 
80
97
  # 导出已有配置不创建清单或设备连接。
@@ -129,10 +146,12 @@ module Net
129
146
  args.banner = "用法:net-backup [--config FILE] [--plan | --show-config | --export IP] [--tftp]"
130
147
  Options.add_settings(args, options)
131
148
  Options.add_execution(args, options)
149
+ args.on("--init", "创建用户目录中的缺失配置和环境模板后退出") { options[:init] = true }
150
+ args.on("--interactive", "通过终端问答创建缺失配置") { options[:interactive] = true }
151
+ args.on("--non-interactive", "禁用配置问答") { options[:interactive] = false }
132
152
  args.on("--source SOURCE", %w[http postgres], "清单来源:http(默认)或 postgres") { |value| options[:source] = value }
133
153
  args.on("--query SQL", "PostgreSQL 清单查询,使用 $1、$2 绑定参数") { |value| options[:query] = value }
134
154
  args.on("--query-params JSON", "查询参数的 JSON 数组") { |value| options[:query_params] = value }
135
- args.on("--show-config", "显示生效的非敏感设置") { options[:show_config] = true }
136
155
  args.on("--plan", "预览设备清单,不连接设备") { options[:plan] = true }
137
156
  args.on("--tftp", "由设备发起 TFTP 备份") { options[:tftp] = true }
138
157
  args.on("--export IP", "导出已保存的本地配置") { |value| options[:export] = value }
@@ -42,7 +42,7 @@ module Net
42
42
  raise ArgumentError unless %w[true false].include?(value)
43
43
 
44
44
  value == "true"
45
- when :list then value.split(",").map(&:strip)
45
+ when :list then value.split(",", -1).map(&:strip)
46
46
  when :json, :json_array then JSON.parse(value)
47
47
  else value
48
48
  end
@@ -3,6 +3,7 @@
3
3
  require "yaml"
4
4
  require "tempfile"
5
5
  require_relative "../settings"
6
+ require_relative "../../config"
6
7
 
7
8
  module Net
8
9
  module Connector
@@ -16,7 +17,7 @@ module Net
16
17
  end
17
18
 
18
19
  # 完成默认值校验与可选问答后独占发布新配置,不覆盖已存在文件。
19
- def create(path:, document:, interactive: nil, mode: nil)
20
+ def create(path:, document:, interactive: nil, mode: nil, inherited_parallel: Settings::DEFAULT_PARALLEL)
20
21
  raise ArgumentError, "config path must be a nonempty String" unless path.is_a?(String) && !path.empty?
21
22
  unless interactive.nil? || [true, false].include?(interactive)
22
23
  raise ArgumentError, "interactive must be true, false or nil"
@@ -26,9 +27,10 @@ module Net
26
27
  values = YAML.safe_load(YAML.dump(document), aliases: false)
27
28
  validate!(values)
28
29
  interactive = @input.respond_to?(:tty?) && @input.tty? && @output.respond_to?(:tty?) && @output.tty? if interactive.nil?
29
- configure(values, mode: mode) if interactive && answer("进入交互配置?[y/N]", "n").casecmp?("y")
30
+ configure(values, mode: mode, inherited_parallel: inherited_parallel) if interactive && answer("进入交互配置?[y/N]", "n").casecmp?("y")
30
31
  validate!(values)
31
- write(path, YAML.dump(values))
32
+ name = mode == :topology ? "topology" : "backup"
33
+ write(path, Net::Connector::Config.dump(values, name: name, path: path))
32
34
  end
33
35
 
34
36
  # 发布环境文件模板;不收集或复制进程中的密码,也不覆盖已有文件。
@@ -55,25 +57,29 @@ module Net
55
57
  Settings.new(env: {}, defaults: Config.parse(document)).snapshot(mode: :show_config)
56
58
  end
57
59
 
58
- # 读取一行配置回答,空输入沿用默认值,输入结束则中止生成。
59
- def answer(label, default)
60
+ # 显示有效默认值;空输入可由字段选择沿用或保留继承,输入结束则中止生成。
61
+ def answer(label, default, blank: default)
60
62
  @output.print "#{label}#{default.nil? ? "" : " [#{default}]"}:"
61
63
  @output.flush
62
64
  line = @input.gets("\n")
63
65
  raise EOFError, "configuration input ended before completion" unless line
64
66
 
65
67
  value = line.chomp("\n").chomp("\r").strip
66
- value.empty? ? default : value
68
+ value.empty? ? blank : value
67
69
  end
68
70
 
69
71
  # 循环读取并校验单个配置字段,只有合法回答才更新候选配置。
70
72
  def field(document, section, key, label, default, list: false)
71
73
  values = (document[section] ||= {})
72
74
  previous = values.fetch(key, default)
75
+ label = "#{label}(留空继承)" if key == "parallel" && !values.key?(key)
73
76
  loop do
74
- text = answer(label, previous.is_a?(Array) ? previous.join(",") : previous&.to_s)
77
+ displayed = previous.is_a?(Array) ? previous.join(",") : previous&.to_s
78
+ text = answer(label, displayed, blank: key == "parallel" ? nil : displayed)
79
+ return if key == "parallel" && text.nil?
80
+
75
81
  value = if list
76
- text.to_s.empty? ? [] : text.split(",").map(&:strip)
82
+ text.to_s.empty? ? [] : text.split(",", -1).map(&:strip)
77
83
  elsif key == "parallel"
78
84
  Integer(text, exception: false)
79
85
  else
@@ -91,7 +97,7 @@ module Net
91
97
  end
92
98
 
93
99
  # 按清单来源和业务模式逐项填写非敏感配置。
94
- def configure(document, mode: nil)
100
+ def configure(document, mode: nil, inherited_parallel:)
95
101
  field(document, "netdisco", "source", "清单来源 http/postgres", "http")
96
102
  if document.dig("netdisco", "source") == "http"
97
103
  field(document, "netdisco", "url", "清单 URL", mode.nil? ? "https://netdisco.example.invalid" : nil)
@@ -102,10 +108,10 @@ module Net
102
108
  field(document, "inventory", "name_match", "名称匹配 contains/prefix/glob", "contains")
103
109
  %w[include_vendors exclude_vendors].each { |key| field(document, "inventory", key, key, [], list: true) }
104
110
  if document.key?("topology")
105
- field(document, "topology", "parallel", "拓扑并发数 1..500", 4)
111
+ field(document, "topology", "parallel", "拓扑并发数 1..500", inherited_parallel)
106
112
  field(document, "topology", "directory", "拓扑报告目录", "./topologys")
107
113
  else
108
- field(document, "backup", "parallel", "并发数 1..500", 4)
114
+ field(document, "backup", "parallel", "并发数 1..500", inherited_parallel)
109
115
  field(document, "backup", "directory", "备份目录", "./backups")
110
116
  field(document, "tftp", "server", "TFTP 服务器", nil) if mode.nil? || mode == :tftp
111
117
  end
@@ -79,14 +79,22 @@ module Net
79
79
  raise ArgumentError, "invalid YAML config (#{error.class})", cause: nil
80
80
  end
81
81
 
82
- # 文件读取与纯配置校验共用入口,初始化无需借临时文件验证。
82
+ # 文件读取与纯配置校验共用入口,保持原生 Hash 参数调用契约。
83
83
  def self.parse(document)
84
+ parse_sections(document, sections: FIELDS.keys)
85
+ end
86
+
87
+ # 按消费方职责校验选定分区;未知顶层名称仍拒绝,避免拼写错误变成空清单策略。
88
+ def self.parse_sections(document, sections:)
84
89
  raise ArgumentError, "config must be a YAML mapping" unless document.is_a?(Hash)
85
90
 
86
91
  unknown_sections = document.keys - FIELDS.keys
87
92
  raise ArgumentError, "unknown config sections: #{unknown_sections.join(", ")}" unless unknown_sections.empty?
88
93
 
94
+ sections.each { |section| FIELDS.fetch(section) }
89
95
  document.each_with_object({}) do |(section, values), result|
96
+ next unless sections.include?(section)
97
+
90
98
  fields = FIELDS.fetch(section)
91
99
  raise ArgumentError, "#{section} must be a mapping" unless values.is_a?(Hash)
92
100
 
@@ -100,6 +108,46 @@ module Net
100
108
  end
101
109
  end
102
110
 
111
+ # 配置解析与宿主环境投影共享字段范围,不把其他任务的策略带入清单消费方。
112
+ def self.environment_keys(sections: FIELDS.keys)
113
+ sections.flat_map { |section| FIELDS.fetch(section).values.map(&:first) }
114
+ end
115
+
116
+ # 只投影 schema 声明的公开环境字段;高优先级字段先遮蔽低层无效值。
117
+ def self.from_environment(environment, sections:, higher: {})
118
+ sections.each_with_object({}) do |section, result|
119
+ FIELDS.fetch(section).each do |field, (key, type)|
120
+ next unless environment.key?(key)
121
+ next if higher[section].is_a?(Hash) && higher[section].key?(field)
122
+
123
+ value = decode_environment(environment.fetch(key), type, key)
124
+ encode(section, field, type, value)
125
+ (result[section] ||= {})[field] = value
126
+ end
127
+ end
128
+ end
129
+
130
+ # 环境文本转换集中在 schema 边界,错误只指出字段,不回显输入。
131
+ def self.decode_environment(value, type, key)
132
+ raise ArgumentError unless value.is_a?(String)
133
+
134
+ case type
135
+ when :integer, :optional_integer then Integer(value, 10)
136
+ when :number then Float(value)
137
+ when :boolean
138
+ raise ArgumentError unless %w[true false].include?(value)
139
+
140
+ value == "true"
141
+ when :list then value.split(",", -1).map(&:strip)
142
+ when :json, :json_array then JSON.parse(value)
143
+ else value
144
+ end
145
+ rescue ArgumentError, TypeError, JSON::ParserError
146
+ raise ArgumentError, "invalid public environment field #{key}", cause: nil
147
+ end
148
+
149
+ private_class_method :decode_environment
150
+
103
151
  # 按字段类型校验并编码单项配置。
104
152
  def self.encode(section, name, type, value)
105
153
  case type
@@ -15,7 +15,7 @@ require_relative "report"
15
15
  require_relative "tftp/verifier"
16
16
  require_relative "tftp/archive"
17
17
  require_relative "fleet/options"
18
- require_relative "resources"
18
+ require_relative "../resources"
19
19
 
20
20
  module Net
21
21
  module Connector
@@ -9,7 +9,7 @@ require_relative "../device/interfaces"
9
9
  require_relative "settings"
10
10
  require_relative "operation/batch"
11
11
  require_relative "device/access"
12
- require_relative "resources"
12
+ require_relative "../resources"
13
13
  require_relative "worker"
14
14
 
15
15
  module Net
@@ -145,8 +145,8 @@ module Net
145
145
 
146
146
  Script.new(plan.commands)
147
147
  plan.changes.each do |change|
148
- Net::Connector::Interfaces::InterfaceDescription.validate_interface!(change.interface)
149
- Net::Connector::Interfaces::InterfaceDescription.validate!(change.new_description)
148
+ Net::Connector::Interfaces::Description.validate_interface!(change.interface)
149
+ Net::Connector::Interfaces::Description.validate!(change.new_description)
150
150
  end
151
151
  raise ArgumentError, "empty description plan cannot contain commands" if plan.changes.empty? && !plan.commands.empty?
152
152