vxlan 0.6.0 → 0.8.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c114dcb0645a2b10176e8a6cc68cdea2b517edd069c166d20b02046dddaf766a
4
- data.tar.gz: edccf86d53afb7ad825c2fd468dcaba21ebda26a7b2330233fc2461840ba220f
3
+ metadata.gz: 3a0904488ebdedf6f5983003bf51724e3e0c5442b2347fb6433041da8f858394
4
+ data.tar.gz: 8c1b2e0ba07891754cb6074e5da60a2174b6a96508309836bdc4db333ce7414e
5
5
  SHA512:
6
- metadata.gz: 34c6082ad93884802d028f56cb2821cb8ae057537ba4618d7dab6e9edb3d73d27dfaebf8a6e99e502f334aecd9617e5aacc0c579070121e7c2364a5a78e3c185
7
- data.tar.gz: 51864b6ddf301c26c41f3eb3fb77b46a2baa32d8047f0f806595a839ef20e32e976c022843bc7bf208794ec54ac12ed31ee2b158f9647cf1e824c191b5bd9fb1
6
+ metadata.gz: a51c259e1059d12babf19d1789e6ae9e3dba5fdaae8b612aad552aca488665b44f2ca2d25e7cec825b781b39ad8b887ee5c71b648a12da03fd6dc4b5f3d7561a
7
+ data.tar.gz: 6d37d517bcc3d7c8e8f143917449bbe450d2f79c54ca64c9032ace956f8db265ed86fbb4ee6e76f4fdf88ea68f74155408cecbf0f14aee20f5e297818b82f07e
data/CHANGELOG.md CHANGED
@@ -4,6 +4,17 @@ Changes to the public contract are recorded here. Versions follow Semantic Versi
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.8.0 (2026-10-30)
8
+
9
+ - Adopt schema 4 Target/Source contracts and shared configuration read/write sessions. Validate target platform before opening a connector. Normalize BGP to `peer_address`, `afi_safi`, `received_prefixes` and symbolic states; CDP uses `local_interface`, `remote_interface`, `remote_name`. Require connector 0.21 for collection.
10
+
11
+ ## 0.7.0 (2026-10-29)
12
+
13
+ - Compose the shared snapshot contract and remove the synthetic collection observation. Whitelist public target identities and validate timestamps and dimensions.
14
+ - Normalize OSPF process_id, router_id, neighbor_address, symbolic state and neighbor_role while retaining priority and uptime.
15
+ - Delegate interactive apply to ctx_cli, resolving credentials through net-connector, including empty overrides and platform enable passwords.
16
+ - Use schema 3 reports and named checksummed plans. Older files must be regenerated.
17
+
7
18
  ## 0.6.0 (2026-10-29)
8
19
 
9
20
  - Require RuntimeParser platform at construction and add parse_many. Rename Snapshot Ruby members to observations/observation while retaining dimensions in persisted reports. Use Catalog and shared Credentials in CLI; reject selected duplicate addresses across platforms before connecting.
data/README.md CHANGED
@@ -146,6 +146,12 @@ Offline review requires `snapshot.target.host` to match the canonical device hos
146
146
 
147
147
  ## API migration
148
148
 
149
- `RuntimeParser.new(platform:, model: nil)` fixes the platform for `parse(name, text, complete: false, command: nil)` and `parse_many(names, text, complete: false, command: nil)`. Snapshots use `observations:` and expose `observations` / `observation(name)`; the old Ruby `dimensions` member and Wireless `dimension` accessor are removed. Known missing dimensions return `not_requested`; unknown names raise `ArgumentError`. Persisted JSON keeps its `dimensions` field.
149
+ `RuntimeParser.new(platform:, model: nil)` fixes the platform for `parse(name, text, complete: false, command: nil)` and `parse_many(names, text, complete: false, command: nil)`. Snapshots use `observations:` and expose `observations` / `observation(name)`; the old Ruby `dimensions` member and Wireless `dimension` accessor are removed. Known missing dimensions return `not_requested`; unknown names raise `ArgumentError`. Persisted schema 4 JSON uses `observations` and an independent `collection_status`; regenerate older reports.
150
150
 
151
151
  Dynamic inventory uses `Netdisco::Catalog`. Any duplicate row for a selected address, including another platform, prevents connection; excluded conflicts retain safe diagnostics. `NC_<PLATFORM>_ENABLE_PASSWORD` takes precedence over `NC_ENABLE_PASSWORD`.
152
+
153
+ 本次契约升级要求重新生成旧报告和计划;Ruby 快照使用 `observations`、`collection_status` 和 `Time`,JSON 通过 `CtxRunner::Document` 输出 UTC ISO8601(解析基础库仅提供 `Result`)。跨模块约定见 [ctx_runner 契约迁移](https://github.com/gatework/ctx_runner/blob/main/docs/contracts-2026-10-29.md)。
154
+
155
+ ## Domain contract migration (2026-10-30)
156
+
157
+ Adopt schema 4 Target/Source contracts and shared configuration read/write sessions. Validate target platform before opening a connector. Normalize BGP to `peer_address`, `afi_safi`, `received_prefixes` and symbolic states; CDP uses `local_interface`, `remote_interface`, `remote_name`. Require connector 0.21 for collection. See the [schema 4 migration and module contracts](https://github.com/gatework/ctx_runner/blob/main/docs/contracts-2026-10-30.md). Regenerate old collection reports and change plans; changing only their version number is not supported.
@@ -8,13 +8,13 @@ module Vxlan
8
8
  # 从 BGP 汇总解析 EVPN 邻居状态及可选路由类型统计。
9
9
  class ShowBgpL2vpnEvpnSummary < Parser
10
10
  EMPTY = "(?:BGP )?neighbors"
11
- IDENTITY = %i[vrf address_family peer_ip].freeze
11
+ IDENTITY = %i[vrf afi_safi peer_address].freeze
12
12
  BOUNDARY = /^\s*BGP summary information for VRF /
13
13
  SCOPE = /\ABGP summary information for VRF (\S+), address family (.+)\z/
14
14
  ROUTER = /\ABGP router identifier (\S+), local AS number (\S+)\z/
15
15
  HEADER = /\ANeighbor\s+V\s+AS\s+MsgRcvd\s+MsgSent\s+TblVer\s+InQ\s+OutQ\s+Up\/Down\s+State\/PfxRcd\z/i
16
16
  ROW = /\A([\da-f:.]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)\z/i
17
- FIELDS = %i[peer_ip version remote_as messages_received messages_sent table_version input_queue output_queue uptime state].freeze
17
+ FIELDS = %i[peer_address version remote_as messages_received messages_sent table_version input_queue output_queue uptime state].freeze
18
18
  INTEGERS = %i[version remote_as messages_received messages_sent table_version input_queue output_queue].freeze
19
19
  PREFIX_TYPES = %i[type1 type2 type3 type4 type5 type6 type7 type8 type12].freeze
20
20
  TABLE = /\ABGP table version is \d+(?:, L2VPN EVPN config peers (\d+), capable peers (\d+))?\z/i
@@ -29,7 +29,7 @@ module Vxlan
29
29
  scope, identities, invalid = nil, {}, {}
30
30
  text.each_line("\n") do |line|
31
31
  if (match = SCOPE.match(line.strip))
32
- scope = match.captures
32
+ scope = [ match[1], match[2] == "L2VPN EVPN" ? "l2vpn_evpn" : match[2] ]
33
33
  elsif (match = ROUTER.match(line.strip))
34
34
  identity = router_identity(match)
35
35
  if !identity
@@ -42,10 +42,10 @@ module Vxlan
42
42
  end
43
43
  end
44
44
  invalid.each do |key, code|
45
- issue = { code: code, vrf: key&.first, address_family: key&.last }
45
+ issue = { code: code, vrf: key&.first, afi_safi: key&.last }
46
46
  @issues << issue unless @issues.include?(issue)
47
47
  end
48
- @rows.reject! { |row| invalid.key?(row.values_at(:vrf, :address_family)) }
48
+ @rows.reject! { |row| invalid.key?(row.values_at(:vrf, :afi_safi)) }
49
49
  end
50
50
 
51
51
  # ASDOT 与 ASPLAIN 用同一数值比较;无效身份不能附着到完整邻居事实。
@@ -67,8 +67,8 @@ module Vxlan
67
67
  @header = true
68
68
  prefix_columns = nil
69
69
  elsif (match = SCOPE.match(line))
70
- scope = { vrf: match[1], address_family: match[2] }
71
- unparsed_records(number) unless scope[:address_family] == "L2VPN EVPN"
70
+ scope = { vrf: match[1], afi_safi: match[2] == "L2VPN EVPN" ? "l2vpn_evpn" : match[2] }
71
+ unparsed_records(number) unless scope[:afi_safi] == "l2vpn_evpn"
72
72
  prefix_columns = nil
73
73
  elsif (match = ROUTER.match(line))
74
74
  scope.merge!(router_id: match[1], local_as: match[2])
@@ -89,7 +89,7 @@ module Vxlan
89
89
  if statistics && !prefix_seen.key?(statistics.first.object_id)
90
90
  peer, counts = statistics
91
91
  # 路由类型是总前缀的子集;未展示的类型允许存在,已展示之和不能超过总数。
92
- if peer[:prefixes_received] && counts.sum > peer[:prefixes_received]
92
+ if peer[:received_prefixes] && counts.sum > peer[:received_prefixes]
93
93
  @issues << { code: :inconsistent_prefix_statistics, line: number }
94
94
  else
95
95
  peer[:prefixes_by_type] = prefix_columns.zip(counts).to_h
@@ -106,7 +106,7 @@ module Vxlan
106
106
  end
107
107
  @rows << row
108
108
  # 统计表按完整作用域查找;重复邻居仍由最终身份检查整体隔离。
109
- peers[row.values_at(:vrf, :address_family, :peer_ip)] ||= row
109
+ peers[row.values_at(:vrf, :afi_safi, :peer_address)] ||= row
110
110
  else
111
111
  unparsed_records(number)
112
112
  end
@@ -125,25 +125,30 @@ module Vxlan
125
125
  count_mismatch(configured, @rows.size)
126
126
  @issues << { code: :invalid_peer_counts, configured: configured, capable: capable } if capable > configured
127
127
  end
128
- @empty = true if values == [ [ 0, 0 ] ] && @rows.empty? && scope[:address_family] == "L2VPN EVPN"
128
+ @empty = true if values == [ [ 0, 0 ] ] && @rows.empty? && scope[:afi_safi] == "l2vpn_evpn"
129
129
  end
130
130
 
131
131
  # AS 0 只表示尚未建立邻居的未知身份;数值前缀总数始终表示已建立会话。
132
132
  def neighbor_record(match, scope)
133
133
  row = FIELDS.zip(match.captures).to_h.merge(scope)
134
134
  INTEGERS.each { |key| row[key] = row[key].to_i }
135
- return unless row[:vrf] && row[:address_family] == "L2VPN EVPN" && ip_address?(row[:peer_ip]) && row[:version] == 4 &&
135
+ return unless row[:vrf] && row[:afi_safi] == "l2vpn_evpn" && ip_address?(row[:peer_address]) && row[:version] == 4 &&
136
136
  (0..4_294_967_295).cover?(row[:remote_as]) && STATE.match?(row[:state])
137
137
 
138
- row[:prefixes_received] = row[:state].match?(/\A\d+\z/) ? row[:state].to_i : nil
138
+ row[:received_prefixes] = row[:state].match?(/\A\d+\z/) ? row[:state].to_i : nil
139
139
  row[:remote_as] = row[:remote_as].nonzero?
140
- return if row[:prefixes_received] && row[:remote_as].nil?
140
+ return if row[:received_prefixes] && row[:remote_as].nil?
141
141
 
142
- row[:peer_ip] = CtxParser::Values.ip_address(row[:peer_ip], allow_zone: true)
143
- row[:state] = row[:prefixes_received] ? "established" : row[:state].downcase.tr(" ", "_")
142
+ row[:peer_address] = CtxParser::Values.ip_address(row[:peer_address], allow_zone: true)
143
+ row[:state] = row[:received_prefixes] ? :established : state_value(row[:state])
144
144
  row
145
145
  end
146
146
 
147
+ def state_value(value)
148
+ return :shutdown if /admin|shutdown/i.match?(value)
149
+ value.downcase.to_sym
150
+ end
151
+
147
152
  # 从末尾读取类型计数,保留多词状态,并按主表身份与总数关联统计。
148
153
  def prefix_record(line, scope:, peers:, columns:, total:)
149
154
  words = line.split(" ")
@@ -154,14 +159,14 @@ module Vxlan
154
159
  return unless ip_address?(address) && %w[I E].include?(kind) && asn.match?(/\A\d+\z/) && counts.all? { |value| value.match?(/\A\d+\z/) }
155
160
 
156
161
  address = CtxParser::Values.ip_address(address, allow_zone: true)
157
- peer = peers[[ scope[:vrf], scope[:address_family], address ]]
162
+ peer = peers[[ scope[:vrf], scope[:afi_safi], address ]]
158
163
  return unless peer && peer[:remote_as] == asn.to_i.nonzero?
159
164
 
160
165
  if total
161
166
  value = words.join(" ")
162
167
  return unless STATE.match?(value)
163
- observed = value.match?(/\A\d+\z/) ? value.to_i : value.downcase.tr(" ", "_")
164
- return unless observed == (peer[:prefixes_received] || peer[:state])
168
+ observed = value.match?(/\A\d+\z/) ? value.to_i : state_value(value)
169
+ return unless observed == (peer[:received_prefixes] || peer[:state])
165
170
  else
166
171
  return unless words.empty?
167
172
  end
@@ -8,7 +8,7 @@ module Vxlan
8
8
  # 在所属邻居记录内解释 CDP 详细字段。
9
9
  class ShowCdpNeighborsDetail < Parser
10
10
  EMPTY = "(?:CDP neighbors|CDP entries|neighbors|entries)".freeze
11
- IDENTITY = %i[device_id interface neighbor_interface].freeze
11
+ IDENTITY = %i[device_id local_interface remote_interface].freeze
12
12
 
13
13
  private
14
14
 
@@ -39,7 +39,7 @@ module Vxlan
39
39
  end
40
40
  case line
41
41
  when /\A--More--/i then unparsed_records(number)
42
- when /\ASystem Name:\s*(\S.*)\z/i then assign_field(row, :neighbor_name, $1, number)
42
+ when /\ASystem Name:\s*(\S.*)\z/i then assign_field(row, :remote_name, $1, number)
43
43
  when /\AInterface address\(es\):(?:\s+\d+)?\z/i then scope = :interface_addresses
44
44
  when /\AMgmt address\(es\):(?:\s+\d+)?\z/i then scope = :management_addresses
45
45
  when /\AIP(?:v[46])? Address:\s*(\S+)\z/i
@@ -55,9 +55,9 @@ module Vxlan
55
55
  assign_field(row, :capabilities, capabilities, number)
56
56
  scope = nil
57
57
  when /\AInterface:\s*(\S+),\s*Port ID \(outgoing port\):\s*(\S.*)\z/i
58
- interface, neighbor_interface = $1, $2
59
- assign_field(row, :interface, interface, number)
60
- assign_field(row, :neighbor_interface, neighbor_interface, number)
58
+ interface, remote_interface = $1, $2
59
+ assign_field(row, :local_interface, interface, number)
60
+ assign_field(row, :remote_interface, remote_interface, number)
61
61
  scope = nil
62
62
  when /\AHoldtime:\s*(\d+) sec\z/i then assign_field(row, :holdtime, $1.to_i, number)
63
63
  when /\AVersion:\z/i
@@ -81,10 +81,10 @@ module Vxlan
81
81
  totals.each { |total| count_mismatch(total, @rows.size) }
82
82
  @empty = true if totals == [ 0 ] && @rows.empty?
83
83
  @rows.reject! do |entry|
84
- next true if @field_conflicts.fetch(entry, {}).keys.intersect?(%i[neighbor_name interface neighbor_interface])
84
+ next true if @field_conflicts.fetch(entry, {}).keys.intersect?(%i[remote_name local_interface remote_interface])
85
85
 
86
- entry[:neighbor_name] ||= entry[:device_id].sub(/\([^)]*\)\z/, "").split(".").first
87
- if entry.values_at(:neighbor_name, :interface, :neighbor_interface).any? { |value| value.nil? || value.empty? }
86
+ entry[:remote_name] ||= entry[:device_id].sub(/\([^)]*\)\z/, "").split(".").first
87
+ if entry.values_at(:remote_name, :local_interface, :remote_interface).any? { |value| value.nil? || value.empty? }
88
88
  @issues << { code: :incomplete_cdp_neighbor }
89
89
  true
90
90
  end
@@ -8,11 +8,11 @@ module Vxlan
8
8
  # 逐进程、VRF 独立核对 OSPF 邻居总数。
9
9
  class ShowIpOspfNeighbors < Parser
10
10
  EMPTY = "(?:OSPF )?neighbors"
11
- IDENTITY = %i[process vrf neighbor_id interface].freeze
11
+ IDENTITY = %i[process_id vrf router_id interface].freeze
12
12
  BOUNDARY = /^\s*OSPF Process ID /
13
13
  HEADER = /\ANeighbor ID\s+Pri\s+State\s+Up Time\s+Address\s+Interface\z/i
14
14
  ROW = /\A([\d.]+)\s+(\d+)\s+(\S+(?:\/\s*\S+)?)\s+(\S+)\s+([\d.]+)\s+(\S+)\z/
15
- FIELDS = %i[neighbor_id priority state uptime address interface].freeze
15
+ FIELDS = %i[router_id priority state uptime neighbor_address interface].freeze
16
16
 
17
17
  private
18
18
 
@@ -23,18 +23,20 @@ module Vxlan
23
23
  if HEADER.match?(line)
24
24
  @header = true
25
25
  elsif (match = /\AOSPF Process ID (\S+) VRF (\S+)\z/i.match(line))
26
- scope = { process: match[1], vrf: match[2] }
26
+ scope = { process_id: match[1], vrf: match[2] }
27
27
  elsif (match = /\ATotal number of neighbors:\s*(\d+)\z/i.match(line))
28
28
  totals << match[1].to_i
29
29
  elsif (match = ROW.match(line))
30
30
  row = FIELDS.zip(match.captures).to_h.merge(scope)
31
31
  row[:priority] = row[:priority].to_i
32
- unless ip_address?(row[:neighbor_id]) && ip_address?(row[:address]) && (0..255).cover?(row[:priority]) &&
32
+ unless ip_address?(row[:router_id]) && ip_address?(row[:neighbor_address]) && (0..255).cover?(row[:priority]) &&
33
33
  row[:state].match?(/\A(?:DOWN|ATTEMPT|INIT|2WAY|EXSTART|EXCHANGE|LOADING|FULL)\/(?:\s*(?:DR|BDR|DROTHER|-))\z/i)
34
34
  unparsed_records(number)
35
35
  next
36
36
  end
37
- @rows << row.merge(state: row[:state].downcase.delete(" "))
37
+ state, role = row[:state].downcase.delete(" ").split("/", 2)
38
+ @rows << row.merge(state: state == "2way" ? :two_way : state.to_sym,
39
+ neighbor_role: role == "-" ? :unknown : role.to_sym)
38
40
  else
39
41
  unparsed_records(number)
40
42
  end
@@ -8,10 +8,10 @@ module Vxlan
8
8
  # 解析 NVE 端点及路由器 MAC,支持终端换行记录。
9
9
  class ShowNvePeers < Parser
10
10
  EMPTY = "peers"
11
- IDENTITY = %i[interface peer_ip].freeze
11
+ IDENTITY = %i[interface peer_address].freeze
12
12
  HEADER = /\AInterface\s+Peer-IP\s+State\s+LearnType\s+Uptime\s+Router-Mac\z/i
13
13
  ROW = /\A(nve\d+)\s+(\d+(?:\.\d+){3})\s+(Up|Down)\s+(\S+)\s+(\S+)\s+([\da-f]{4}(?:\.[\da-f]{4}){2}|n\/a)\z/i
14
- FIELDS = %i[interface peer_ip state learn_type uptime router_mac].freeze
14
+ FIELDS = %i[interface peer_address state learn_type uptime router_mac].freeze
15
15
 
16
16
  private
17
17
 
@@ -1,134 +1,57 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "ctx_cli/command"
4
- require "ctx_cli/terminal"
5
- require "ctx_cli/input"
6
- require "ctx_cli/output"
7
- require "json"
3
+ require "ctx_cli/apply"
8
4
  require "ctx_runner/document"
9
- require "digest"
5
+ require "ctx_runner/evidence"
10
6
  require "ctx_runner/execution"
11
- require "ipaddr"
7
+ require "ctx_runner/configuration_session"
12
8
  require "vxlan"
13
9
  require_relative "report"
14
10
  require_relative "../change_plan"
15
11
 
16
12
  module Vxlan
17
13
  module CLI
18
- # 原生会话适配:读取使用固定查询提示符,写入由连接器识别配置模式提示符。
19
- class ApplySession
20
- # 借用一次已连接且独占的会话,不重连、不重放。
14
+ # 领域仅声明准备命令及配置语法,共享会话维护回执和读取边界。
15
+ class ApplySession < CtxRunner::ConfigurationSession
21
16
  def initialize(native)
22
- @native = native
23
- end
24
-
25
- # 读回完整配置并交给现有解析器;部分证据不能参与前置检查或验收。
26
- def read_configuration
27
- [ "terminal length 0", "terminal width 511" ].each { |command| write(command) }
28
- capture = CtxDriver::Reader.new(session: @native).read("show running-config")
29
- raise IOError, "Configuration readback failed" unless capture.success?
30
- observation = Vxlan::Config.new.parse(capture.body, complete: true)
31
- raise ArgumentError, "Configuration evidence is incomplete" unless observation.complete? && observation.records.one?
32
- CtxRunner::Document.call(observation.records.first)
33
- end
34
-
35
- # 每次只发一条命令;失败立即交还宿主,原始输出不进入终端和日志报告。
36
- def write(command)
37
- result = @native.execute_command(command.strip, output_sensitive: true)
38
- raise IOError, "Device command is unconfirmed" unless result.success? && result.steps.one?
39
- true
17
+ super(session: CtxDriver::Session.new(native), preparation_commands: [ "terminal length 0", "terminal width 511" ],
18
+ configuration_command: "show running-config", parser: Vxlan::Config.new)
40
19
  end
41
20
  end
42
21
 
43
- # 交互式单设备下发:展示、确认、重新读取、记录意图、执行、回读,禁止无人值守确认。
22
+ # 领域适配器只维护计划类型、凭据来源与独占设备会话。
44
23
  class Apply
45
- # 注入连接工厂仅用于宿主集成和离线失败测试。
46
24
  def initialize(env: ENV, out: $stdout, error: $stderr, input: $stdin, connector_factory: nil, discovery: {})
47
- @env, @out, @error, @input, @factory = env, out, error, input, connector_factory
48
- @discovery = discovery
49
- @output = CtxCli::Output.new(out: out, error: error)
25
+ @env, @factory, @discovery = env, connector_factory, discovery
26
+ @entry = CtxCli::Apply.new(adapter: self, execution: CtxRunner::Execution, name: "vxlan", out: out, error: error, input: input)
50
27
  end
51
28
 
52
- # 没有 --yes 或自动回退;零退出码只确认配置回读,不声称业务已验收。
53
- def run(argv)
54
- @store, @execution = nil, nil
55
- command = CtxCli::Command.new(banner: "Usage: vxlan apply --plan FILE --item ID [--env-file FILE] (requires explicit confirmation in an interactive terminal)",
56
- defaults: { directory: File.join(Dir.pwd, "vxlan-executions"), port: 22 }, out: @out) do |p, options|
57
- p.on("--plan FILE", "Batch plan.json; requires a SHA256 checksum file in the same directory") { |value| options[:plan] = value }
58
- p.on("--item ID", "Explicitly select one change from the batch plan; bulk execution is prohibited") { |value| options[:item] = value }
59
- p.on("--env-file FILE", "Explicit credentials file; process environment takes precedence") { |value| options[:env_file] = value }
60
- p.on("--directory DIR", "Private execution log directory") { |value| options[:directory] = value }
61
- p.on("--port N", Integer, "SSH port, default 22") { |value| options[:port] = value }
62
- p.on("-h", "--help", "Show help without connecting to devices") { options[:help] = true }
63
- end
64
- options = command.parse(argv)
65
- return 0 if command.informational?
66
- terminal = CtxCli::Terminal.new(input: @input, out: @out)
67
- terminal.require_tty!(@error)
68
- raise ArgumentError, "A single plan is required" unless options[:plan] && options[:port].between?(1, 65_535)
69
- body = CtxCli::Input.read(path: options[:plan])
70
- hash = Digest::SHA256.hexdigest(body)
71
- plan = CtxParser::Immutable.copy(select_plan(JSON.parse(body), options, hash))
72
- change = validate_plan(plan)
73
- host = plan.fetch("device").fetch("host")
74
- @out.puts "Target: #{plan['device']['name']}(#{host}); #{plan['scope']}; #{plan['title']}"
75
- @out.puts "Impact: #{plan['impact']}"
76
- @out.puts Array(plan["prerequisites"]).map { |value| "Prerequisite: #{value}" }
77
- @out.puts "Plan SHA256: #{hash}\nProposed commands:\n#{change.commands.join("\n")}\nConditional rollback (not executed automatically):\n#{change.rollback.join("\n")}"
78
- token = "APPLY #{host} #{hash[0, 12]} #{options[:item]}"
79
- confirmed = terminal.confirm(token: token, prompt: "After confirming the service policy and maintenance window, enter #{token}; any other input cancels: ")
80
- return @out.puts("Cancelled; no device connection opened.") || 1 unless confirmed
81
- settings = credentials(options)
82
- @store = Report.new(options[:directory])
83
- @execution = CtxRunner::Execution.new(plan: plan, change: change, journal: @store, plan_sha256: hash, item: options[:item])
84
- @execution.run { |operation| with_session(plan["device"], settings, &operation) }
85
- @out.puts "Configuration readback confirmed; service acceptance is still required. Configuration was not saved to startup configuration. Log: #{@store.directory}/execution.json"
86
- 0
87
- rescue Interrupt
88
- report_journal_failure
89
- @output.diagnostic "Operation interrupted; #{@execution&.started? ? 'Device effects may be incomplete; read back and verify before proceeding. Do not replay commands.' : 'No service configuration was sent.'}"
90
- 130
91
- rescue StandardError, LoadError => error
92
- report_journal_failure
93
- @output.diagnostic "Apply stopped (#{error.class.name}); #{@execution&.started? ? 'Effects are not fully confirmed; read back first. No automatic replay or rollback.' : 'No service configuration was sent; check the terminal, plan, credentials and current configuration for consistency.'}"
94
- 2
95
- end
29
+ def run(argv) = @entry.run(argv)
96
30
 
97
- private
98
-
99
- # 聚合文件必须校验哈希并选中唯一动作;绝不隐式选择第一项或循环执行。
100
- def select_plan(document, options, hash)
101
- id = options[:item]
102
- unless document.is_a?(Hash) && document["schema_version"] == 2 && document["platform"] == "cisco_nxos" && document["changes"].is_a?(Hash) &&
103
- id.is_a?(String) && id.match?(/\A[A-Za-z0-9_.-]+\z/) && document["changes"].key?(id)
104
- raise ArgumentError, "A batch plan and valid --item are required"
105
- end
106
- raise ArgumentError, "Plan checksum verification failed" unless CtxCli::Input.read(path: "#{options[:plan]}.sha256", max_bytes: 128).strip == hash
107
- document["changes"].fetch(id)
31
+ def select_plan(document, item:)
32
+ CtxRunner::Evidence.plan(document, item: item, platform: "cisco_nxos")
108
33
  end
109
34
 
110
- # 不信任文件中的命令,重新从有限动作渲染并逐字核对,拒绝额外命令。
35
+ # 从类型化增量重新生成命令,拒绝修改后的任意脚本。
111
36
  def validate_plan(plan)
112
- raise ArgumentError, "Plan type mismatch" unless plan.is_a?(Hash) && plan["schema_version"] == 1 && plan["platform"] == "cisco_nxos"
113
- host = plan.fetch("device").fetch("host")
114
- raise ArgumentError, "Invalid target address" unless host.is_a?(String) && !host.include?("/") && IPAddr.new(host).to_s == host
115
- raise ArgumentError, "Invalid configuration fingerprint" unless plan["expected_config_sha256"].is_a?(String) && plan["expected_config_sha256"].match?(/\A[0-9a-f]{64}\z/)
116
37
  change = ChangePlan.build(plan.fetch("change"))
117
- raise ArgumentError, "Plan commands were modified" unless change.commands == plan["commands"] && change.rollback == plan["rollback"]
38
+ unless change.commands == plan["commands"] && change.rollback == plan["rollback"]
39
+ raise ArgumentError, "Plan commands were modified"
40
+ end
118
41
  change
119
42
  end
120
43
 
121
- # 共用分层环境加载器,显式文件最高、进程环境优先;凭据不进入计划或日志。
122
44
  def credentials(options)
123
45
  require "net/connector/config"
46
+ require "net/connector/credentials"
124
47
  env = Net::Connector::Config.new(name: "vxlan", env: @env, env_file: options[:env_file], **@discovery).load_environment.environment
125
- username = env["NC_CISCO_NXOS_USERNAME"] || env["NC_DEVICE_USERNAME"]
126
- raise ArgumentError, "Device username is missing" unless username.is_a?(String) && !username.strip.empty?
127
- { username: username, password: env["NC_CISCO_NXOS_PASSWORD"] || env["NC_DEVICE_PASSWORD"], enable_password: env["NC_ENABLE_PASSWORD"],
128
- port: options[:port], host_key_policy: "strict", command_timeout: 60, login_timeout: 15 }
48
+ credentials = Net::Connector::Credentials.new(env: env).resolve(platform: :cisco_nxos)
49
+ raise ArgumentError, "Device username is missing" unless credentials
50
+ credentials.merge(port: options[:port], host_key_policy: "strict", command_timeout: 60, login_timeout: 15)
129
51
  end
130
52
 
131
- # 原生会话只打开一次,读写处于同一操作租约中。
53
+ def report(options) = Report.new(options.fetch(:directory))
54
+
132
55
  def with_session(device, settings, &operation)
133
56
  return @factory.call(device, settings, &operation) if @factory
134
57
  require "net/connector"
@@ -137,13 +60,9 @@ module Vxlan
137
60
  end
138
61
  end
139
62
 
140
- # 公共执行器保存失败状态;CLI 只呈现持久性尚未确认的诊断。
141
- def report_journal_failure
142
- return unless @execution&.journal_failed?
143
- @output.diagnostic "Execution log finalization is unconfirmed; existing checkpoints retained. Do not replay configuration based on this state."
144
- rescue Interrupt
145
- nil
146
- end
63
+ def inspect = "#<#{self.class.name}>"
64
+ alias to_s inspect
65
+ def pretty_print(printer) = printer.text(inspect)
147
66
  end
148
67
  end
149
68
  end
@@ -34,7 +34,7 @@ module Vxlan
34
34
  def load_network
35
35
  require "net/connector"
36
36
  rescue LoadError
37
- raise LoadError, "Online collection requires net-connector >= 0.19.0; add it to the host Gemfile or run gem install net-connector", cause: nil
37
+ raise LoadError, "Online collection requires net-connector >= 0.21.0; add it to the host Gemfile or run gem install net-connector", cause: nil
38
38
  end
39
39
 
40
40
  # YAML 静态设备或显式 Netdisco 来源二选一;选中地址的所有冲突记录在连接前拒绝。
@@ -6,7 +6,7 @@ require "optparse"
6
6
  require "ctx_cli/options"
7
7
  require "ctx_cli/terminal"
8
8
  require "ctx_cli/initializer"
9
- gem "net-connector", "~> 0.19.0"
9
+ gem "net-connector", "~> 0.21.0"
10
10
  require "net/connector/inventory/filters"
11
11
  require "yaml"
12
12
  require "ipaddr"
@@ -67,7 +67,7 @@ module Vxlan
67
67
  @environment = @files.environment
68
68
  @config, @env_file = @files.config, @files.env_file
69
69
  rescue LoadError
70
- raise LoadError, "Collection configuration requires net-connector >= 0.19.0; reading .env also requires dotenv", cause: nil
70
+ raise LoadError, "Collection configuration requires net-connector >= 0.21.0; reading .env also requires dotenv", cause: nil
71
71
  end
72
72
 
73
73
  # 公共与专用文件先合并,进程值和 CLI 最后覆盖;数组不追加设备。
@@ -211,12 +211,12 @@ module Vxlan
211
211
 
212
212
  # 设备身份只接受公开字段,拒绝隐藏在 YAML 中的密码或连接参数。
213
213
  def normalize_device(row)
214
- unless row.is_a?(Hash) && (row.keys - %w[host name model]).empty? && row["host"].is_a?(String) && !row["host"].include?("/")
214
+ unless row.is_a?(Hash) && (row.keys - %w[host name model platform]).empty? && (!row.key?("platform") || row["platform"] == "cisco_nxos") && row["host"].is_a?(String) && !row["host"].include?("/")
215
215
  raise ArgumentError, "devices accepts only host, name and model; host must be a single IP address"
216
216
  end
217
217
  host = IPAddr.new(row.fetch("host")).to_s
218
218
  %w[name model].each { |key| raise ArgumentError, "Device #{key} must be a nonempty string" if row.key?(key) && !row[key].nil? && (!row[key].is_a?(String) || row[key].strip.empty?) }
219
- { "host" => host, "name" => row["name"] || host, "model" => row["model"] }.freeze
219
+ { "platform" => "cisco_nxos", "host" => host, "name" => row["name"] || host, "model" => row["model"] }.freeze
220
220
  rescue IPAddr::Error
221
221
  raise ArgumentError, "Invalid device host", cause: nil
222
222
  end
@@ -4,6 +4,7 @@ require "json"
4
4
  require "time"
5
5
  require "ctx_runner/report"
6
6
  require "ctx_runner/document"
7
+ require "ctx_runner/evidence"
7
8
  require_relative "review/report"
8
9
  require_relative "review/fabric"
9
10
 
@@ -27,20 +28,20 @@ module Vxlan
27
28
  def write_execution(state) = @report.write_execution(state)
28
29
 
29
30
  # 采集和离线审查共用稳定名称,保留 IPv6 地址并避免设备名成为路径。
30
- def self.device_basename(device)
31
+ def self.target_basename(device)
31
32
  "#{device.fetch('name').gsub(/[^A-Za-z0-9_.-]/, '_')[0, 100]}-#{device.fetch('host').gsub(/[^A-Za-z0-9_.-]/, '_')}"
32
33
  end
33
34
 
34
35
  # 每台完成后立即原子保存,即使批次随后取消仍可读取已完成证据。
35
36
  def write(result, snapshot: nil)
36
- device = result.fetch(:device)
37
- name = self.class.device_basename(device)
37
+ device = result.fetch(:target)
38
+ name = self.class.target_basename(device)
38
39
  # 保存状态属于批次宿主;不能让正在发布的文件预先声明自身已保存。
39
40
  body = result.reject { |key, _| key == :report_saved }.merge(snapshot: snapshot && snapshot.to_h)
40
- document = CtxRunner::Document.call(body)
41
+ document = CtxRunner::Evidence.wrap(body, kind: "collection")
41
42
  advice = report_advice(Recommendations.new(document).call)
42
43
  document = document.merge("recommendations" => advice)
43
- json = JSON.pretty_generate(document) + "\n"
44
+ json = JSON.pretty_generate(document, max_nesting: 128) + "\n"
44
45
  prepare_directory(File.join(directory, "evidence"))
45
46
  publish("evidence/#{name}.json", json)
46
47
  write_review(document, basename: name, source: File.join(directory, "evidence", "#{name}.json"), source_sha256: Digest::SHA256.hexdigest(json), advice: advice)
@@ -60,7 +61,7 @@ module Vxlan
60
61
  text << "Progress output error: #{summary['output_error']['error_type']}; device results retained" if summary["output_error"]
61
62
  summary.fetch("devices").each do |r|
62
63
  saved = r["report_saved"] == true ? "saved" : "persistence unconfirmed"
63
- text << "#{r['device']['host']}\t#{r['device']['name']}\t#{r['status']}\t#{saved}\t#{r['error']}"
64
+ text << "#{r['target']['host']}\t#{r['target']['name']}\t#{r['status']}\t#{saved}\t#{r['error']}"
64
65
  end
65
66
  pending.each { |device| text << "#{device['host']}\t#{device['name']}\tnot collected" }
66
67
  text.join("\n") + "\n"
@@ -12,7 +12,7 @@ module Vxlan
12
12
  module Fabric
13
13
  # 相同事实合并展示;规则版本保持匹配顺序,完整证据由聚合计划保存。
14
14
  def fabric_text(audit, documents)
15
- by_host = documents.to_h { |document| [ document.fetch("device").fetch("host"), document ] }
15
+ by_host = documents.to_h { |document| [ document.fetch("target").fetch("host"), document ] }
16
16
  lines = [ "Fabric shared-service consistency", "Scope: compare shared VNIs within explicit Fabrics and roles; compare Leaf and Border separately, and check Spine for service-bearing configuration.", "Deployment facts combine VLAN/NVE/EVPN evidence; incomplete deployment does not mean absence. Deployment scope differences are retained.", "ACL comparison includes ordered rules and dependencies; a majority without an ACL is not grounds for removal.", "" ]
17
17
  inventory = audit[:inventory]
18
18
  if inventory
@@ -23,7 +23,7 @@ module Vxlan
23
23
  services = audit[:coverage].select { |entry| entry[:fabric] == fabric && entry[:role] == role }
24
24
  partial = services.select { |entry| entry[:incomplete].any? }
25
25
  lines << " #{role}: deployed services #{services.size}, services shared across devices #{services.count { |entry| entry[:deployed].size >= 2 }}, incomplete associations #{partial.size}."
26
- partial.each { |entry| lines << " VNI #{entry[:vni]} missing: #{entry[:incomplete].map { |host| by_host.dig(host, 'device', 'name') || host }.join(', ')}" }
26
+ partial.each { |entry| lines << " VNI #{entry[:vni]} missing: #{entry[:incomplete].map { |host| by_host.dig(host, 'target', 'name') || host }.join(', ')}" }
27
27
  end
28
28
  end
29
29
  lines << ""
@@ -39,14 +39,14 @@ module Vxlan
39
39
  common = defined.reduce { |all, members| all & members } || []
40
40
  lines << " Members common to defined versions (not an approved baseline): #{common.empty? ? 'none' : common.join(', ')}"
41
41
  evidence.group_by { |row| row[:value] }.each do |members, rows|
42
- names = rows.map { |row| by_host.dig(row[:host], "device", "name") || row[:host] }
42
+ names = rows.map { |row| by_host.dig(row[:host], "target", "name") || row[:host] }
43
43
  value = members ? "#{members.size} members; outside the common set: #{(members - common).empty? ? 'none' : (members - common).join(', ')}" : "No definition provided or object evidence not collected"
44
44
  lines.concat([ " #{names.join(', ')}", " #{value}" ])
45
45
  end
46
46
  next
47
47
  end
48
48
  unless evidence.is_a?(Array) && evidence.all? { |row| row.is_a?(Hash) }
49
- lines << JSON.pretty_generate(evidence)
49
+ lines << JSON.pretty_generate(evidence, max_nesting: 128)
50
50
  next
51
51
  end
52
52
  grouped = evidence.group_by do |row|
@@ -59,12 +59,12 @@ module Vxlan
59
59
  [ row[:vlan] || row[:interface] || "shared", display_fabric_value(value) ]
60
60
  end
61
61
  grouped.each do |(vlan, value), members|
62
- names = members.map { |row| row[:name] || by_host.dig(row[:host], "device", "name") || row[:host] }
62
+ names = members.map { |row| row[:name] || by_host.dig(row[:host], "target", "name") || row[:host] }
63
63
  lines.concat([ " VLAN/interface #{vlan}: #{value}", " #{names.join(', ')}" ])
64
64
  end
65
65
  if evidence.any? { |row| row[:semantics] }
66
66
  evidence.group_by { |row| row[:semantics] }.each_with_index do |(rules, members), variant|
67
- lines << " Rule version #{variant + 1}: #{members.map { |row| by_host.dig(row[:host], 'device', 'name') || row[:host] }.join(', ')}"
67
+ lines << " Rule version #{variant + 1}: #{members.map { |row| by_host.dig(row[:host], 'target', 'name') || row[:host] }.join(', ')}"
68
68
  lines.concat(rules.map { |rule| " #{rule['action']} #{rule['expression']}" })
69
69
  end
70
70
  end
@@ -94,7 +94,7 @@ module Vxlan
94
94
  def review_collected_fabric(policy)
95
95
  sources = Dir[File.join(directory, "evidence", "*.json")].sort.map do |path|
96
96
  body = CtxCli::Input.read(path: path)
97
- [ File.expand_path(path), body, JSON.parse(body) ]
97
+ [ File.expand_path(path), body, JSON.parse(body, max_nesting: 128) ]
98
98
  end
99
99
  build_review(sources, policy: policy, standalone: false) unless sources.empty?
100
100
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "ctx_runner/evidence"
3
4
  require "digest"
4
5
  require "ctx_runner/fingerprint"
5
6
  require_relative "../../recommendations"
@@ -17,10 +18,10 @@ module Vxlan
17
18
  @fabric_text = @fabric_audit && fabric_text(@fabric_audit, documents)
18
19
  entries = sources.map do |path, body, document, initial|
19
20
  advice = initial || Recommendations.new(document).call
20
- additions = @fabric_audit && @fabric_audit[:device_items][document["device"]["host"]]
21
+ additions = @fabric_audit && @fabric_audit[:device_items][document["target"]["host"]]
21
22
  advice = Recommendations.combine(advice, additions)
22
- device = document.fetch("device")
23
- basename = CLI::Report.device_basename(device)
23
+ device = document.fetch("target")
24
+ basename = CLI::Report.target_basename(device)
24
25
  write_review(document, basename: basename, source: path, source_sha256: Digest::SHA256.hexdigest(body), advice: advice)
25
26
  end
26
27
  finish_review(entries, source_batch: File.dirname(File.dirname(sources.first[0])), standalone: standalone)
@@ -31,7 +32,7 @@ module Vxlan
31
32
  raise ArgumentError, "Invalid report name" unless basename.match?(/\A[A-Za-z0-9_.-]+\z/)
32
33
  advice = report_advice(advice || Recommendations.new(document).call).merge(source: source, source_sha256: source_sha256)
33
34
  advice[:items] = advice[:items].map(&:dup)
34
- entry = { device: advice[:device], counts: advice[:counts], basename: basename, report: "devices/#{basename}.txt", source: source,
35
+ entry = { target: advice[:target], counts: advice[:counts], basename: basename, report: "devices/#{basename}.txt", source: source,
35
36
  source_sha256: source_sha256, script: nil, script_sha256: nil, plans: [], changes: {}, advice: advice }
36
37
  config = Config::Evidence.complete_record(document)
37
38
  config_sha256 = nil
@@ -42,7 +43,7 @@ module Vxlan
42
43
  change = plan.to_h
43
44
  id = [ basename, change["kind"], "vlan#{change['vlan']}", change["direction"], CtxRunner::Fingerprint.call(change)[0, 12] ].compact.join("--")
44
45
  config_sha256 ||= CtxRunner::Fingerprint.call(config)
45
- entry[:changes][id] = { schema_version: 1, platform: "cisco_nxos", device: document.fetch("device"), expected_config_sha256: config_sha256,
46
+ entry[:changes][id] = { schema_version: CtxRunner::Evidence::VERSION, kind: "change", platform: "cisco_nxos", target: document.fetch("target"), expected_config_sha256: config_sha256,
46
47
  source: source, source_sha256: source_sha256, change: change, commands: plan.commands, rollback: plan.rollback,
47
48
  scope: item[:scope], title: item[:title], prerequisites: item[:prerequisites], impact: item[:impact], verify: item[:verify] }
48
49
  item[:plan_id] = id
@@ -65,16 +66,16 @@ module Vxlan
65
66
  def finish_review(entries, source_batch:, standalone: true)
66
67
  counts = entries.each_with_object(Hash.new(0)) { |entry, total| entry[:counts].each { |key, count| total[key] += count } }
67
68
  public_entries = entries.map { |entry| entry.reject { |key, _| %i[advice changes].include?(key) } }
68
- summary = { layout_version: 3, mode: "review", status: "incomplete", review_only: true, devices: entries.size, counts: counts, source_batch: source_batch,
69
+ summary = { schema_version: CtxRunner::Evidence::VERSION, kind: "review", layout_version: 3, mode: "review", status: "incomplete", review_only: true, devices: entries.size, counts: counts, source_batch: source_batch,
69
70
  reports: public_entries, plan: "plan.json", plan_sha256: nil, fabric_findings: @fabric_audit ? @fabric_audit[:findings].size : 0 }
70
71
  checkpoint("summary.json", summary) if standalone
71
- plan = { schema_version: 2, platform: "cisco_nxos", mode: "review", devices: public_entries, audits: entries.map { |entry| entry[:advice] },
72
+ plan = { schema_version: CtxRunner::Evidence::VERSION, kind: "change_plan", platform: "cisco_nxos", mode: "review", devices: public_entries, audits: entries.map { |entry| entry[:advice] },
72
73
  changes: entries.each_with_object({}) { |entry, all| all.merge!(entry[:changes]) }, fabric: @fabric_audit && @fabric_audit.reject { |key, _| key == :device_items } }
73
- body = JSON.pretty_generate(plan) + "\n"
74
+ body = JSON.pretty_generate(plan, max_nesting: 128) + "\n"
74
75
  summary[:plan_sha256] = Digest::SHA256.hexdigest(body)
75
76
  publish("plan.json", body)
76
77
  publish("plan.json.sha256", summary[:plan_sha256] + "\n")
77
- events = public_entries.map { |entry| JSON.generate(event: "device_reviewed", reviewed_at: Time.now.utc.iso8601(6), host: entry[:device]["host"], source_sha256: entry[:source_sha256], counts: entry[:counts], report: entry[:report], script: entry[:script], executed: false) }
78
+ events = public_entries.map { |entry| JSON.generate(event: "device_reviewed", reviewed_at: Time.now.utc.iso8601(6), host: entry[:target]["host"], source_sha256: entry[:source_sha256], counts: entry[:counts], report: entry[:report], script: entry[:script], executed: false) }
78
79
  publish("events.jsonl", events.join("\n") + (events.empty? ? "" : "\n"))
79
80
  text = summary_text(summary)
80
81
  if standalone
@@ -109,17 +110,17 @@ module Vxlan
109
110
 
110
111
  # 文本按设备、证据、问题、动作顺序组织,完整跨设备证据位于聚合计划。
111
112
  def device_text(entry, document)
112
- advice, device = entry.values_at(:advice, :device)
113
+ advice, device = entry.values_at(:advice, :target)
113
114
  lines = [ "Device: #{device['name']} (#{device['host']})", "Mode: diagnostics and planning; no device configuration executed", "Evidence time: #{advice[:observed_at] || 'unknown'}", "Source: #{entry[:source]}", "Source file SHA256: #{entry[:source_sha256]}",
114
115
  "Recommendations: #{entry[:counts]}", "Command file: #{entry[:script] || 'not generated'}", "Command SHA256: #{entry[:script_sha256] || 'none'}", "Plan file: plan.json; interactive plan items: #{entry[:plans].size} items", "" ]
115
116
  lines << "Collection status: #{document['status']}" if document["status"]
116
- configuration_time = document.dig("snapshot", "dimensions", "configuration", "evidence", 0, "observed_at")
117
+ configuration_time = document.dig("snapshot", "observations", "configuration", "evidence", 0, "observed_at")
117
118
  lines << "Configuration evidence time: #{configuration_time}" if configuration_time
118
119
  lines << "No current rules matched; this does not establish network health." if advice[:items].empty?
119
120
  advice[:items].each_with_index do |item, index|
120
121
  lines.concat([ "", "#{index + 1}. #{item[:scope]} — #{item[:title]}", "Status: #{item[:status]}; rule: #{item[:code]}", "Impact: #{item[:impact]}" ])
121
122
  evidence = item[:category] == "fabric" ? Array(item[:evidence]).select { |row| row[:host] == device["host"] } : item[:evidence]
122
- lines.concat([ "Local evidence: ", JSON.pretty_generate(evidence) ])
123
+ lines.concat([ "Local evidence: ", JSON.pretty_generate(evidence, max_nesting: 128) ])
123
124
  lines << "Cross-device comparison: summary.txt; full raw comparison: audits / fabric in plan.json." if item[:category] == "fabric"
124
125
  if item[:plan_id]
125
126
  lines << "Interactive plan item: #{item[:plan_id]}"
@@ -145,8 +146,8 @@ module Vxlan
145
146
  "Read in order: summary.txt -> devices/<device>.txt -> scripts/<device>.cfg -> the selected plan item in plan.json.",
146
147
  "evidence/ stores collection evidence used by the program; routine review does not require opening it. devices/ contains readable diagnostics only.",
147
148
  "plan.json.sha256 verifies the aggregate plan; events.jsonl records this offline review, not device sessions or execution receipts.", "Applying requires selecting one --item, interactive confirmation, configuration readback and fingerprint verification; there is no automatic bulk execution.", "" ]
148
- entries.sort_by { |entry| [ entry[:counts].values.sum.positive? ? 0 : 1, entry[:device]["name"].to_s ] }.each do |entry|
149
- lines.concat([ "#{entry[:device]['host']} #{entry[:device]['name']} unresolved=#{entry[:counts].fetch('blocked', 0)} candidates=#{entry[:counts].fetch('candidate', 0)} investigations=#{entry[:counts].fetch('investigate', 0)}",
149
+ entries.sort_by { |entry| [ entry[:counts].values.sum.positive? ? 0 : 1, entry[:target]["name"].to_s ] }.each do |entry|
150
+ lines.concat([ "#{entry[:target]['host']} #{entry[:target]['name']} unresolved=#{entry[:counts].fetch('blocked', 0)} candidates=#{entry[:counts].fetch('candidate', 0)} investigations=#{entry[:counts].fetch('investigate', 0)}",
150
151
  " Device report: #{entry[:report]}", " Command file: #{entry[:script] || 'not generated'}; executable plans: #{entry[:plans].size} items" ])
151
152
  end
152
153
  lines.concat([ "", @fabric_text ]) if @fabric_text
@@ -34,8 +34,8 @@ module Vxlan
34
34
  validate(entry[2])
35
35
  entry << Recommendations.new(entry[2]).call
36
36
  end
37
- hosts = documents.map { |entry| entry[2]["device"]["host"] }
38
- names = documents.map { |entry| CLI::Report.device_basename(entry[2].fetch("device")) }
37
+ hosts = documents.map { |entry| entry[2]["target"]["host"] }
38
+ names = documents.map { |entry| CLI::Report.target_basename(entry[2].fetch("target")) }
39
39
  raise ArgumentError, "Duplicate device identity or output name" unless hosts.uniq == hosts && names.uniq == names
40
40
  policy = options[:fabric_policy] && YAML.safe_load(CtxCli::Input.read(path: options[:fabric_policy]), aliases: false)
41
41
  Vxlan::Fabric::Scope.new(policy) if policy
@@ -53,7 +53,7 @@ module Vxlan
53
53
 
54
54
  # 先校验公共证据外壳,再验证领域记录。
55
55
  def validate(document)
56
- CtxRunner::Evidence.validate(document) { |record, dimension| validate_record(record, dimension) }
56
+ CtxRunner::Evidence.validate(document, names: CiscoNxos::Profile::COMMANDS.keys) { |record, dimension| validate_record(record, dimension) }
57
57
  end
58
58
 
59
59
  # 在输出目录创建前验证所有会参与建议生成的嵌套字段。
@@ -21,6 +21,7 @@ module Vxlan
21
21
 
22
22
  # 通过调用方持有的连接器顺序采集请求维度。
23
23
  def collect(connector:, target:, fabric_key:, model: nil, dimensions: COMMANDS.keys)
24
+ target = CtxRunner::Target.coerce(target).to_h
24
25
  target, fabric_key, dimensions, profile = request(target, fabric_key, dimensions, connector.platform, model)
25
26
 
26
27
  observations = {}
@@ -29,9 +30,8 @@ module Vxlan
29
30
  if collection.failure
30
31
  code = collection.failure.fetch(:code)
31
32
  dimensions.each { |name| observations[name] ||= failure(name, code) }
32
- observations[:collection] = failure(:collection, code)
33
33
  end
34
- snapshot(target, fabric_key, observations)
34
+ snapshot(target, fabric_key, observations, issues: collection.failure ? [ collection.failure ] : [])
35
35
  end
36
36
 
37
37
  # 借用已打开的会话;调用方负责连接和关闭,本方法不重连、不提权。
@@ -44,11 +44,18 @@ module Vxlan
44
44
 
45
45
  # 连接前固定请求数据,生命周期入口和借用会话入口共用相同校验。
46
46
  def request(target, fabric_key, dimensions, platform, model)
47
- raise ArgumentError, "Target must be a hash" unless target.is_a?(Hash)
47
+ target = CtxRunner::Target.coerce(target).to_h
48
+ unless fabric_key.is_a?(String) && !fabric_key.strip.empty? && !/[\x00-\x1f\x7f]/.match?(fabric_key)
49
+ raise ArgumentError, "Fabric identity must be nonempty text"
50
+ end
48
51
  unless dimensions.is_a?(Array) && dimensions.any? && dimensions.uniq == dimensions && (dimensions - COMMANDS.keys).empty?
49
52
  raise ArgumentError, "Unknown or duplicate VXLAN dimensions"
50
53
  end
51
- raise ArgumentError, "VXLAN requires Cisco NX-OS" unless platform.to_s == "cisco_nxos"
54
+ platform = ParserRegistry.canonical(platform).to_s
55
+ if target[:platform] && ParserRegistry.canonical(target[:platform]).to_s != platform
56
+ raise ArgumentError, "Target platform differs from the connector"
57
+ end
58
+ target = target.merge(platform: platform)
52
59
 
53
60
  [ CtxParser::Immutable.copy(target), CtxParser::Immutable.copy(fabric_key), dimensions.dup.freeze,
54
61
  ParserRegistry.fetch(platform, model: model) ]
@@ -60,7 +67,6 @@ module Vxlan
60
67
  reader = CtxDriver::Reader.new(session: session, clock: @clock)
61
68
  if (code = prepare_terminal(reader))
62
69
  dimensions.each { |name| observations[name] = failure(name, code) }
63
- observations[:collection] = failure(:collection, code)
64
70
  return observations
65
71
  end
66
72
  ordered = dimensions.include?(:configuration) ? [ :configuration, *dimensions.reject { |name| name == :configuration } ] : dimensions
@@ -76,16 +82,8 @@ module Vxlan
76
82
  end
77
83
 
78
84
  # 汇总证据完整性,不将查询成功解释为 Fabric 健康。
79
- def snapshot(target, fabric_key, observations)
80
- status = if observations.values.all?(&:complete?)
81
- :complete
82
- elsif observations.values.any? { |value| %i[complete partial].include?(value.status) }
83
- :partial
84
- else
85
- :failed
86
- end
87
- observations[:collection] ||= Observation.new(name: :collection, status: status, completed_at: @clock.call)
88
- Snapshot.new(target: target, fabric_key: fabric_key, observations: observations, observed_at: @clock.call)
85
+ def snapshot(target, fabric_key, observations, issues: [])
86
+ Snapshot.new(target: target, fabric_key: fabric_key, observations: observations, observed_at: @clock.call, issues: issues)
89
87
  end
90
88
 
91
89
  # 采集设备回显前,禁用分页并归一化终端宽度。
@@ -6,7 +6,7 @@ module Vxlan
6
6
  module Evidence
7
7
  # 外层采集成功不能覆盖记录层的部分解析或多份配置歧义。
8
8
  def self.complete_record(document)
9
- observation = document&.dig("snapshot", "dimensions", "configuration")
9
+ observation = document&.dig("snapshot", "observations", "configuration")
10
10
  return unless observation && observation["status"] == "complete"
11
11
  records = observation["records"]
12
12
  return unless records.is_a?(Array) && records.one?
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "ctx_runner/evidence"
3
4
  require "ipaddr"
4
5
  require "json"
5
6
  require "digest"
@@ -17,7 +18,7 @@ module Vxlan
17
18
  class Review
18
19
  # 比较范围由业务策略统一验证,审查器只负责组织规则与建议。
19
20
  def initialize(documents, policy)
20
- @documents = documents.to_h { |document| [ document.fetch("device").fetch("host"), document ] }
21
+ @documents = documents.to_h { |document| [ document.fetch("target").fetch("host"), document ] }
21
22
  raise ArgumentError, "Duplicate device identity" unless @documents.size == documents.size
22
23
  @scope = Scope.new(policy)
23
24
  end
@@ -43,7 +44,7 @@ module Vxlan
43
44
  @role = nil
44
45
  review_subnets(fabric, configs)
45
46
  end
46
- { schema_version: 2, scope: "same_role_same_deployed_vni", inventory: inventory, findings: @findings, device_items: @items.to_h, coverage: @coverage }
47
+ { schema_version: CtxRunner::Evidence::VERSION, kind: "fabric_review", scope: "same_role_same_deployed_vni", inventory: inventory, findings: @findings, device_items: @items.to_h, coverage: @coverage }
47
48
  end
48
49
 
49
50
  private
@@ -176,7 +177,7 @@ module Vxlan
176
177
  index = (@subnet_indexes[host] ||= SubnetIndex.new(config))
177
178
  excluded = except&.first == host ? except.last : nil
178
179
  index.conflicts(address: change["address"], vrf: change["vrf"], vni: change["vni"], except_interface: excluded).map do |entry|
179
- { host: host, name: @documents[host]["device"]["name"], **entry }
180
+ { host: host, name: @documents[host]["target"]["name"], **entry }
180
181
  end
181
182
  end
182
183
  end
@@ -298,7 +299,7 @@ module Vxlan
298
299
 
299
300
  # 观察附带设备名、地址及本地 VLAN,报告可直接定位配置入口。
300
301
  def observations(rows)
301
- rows.map { |row| { host: row[:host], name: @documents[row[:host]]["device"]["name"], vlan: row[:vlan], value: yield(row) } }
302
+ rows.map { |row| { host: row[:host], name: @documents[row[:host]]["target"]["name"], vlan: row[:vlan], value: yield(row) } }
302
303
  end
303
304
 
304
305
  # 按业务问题计数,不把证据行数当作问题数量。
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "ctx_runner/evidence"
3
4
  require_relative "cisco_nxos/profile"
4
5
  require_relative "config/evidence"
5
6
 
@@ -35,7 +36,7 @@ module Vxlan
35
36
  # 输入为报告 JSON 的字符串键结构,离线与实时报告共用此边界。
36
37
  def initialize(document)
37
38
  @document = document
38
- @dimensions = document.dig("snapshot", "dimensions") || {}
39
+ @dimensions = document.dig("snapshot", "observations") || {}
39
40
  end
40
41
 
41
42
  # 建议与采集完整性分开;没有命中规则并不代表网络健康。
@@ -47,7 +48,7 @@ module Vxlan
47
48
  items.concat(undefined_acl_items(config))
48
49
  end
49
50
  items.concat(runtime_tasks)
50
- { schema_version: 1, review_only: true, health_assessment: "not_performed", device: @document["device"],
51
+ { schema_version: CtxRunner::Evidence::VERSION, kind: "recommendations", review_only: true, health_assessment: "not_performed", target: @document["target"],
51
52
  observed_at: @document.dig("snapshot", "observed_at"), items: items, counts: items.map { |item| item[:status] }.tally }
52
53
  end
53
54
 
@@ -1,44 +1,32 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "ctx_parser/immutable"
3
+ require "forwardable"
4
+ require "ctx_runner/snapshot"
4
5
  require_relative "observation"
5
6
  require_relative "parser_registry"
6
7
 
7
8
  module Vxlan
8
- # 携带单设备 Fabric 身份及观测结果,不管理资产清单。
9
- Snapshot = Data.define(:target, :fabric_key, :observations, :observed_at) do
10
- # 事实由不可变领域观测持有;仅复制维度选择,不重复复制事实。
11
- def initialize(target:, fabric_key:, observations:, observed_at:)
12
- unless observations.is_a?(Hash) && observations.all? { |name, value| value.is_a?(Observation) && value.name == name }
13
- raise ArgumentError, "Dimensions must match their observations"
9
+ # 领域组合公共快照,身份、维度、时间及采集结论共用同一契约。
10
+ class Snapshot
11
+ include CtxRunner::Document::Value
12
+ extend Forwardable
13
+ def_delegators :@snapshot, :target, :observations, :observed_at, :issues, :collection_status,
14
+ :observation, :records, :complete?, :same_target?
15
+ attr_reader :fabric_key
16
+
17
+ def initialize(target:, fabric_key:, observations:, observed_at:, issues: [])
18
+ unless fabric_key.is_a?(String) && !fabric_key.strip.empty? && !/[\x00-\x1f\x7f]/.match?(fabric_key)
19
+ raise ArgumentError, "Fabric identity must be nonempty text"
14
20
  end
15
-
16
- super(target: CtxParser::Immutable.copy(target), fabric_key: CtxParser::Immutable.copy(fabric_key),
17
- observations: observations.to_h { |name, value| [ name, value ] }.freeze, observed_at: observed_at&.dup&.freeze)
18
- end
19
-
20
- # 未请求的已知维度保留明确状态;未知维度属于调用错误。
21
- def observation(name)
22
- unless name == :collection || CiscoNxos::Profile::COMMANDS.key?(name)
23
- raise ArgumentError, "Unknown VXLAN dimension"
24
- end
25
- observations.fetch(name) { Observation.new(name: name, status: :not_requested) }
21
+ @fabric_key = fabric_key.dup.freeze
22
+ @snapshot = CtxRunner::Snapshot.new(target: target, observations: observations, observed_at: observed_at,
23
+ names: CiscoNxos::Profile::COMMANDS.keys, issues: issues)
24
+ freeze
26
25
  end
27
26
 
28
- # 报告格式独立于 Ruby 成员命名,已有离线证据继续使用 dimensions。
29
- def to_h = super.except(:observations).merge(dimensions: observations)
30
-
31
- # 判断所有已选事实是否都有完整证据支持。
32
- def complete?
33
- selected = observations.values.reject { |dimension| dimension.status == :not_requested }
34
- selected.any? && selected.all?(&:complete?)
35
- end
36
-
37
- # 展示对象身份与状态,避免泄露原始回显或凭据。
38
- def inspect = "#<#{self.class.name} fabric=#{fabric_key.inspect} complete=#{complete?}>"
27
+ def to_h = @snapshot.to_h.merge(fabric_key: fabric_key)
28
+ def inspect = "#<#{self.class.name} collection_status=#{collection_status}>"
39
29
  alias to_s inspect
40
-
41
- # PP 默认展开 Data 成员,显式沿用脱敏展示。
42
30
  def pretty_print(printer) = printer.text(inspect)
43
31
  end
44
32
  end
data/lib/vxlan/version.rb CHANGED
@@ -2,5 +2,5 @@
2
2
 
3
3
  module Vxlan
4
4
  # 公开包版本,供 RubyGems 元数据和运行时调用方共用。
5
- VERSION = "0.6.0"
5
+ VERSION = "0.8.0"
6
6
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: vxlan
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.0
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Gatework contributors
@@ -10,7 +10,7 @@ cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
- name: ctx_cli
13
+ name: forwardable
14
14
  requirement: !ruby/object:Gem::Requirement
15
15
  requirements:
16
16
  - - ">="
@@ -23,66 +23,86 @@ dependencies:
23
23
  - - ">="
24
24
  - !ruby/object:Gem::Version
25
25
  version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: ctx_cli
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 0.5.0
33
+ - - "<"
34
+ - !ruby/object:Gem::Version
35
+ version: '0.6'
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: 0.5.0
43
+ - - "<"
44
+ - !ruby/object:Gem::Version
45
+ version: '0.6'
26
46
  - !ruby/object:Gem::Dependency
27
47
  name: ctx_runner
28
48
  requirement: !ruby/object:Gem::Requirement
29
49
  requirements:
30
50
  - - ">="
31
51
  - !ruby/object:Gem::Version
32
- version: 0.3.0
52
+ version: 0.5.0
33
53
  - - "<"
34
54
  - !ruby/object:Gem::Version
35
- version: '0.4'
55
+ version: '0.6'
36
56
  type: :runtime
37
57
  prerelease: false
38
58
  version_requirements: !ruby/object:Gem::Requirement
39
59
  requirements:
40
60
  - - ">="
41
61
  - !ruby/object:Gem::Version
42
- version: 0.3.0
62
+ version: 0.5.0
43
63
  - - "<"
44
64
  - !ruby/object:Gem::Version
45
- version: '0.4'
65
+ version: '0.6'
46
66
  - !ruby/object:Gem::Dependency
47
67
  name: ctx_parser
48
68
  requirement: !ruby/object:Gem::Requirement
49
69
  requirements:
50
70
  - - ">="
51
71
  - !ruby/object:Gem::Version
52
- version: 0.3.0
72
+ version: 0.4.0
53
73
  - - "<"
54
74
  - !ruby/object:Gem::Version
55
- version: '0.4'
75
+ version: '0.5'
56
76
  type: :runtime
57
77
  prerelease: false
58
78
  version_requirements: !ruby/object:Gem::Requirement
59
79
  requirements:
60
80
  - - ">="
61
81
  - !ruby/object:Gem::Version
62
- version: 0.3.0
82
+ version: 0.4.0
63
83
  - - "<"
64
84
  - !ruby/object:Gem::Version
65
- version: '0.4'
85
+ version: '0.5'
66
86
  - !ruby/object:Gem::Dependency
67
87
  name: ctx_driver
68
88
  requirement: !ruby/object:Gem::Requirement
69
89
  requirements:
70
90
  - - ">="
71
91
  - !ruby/object:Gem::Version
72
- version: 0.3.0
92
+ version: 0.5.0
73
93
  - - "<"
74
94
  - !ruby/object:Gem::Version
75
- version: '0.4'
95
+ version: '0.6'
76
96
  type: :runtime
77
97
  prerelease: false
78
98
  version_requirements: !ruby/object:Gem::Requirement
79
99
  requirements:
80
100
  - - ">="
81
101
  - !ruby/object:Gem::Version
82
- version: 0.3.0
102
+ version: 0.5.0
83
103
  - - "<"
84
104
  - !ruby/object:Gem::Version
85
- version: '0.4'
105
+ version: '0.6'
86
106
  - !ruby/object:Gem::Dependency
87
107
  name: digest
88
108
  requirement: !ruby/object:Gem::Requirement