提交脚本的设计注意事项
在对使用 XML 查看 Junos OS 配置数据有一定经验之后,创建提交脚本相当简单。本节提供使用 XSLT 开发提交脚本的一些建议和常见模式。
XSLT 是一种解释性语言,因此性能是一个重要考虑因素。为了获得最佳性能,最大限度地减少在每个节点上执行的节点遍历和测试。如果可能,对 select
递归 <xsl:apply-templates>
调用使用属性,以限制要访问的文档层次结构的部分。
例如,以下 select
属性通过指定启用了 (IPv4) 协议家族的 SONET/SDH 接口来限制要评估的 inet
节点:
<xsl:apply-templates select="interfaces/interface[starts-with(name, 'so-') and unit/family/inet]"/>
以下示例包含两 <xsl:apply-templates>
个指令,用于将脚本的范围限制为 import
在 [edit protocols ospf]
层级和 [edit protocols isis]
层级配置的语句:
<xsl:template match="configuration"> <xsl:apply-templates select="protocols/ospf/import"/> <xsl:apply-templates select="protocols/isis/import"/> <!-- ... body of template ... --> </xsl:template>
使用解释性语言,做任何不止一次的事情都会影响性能。如果脚本需要重复引用一个或多个节点集,请创建一个容纳该节点集的变量,然后对该变量进行多次引用。例如,以下变量声明会创建一个名为 mpls
的变量,该变量解析为 [edit protocols mpls]
层次结构级别。这使脚本只需遍历搜索 /protocols/
该节点的 mpls/
层次结构一次。
<xsl:variable name="mpls" select="/protocols/mpls"/> <xsl:choose> <xsl:when test="$mpls/path-mtu/allow-fragmentation"> <!-- ... --> </xsl:when> <xsl:when test="$mpls/hop-limit > 40"> <!-- ... --> </xsl:when> </xsl:choose>
使用 <xsl:for-each>
指令时,变量也很重要,因为当前的 上下文节点 会检查指令 <xsl:for-each>
选择的每个节点。例如,以下脚本使用多个变量来存储和引用值,因为 <xsl:for-each>
指令会评估在所有通道化 STM1 (cstm1-) 接口上配置的 E1 接口:
<xsl:param name="limit" select="16"/> <xsl:template match="configuration"> <xsl:variable name="interfaces" select="interfaces"/> <xsl:for-each select="$interfaces/interface[starts-with(name, 'cstm1-')]"> <xsl:variable name="triple" select="substring-after(name, 'cstm1-')"/> <xsl:variable name="e1name" select="concat('e1-', $triple)"/> <xsl:variable name="count" select="count($interfaces/interface[starts-with(name, $e1name)])"/> <xsl:if test="$count > $limit"> <xnm:error> <edit-path>[edit interfaces]</edit-path> <statement><xsl:value-of select="name"/></statement> <message> <xsl:text>E1 interface limit exceeded on CSTM1 IQ PIC. </xsl:text> <xsl:value-of select="$count"/> <xsl:text> E1 interfaces are configured, but only </xsl:text> <xsl:value-of select="$limit"/> <xsl:text> are allowed.</xsl:text> </message> </xnm:error> </xsl:if> </xsl:for-each> </xsl:template>
如果将一个 cstm1-0/1/0 接口通道化为 17 个 E1 接口,则脚本将导致在发出 commit
命令时出现以下错误消息。(有关此示例的详细信息,请参阅 示例:限制 E1 接口的数量。)
[edit] user@host# commit [edit interfaces] 'cstm1-0/1/0' E1 interface limit exceeded on CSTM1 IQ PIC. 17 E1 interfaces are configured, but only 16 are allowed. error: 1 error reported by commit scripts error: commit script failure