3
3
import os
4
4
import re
5
5
import sys
6
+ import subprocess
7
+ import argparse
8
+ import shlex
6
9
7
10
PY3x = sys .version_info >= (3 , 0 )
8
11
PYvX_DIR = "py3" if PY3x else "py2"
9
12
PYTHON_INTERPRETTER = "python3" if PY3x else "python2"
13
+ YANG_MODELS_DIR = "/usr/local/yang-models"
10
14
11
15
def tuple_to_str (tuplestr ):
12
16
""" Convert Python tuple '('elem1', 'elem2')' representation into string on the for "elem1|elem2" """
@@ -33,6 +37,52 @@ def liststr_to_dict(liststr):
33
37
34
38
return list_obj
35
39
40
+ class YangWrapper (object ):
41
+ def __init__ (self , path = YANG_MODELS_DIR ):
42
+ """
43
+ sonic_yang only supports python3
44
+ """
45
+ if PY3x :
46
+ import sonic_yang
47
+ self .yang_parser = sonic_yang .SonicYang (path )
48
+ self .yang_parser .loadYangModel ()
49
+ self .test_dir = os .path .dirname (os .path .realpath (__file__ ))
50
+ self .script_file = PYTHON_INTERPRETTER + ' ' + os .path .join (self .test_dir , '..' , 'sonic-cfggen' )
51
+
52
+ def validate (self , argument ):
53
+ """
54
+ Raise exception when yang validation failed
55
+ """
56
+ if PY3x and "-m" in argument :
57
+ import sonic_yang
58
+ parser = argparse .ArgumentParser (description = "Render configuration file from minigraph data and jinja2 template." )
59
+ parser .add_argument ("-m" , "--minigraph" , help = "minigraph xml file" , nargs = '?' , const = '/etc/sonic/minigraph.xml' )
60
+ parser .add_argument ("-k" , "--hwsku" , help = "HwSKU" )
61
+ parser .add_argument ("-n" , "--namespace" , help = "namespace name" , nargs = '?' , const = None , default = None )
62
+ parser .add_argument ("-p" , "--port-config" , help = "port config file, used with -m or -k" , nargs = '?' , const = None )
63
+ parser .add_argument ("-S" , "--hwsku-config" , help = "hwsku config file, used with -p and -m or -k" , nargs = '?' , const = None )
64
+ args , unknown = parser .parse_known_args (shlex .split (argument ))
65
+
66
+ print ('\n Validating yang schema' )
67
+ cmd = self .script_file + ' -m ' + args .minigraph
68
+ if args .hwsku is not None :
69
+ cmd += ' -k ' + args .hwsku
70
+ if args .hwsku_config is not None :
71
+ cmd += ' -S ' + args .hwsku_config
72
+ if args .port_config is not None :
73
+ cmd += ' -p ' + args .port_config
74
+ if args .namespace is not None :
75
+ cmd += ' -n ' + args .namespace
76
+ cmd += ' --print-data'
77
+ output = subprocess .check_output (cmd , shell = True ).decode ()
78
+ try :
79
+ self .yang_parser .loadData (configdbJson = json .loads (output ))
80
+ self .yang_parser .validate_data_tree ()
81
+ except sonic_yang .SonicYangException as e :
82
+ print ("yang data generated from %s is not valid: %s" % (args .minigraph , str (e )))
83
+ return False
84
+ return True
85
+
36
86
def cmp (file1 , file2 ):
37
87
""" compare files """
38
88
try :
@@ -43,4 +93,3 @@ def cmp(file1, file2):
43
93
return obj1 == obj2
44
94
except :
45
95
return filecmp .cmp (file1 , file2 )
46
-
0 commit comments