yang模型和pyang的基本使用

本文最后更新于:2023年4月15日 晚上

yang模型简介

yang 1.1在RFC7950中被提出: https://tools.ietf.org/html/rfc7950

翻译资料: https://tonydeng.github.io/rfc7950-zh/

YANG是一种数据建模语言(data modeling language),用于对配置数据(model configuration data),状态数据(state data),远程过程调用(Remote Procedure Calls)和网络管理协议通知(notifications for network management protocols)进行建模。

数据节点类型

下面给出四种节点类型和对应的yang例子

  • leaf nodes

    1
    2
    3
    4
    5
    leaf host-name {
    type string;
    description
    "Hostname for this system.";
    }
  • leaf-list nodes

    1
    2
    3
    4
    5
    leaf-list domain-search {
    type string;
    description
    "List of domain names to search.";
    }
  • container nodes

    1
    2
    3
    4
    5
    6
    7
    8
    9
    container system {
    container login {
    leaf message {
    type string;
    description
    "Message given at start of login session.";
    }
    }
    }
  • list nodes

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    list user {
    key "name";
    leaf name {
    type string;
    }
    leaf full-name {
    type string;
    }
    leaf class {
    type string;
    }
    }

状态属性和配置属性

YANG可以根据“config”语句为状态数据和配置数据建模。 当一个节点被标记为“config false”时,其子层被标记为状态数据。 如果标记为“config true”,则其子层被标记为配置数据。

配置数据可以理解为read and write属性, 而状态数据即read only属性

内置类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
+---------------------+-------------------------------------+
| Name | Description |
+---------------------+-------------------------------------+
| binary | Any binary data |
| bits | A set of bits or flags |
| boolean | "true" or "false" |
| decimal64 | 64-bit signed decimal number |
| empty | A leaf that does not have any value |
| enumeration | One of an enumerated set of strings |
| identityref | A reference to an abstract identity |
| instance-identifier | A reference to a data tree node |
| int8 | 8-bit signed integer |
| int16 | 16-bit signed integer |
| int32 | 32-bit signed integer |
| int64 | 64-bit signed integer |
| leafref | A reference to a leaf instance |
| string | A character string |
| uint8 | 8-bit unsigned integer |
| uint16 | 16-bit unsigned integer |
| uint32 | 32-bit unsigned integer |
| uint64 | 64-bit unsigned integer |
| union | Choice of member types |
+---------------------+-------------------------------------+

重复使用: grouping和uses

可以使用“grouping”语句将节点组组合成可重复使用的集合。 分组定义了一组使用“uses”语句实例化的节点。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 定义一个grouping分组
grouping target {
leaf address {
type inet:ip-address;
description "Target IP address.";
}
leaf port {
type inet:port-number;
description "Target port number.";
}
}
container peer {
container destination {
uses target; // 使用grouping
}
}

扩展: argument和when

augment语句定义插入新节点的数据模型层次结构中的位置,when语句定义新节点有效时的条件。

1
2
3
4
5
6
7
8
augment /system/login/user {
when "class != 'wheel'";
leaf uid {
type uint16 {
range "1000 .. 30000";
}
}
}

操作: rpc和action

模块顶层的操作用“rpc”语句定义。 操作也可以绑定到容器或列表数据节点。 这些操作用“action”语句来定义。

通过rpc定义一个远程操作, 输入输出参数通过inputoutput确定

rpc操作:

1
2
3
4
5
6
7
8
9
10
11
12
rpc activate-software-image {
input {
leaf image-name {
type string;
}
}
output {
leaf status {
type string;
}
}
}

action操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
list interface {
key "name";

leaf name {
type string;
}

action ping {
input {
leaf destination {
type inet:ip-address;
}
}
output {
leaf packet-loss {
type uint8;
}
}
}
}

通知: notification

YANG允许定义通知。 YANG数据定义语句用于模拟通知的内容。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
notification link-failure {
description
"A link failure has been detected.";
leaf if-name {
type leafref {
path "/interface/name";
}
}
leaf if-admin-status {
type admin-status;
}
leaf if-oper-status {
type oper-status;
}
}

pyang

项目地址: https://github.com/mbj4668/pyang

简介:

pyang is a YANG validator, transformator and code generator, written in python. It can be used to validate YANG modules for correctness, to transform YANG modules into other formats, and to write plugins to generate code from the modules.

pyang可以理解为一个用python写的yang模型的解析器, 下面记录一些简单的使用方式

安装(for windows)

linux直接按照readme输入pip install然后export就好了

首先初始化一个虚拟环境

1
virtualenv yang

然后进入到Script目录下

执行activate.bat

就成功激活了虚拟环境

然后直接pip install pyang

最后直接在虚拟环境中的/Script目录下使用就好了, 无需配置环境变量之类的

man

使用python .\pyang --help可以查看使用方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
Validates the YANG module in <filename> (or stdin), and all its dependencies.

Options:
-h, --help Show this help message and exit
-v, --version Show version number and exit
-V, --verbose
-e, --list-errors Print a listing of all error and warning codes and
exit.
--print-error-code On errors, print the error code instead of the error
message.
--print-error-basename
On errors, print the basename of files of the error
message.
--msg-template=MSG_TEMPLATE
Template used to display error messages. This is a
python new-style format string used to format the
message information with keys file, line, code, type
and msg. Example: --msg-template='{file} || {line} ||
{code} || {type} || {level} || {msg}'
-W WARNING If WARNING is 'error', treat all warnings as errors,
except any listed WARNING. If WARNING is 'none', do
not report any warnings.
-E WARNING Treat each WARNING as an error. For a list of
warnings, use --list-errors.
--ignore-error=ERROR Ignore ERROR. Use with care. For a list of errors,
use --list-errors.
--ignore-errors Ignore all errors. Use with care.
--canonical Validate the module(s) according to the canonical YANG
order.
--verify-revision-history
Ensure that all old revisions in the revision history
can be found in the module search path.
--max-line-length=MAX_LINE_LEN
--max-identifier-length=MAX_IDENTIFIER_LEN
-t TRANSFORMS, --transform=TRANSFORMS
Apply transform TRANSFORM. Supported transforms are:
edit
-f FORMAT, --format=FORMAT
Convert to FORMAT. Supported formats are: yang, yin,
dsdl, capability, depend, flatten, identifiers,
jsonxsl, jstree, jtox, name, omni, sample-xml-
skeleton, tree, uml
-o OUTFILE, --output=OUTFILE
Write the output to OUTFILE instead of stdout.
-F FEATURES, --features=FEATURES
Features to support, default all.
<modname>:[<feature>,]*
-X EXCLUDE_FEATURES, --exclude-features=EXCLUDE_FEATURES
Features not to support, default none.
<modname>:[<feature>,]*
--max-status=MAXSTATUS
Max status to support, one of: current, deprecated,
obsolete
--deviation-module=DEVIATION
Deviation module
-p PATH, --path=PATH ;-separated search path for yin and yang modules
--plugindir=PLUGINDIR
Load pyang plugins from PLUGINDIR
--strict Force strict YANG compliance.
--lax-quote-checks Lax check of backslash in quoted strings.
--lax-xpath-checks Lax check of XPath expressions.
--trim-yin In YIN input modules, trim whitespace in textual
arguments.
-L, --hello Filename of a server's hello message is given instead
of module filename(s).
--implicit-hello-deviations
Attempt to parse all deviations from hello message
regardless of declaration.
--keep-comments Pyang will not discard comments;
has effect if the output plugin can
handle comments.
--no-path-recurse Do not recurse into directories in the
yang path.
--bbf Validate the module(s) according to BBF rules.
--check-update-from=OLDMODULE
Verify that upgrade from OLDMODULE follows RFC 6020
and 7950 rules.
-P OLD_PATH, --check-update-from-path=OLD_PATH
;-separated search path for yin and yang modules used
by OLDMODULE
-D OLD_DEVIATION, --check-update-from-deviation-module=OLD_DEVIATION
Old deviation module of the OLDMODULE. This option can
be given multiple times.
--check-update-include-structures
Check sx:structures.
--ieee Validate the module(s) according to IEEE rules.
--ietf Validate the module(s) according to IETF rules.
--ietf-help Print help on the IETF checks and exit
--lint Validate the module(s) according to RFC 8407rules.
--lint-namespace-prefix=LINT_NAMESPACE_PREFIXES
Validate that the module's namespace matches one of
the given prefixes.
--lint-modulename-prefix=LINT_MODULENAME_PREFIXES
Validate that the module's name matches one of the
given prefixes.
--lint-ensure-hyphenated-names
No upper case and underscore in names.
--mef Validate the module(s) according to MEF rules.
--3gpp Validate the module(s) according to 3GPP rules.

YANG output specific options:
--yang-canonical Print in canonical order
--yang-remove-unused-imports
--yang-remove-comments
--yang-line-length=YANG_LINE_LENGTH
Maximum line length

YIN output specific options:
--yin-canonical Print in canonical order
--yin-pretty-strings
Pretty print strings

Hybrid DSDL schema output specific options:
--dsdl-no-documentation
No output of DTD compatibility documentation
annotations
--dsdl-no-dublin-core
No output of Dublin Core metadata annotations
--dsdl-record-defs Record all top-level defs (even if not used)
--dsdl-lax-yang-version
Try to translate modules with unsupported YANG
versions (use at own risk)

Capability output specific options:
--capability-entity
Write ampersands as XML entity

Depend output specific options:
--depend-target=DEPEND_TARGET
Makefile rule target
--depend-no-submodules
Do not generate dependencies for included submodules
--depend-from-submodules
Generate dependencies from included submodules
--depend-recurse Generate dependencies to all imports, recursively
--depend-extension=DEPEND_EXTENSION
YANG module file name extension
--depend-include-path
Include file path in the prerequisites
--depend-ignore-module=DEPEND_IGNORE
(sub)module to ignore in the prerequisites. This
option can be given multiple times.

Flatten output specific options:
--flatten-no-header
Do not emit the CSV header.
--flatten-keyword Output the keyword.
--flatten-type Output the top-level type.
--flatten-primitive-type
Output the primitive type.
--flatten-flag Output flag property.
--flatten-description
Output the description.
--flatten-keys Output the key names if specified.
--flatten-keys-in-xpath
Output the XPath with keys in path.
--flatten-prefix-in-xpath
Output the XPath with prefixes instead of modules.
--flatten-qualified-in-xpath
Output the XPath with qualified in path
/module1:root/module1:node/module2:node/...
--flatten-qualified-module-and-prefix-path
Output an XPath with both module and prefix i.e.
/module1:prefix1:root/...
--flatten-deviated Output deviated nodes.
--flatten-data-keywords
Flatten all data keywords instead of onlydata
definition keywords.
--flatten-filter-keyword=FLATTEN_FILTER_KEYWORD
Filter output to only desired keywords.
--flatten-filter-primitive=FLATTEN_FILTER_PRIMITIVE
Filter output to only desired primitive types.
--flatten-filter-flag=FLATTEN_FILTER_FLAG
Filter output to flags.
--flatten-csv-dialect=FLATTEN_CSV_DIALECT
CSV dialect for output.
--flatten-ignore-no-primitive
Ignore error if primitive is missing.
--flatten-status Output the status statement value.
--flatten-resolve-leafref
Output the XPath of the leafref target.

JSTree output specific options:
--jstree-no-path Do not include paths to make
page less wide
--jstree-path=JSTREE_PATH
Subtree to print

Name output specific options:
--name-print-revision
Print the name and revision in name@revision format

OmniGraffle output specific options:
--omni-path=OMNI_TREE_PATH
Subtree to print

Sample-xml-skeleton output specific options:
--sample-xml-skeleton-doctype=DOCTYPE
Type of sample XML document (data or config).
--sample-xml-skeleton-defaults
Insert leafs with defaults values.
--sample-xml-skeleton-annotations
Add annotations as XML comments.
--sample-xml-skeleton-path=SAMPLE_PATH
Subtree to print

SID file specific options:
--sid-help Print help on automatic SID generation
--sid-generate-file=GENERATE_SID_FILE
Generate a .sid file.
--sid-update-file=UPDATE_SID_FILE
Generate a .sid file based on a previous .sid file.
--sid-check-file=CHECK_SID_FILE
Check the consistency between a .sid file and the
.yang file(s).
--sid-list Print the list of SID.
--sid-registration-info
Print the information required by the SID registry.
--sid-extra-range=EXTRA_SID_RANGE
Add an extra SID range during a .sid file update.

Tree output specific options:
--tree-help Print help on tree symbols and exit
--tree-depth=TREE_DEPTH
Number of levels to print
--tree-line-length=TREE_LINE_LENGTH
Maximum line length
--tree-path=TREE_PATH
Subtree to print
--tree-print-groupings
Print groupings
--tree-no-expand-uses
Do not expand uses of groupings
--tree-module-name-prefix
Prefix with module names instead of prefixes
--tree-print-yang-data
Print ietf-restconf:yang-data structures
--tree-print-structures
Print ietf-yang-structure-ext:structure

UML specific options:
--uml-classes-only Generate UML with classes only, no attributes
--uml-split-pages=UML_PAGES_LAYOUT
Generate UML output split into pages (separate .png
files), NxN, example 2x2
--uml-output-directory=UML_OUTPUTDIR
Put generated <modulename>.png or <title>.png file(s)
in OUTPUTDIR (default img/)
--uml-title=UML_TITLE
Set the title of the generated UML, including the
output file name
--uml-header=UML_HEADER
Set the page header of the generated UML
--uml-footer=UML_FOOTER
Set the page footer of the generated UML
--uml-long-identifiers
Use the full schema identifiers for UML class names.
--uml-inline-groupings
Inline groupings where they are used.
--uml-inline-augments
Inline augmentations where they are used.
--uml-description Include description of structural nodes in diagram.
--uml-no=UML_NO Suppress parts of the diagram. Valid suppress values
are: module, uses, leafref, identity, identityref,
typedef, import, annotation, circles, stereotypes.
Annotations suppresses YANG constructs represented as
annotations such as config statements for containers
and module info. Module suppresses module box around
the diagram and module information. Example --uml-
no=circles,stereotypes,typedef,import
--uml-truncate=UML_TRUNCATE
Leafref attributes and augment elements can have long
paths making the classes too wide. This option will
only show the tail of the path. Example --uml-
truncate=augment,leafref
--uml-max-enums=UML_MAX_ENUMS
The maximum number of enumerated values being rendered
--uml-filter Generate filter file, comment out lines with '-' and
use with option '--filter-file' to filter the UML
diagram
--uml-filter-file=UML_FILTER_FILE
NOT IMPLEMENTED: Only paths in the filter file will be
included in the diagram

Edit transform specific options:
--edit-yang-version=VERSION
Set YANG version to the supplied value
--edit-namespace=NAMESPACE
Set YANG namespace to the supplied value
--edit-update-import-dates
Set import/include revision-date statements to match
imported/included modules/submodules
--edit-delete-import-dates
Delete import/include revision-date statements
--edit-organization=ORGANIZATION
Set module/submodule organization to the supplied
value
--edit-contact=CONTACT
Set module/submodule contact to the supplied value
--edit-description=DESCRIPTION
Set module/submodule description to the supplied value
--edit-delete-revisions-after=PREVDATE
Delete any revisions after the supplied yyyy-mm-dd
--edit-revision-date=DATE
Set most recent revision date to the supplied yyyy-mm-
dd
--edit-revision-description=DESCRIPTION
Set most recent revision description to the supplied
value
--edit-revision-reference=REFERENCE
Set most recent revision reference to the supplied
value

使用: yang -> tree

tree文件是yang独有的一个文件,主要功能就是为yang生成一个快速化的浏览视图,功能在于直观的展示嵌套的yang结构

命令:

1
python .\pyang -p {yang模型文件集路径} -f tree {需要转换的yang文件}

即可在命令行打印完整的tree信息

可以通过

1
python .\pyang --tree-help

查看tree是如何表示数据的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Each node is printed as:

<status>--<flags> <name><opts> <type> <if-features>

<status> is one of:
+ for current
x for deprecated
o for obsolete

<flags> is one of:
rw for configuration data
ro for non-configuration data, output parameters to rpcs
and actions, and notification parameters
-w for input parameters to rpcs and actions
-u for uses of a grouping
-x for rpcs and actions
-n for notifications

<name> is the name of the node
(<name>) means that the node is a choice node
:(<name>) means that the node is a case node

If the node is augmented into the tree from another module, its
name is printed as <prefix>:<name>.

<opts> is one of:
? for an optional leaf, choice, anydata or anyxml
! for a presence container
* for a leaf-list or list
[<keys>] for a list's keys

<type> is the name of the type for leafs and leaf-lists, or
"<anydata>" or "<anyxml>" for anydata and anyxml, respectively

If the type is a leafref, the type is printed as "-> TARGET", where
TARGET is the leafref path, with prefixes removed if possible.

<if-features> is the list of features this node depends on, printed
within curly brackets and a question mark "{...}?"

jstree

更进一步地, 为了更方便观看, 可以直接导出为html(jstree格式)供查看:

1
python .\pyang -p {yang模型文件集路径} -f jstree {yang文件} -o {输出文件路径(.html)}

格式例子如下:


yang模型和pyang的基本使用
https://blog.roccoshi.top/posts/5574/
作者
RoccoShi
发布于
2022年5月20日
许可协议