open62541_XMLPreprocessor.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #!/usr/bin/env/python
  2. # -*- coding: utf-8 -*-
  3. ###
  4. ### Author: Chris Iatrou (ichrispa@core-vector.net)
  5. ###
  6. ### This program was created for educational purposes and has been
  7. ### contributed to the open62541 project by the author. All licensing
  8. ### terms for this source is inherited by the terms and conditions
  9. ### specified for by the open62541 project (see the projects readme
  10. ### file for more information on the LGPL terms and restrictions).
  11. ###
  12. ### This program is not meant to be used in a production environment. The
  13. ### author is not liable for any complications arising due to the use of
  14. ### this program.
  15. ###
  16. from logger import *
  17. from ua_constants import *
  18. import tempfile
  19. import xml.dom.minidom as dom
  20. import os
  21. import string
  22. from collections import Counter
  23. from ua_namespace import opcua_node_id_t
  24. class preProcessDocument:
  25. originXML = '' # Original XML passed to the preprocessor
  26. targetXML = () # tuple of (fileHandle, fileName)
  27. nodeset = '' # Parsed DOM XML object
  28. parseOK = False;
  29. containedNodes = [] # contains tuples of (opcua_node_id_t, xmlelement)
  30. referencedNodes = [] # contains tuples of (opcua_node_id_t, xmlelement)
  31. namespaceOrder = [] # contains xmlns:sX attributed as tuples (int ns, string name)
  32. namespaceQualifiers = [] # contains all xmlns:XYZ qualifiers that might prefix value aliases (like "<uax:Int32>")
  33. referencedNamesSpaceUris = [] # contains <NamespaceUris> URI elements
  34. def __init__(self, originXML):
  35. self.originXML = originXML
  36. self.targetXML = tempfile.mkstemp(prefix=os.path.basename(originXML)+"_preProcessed-" ,suffix=".xml")
  37. self.parseOK = True
  38. self.containedNodes = []
  39. self.referencedNodes = []
  40. self.namespaceOrder = []
  41. self.referencedNamesSpaceUris = []
  42. self.namespaceQualifiers = []
  43. try:
  44. self.nodeset = dom.parse(originXML)
  45. if len(self.nodeset.getElementsByTagName("UANodeSet")) == 0 or len(self.nodeset.getElementsByTagName("UANodeSet")) > 1:
  46. log(self, "Document " + self.targetXML[1] + " contains no or more then 1 nodeset", LOG_LEVEL_ERROR)
  47. self.parseOK = False
  48. except:
  49. self.parseOK = False
  50. log(self, "Adding new document to be preprocessed " + os.path.basename(originXML) + " as " + self.targetXML[1], LOG_LEVEL_DEBUG)
  51. def clean(self):
  52. #os.close(self.targetXML[0]) Don't -> done to flush() after finalize()
  53. os.remove(self.targetXML[1])
  54. def getTargetXMLName(self):
  55. if (self.parseOK):
  56. return self.targetXML[1]
  57. return None
  58. def extractNamespaceURIs(self):
  59. """ extractNamespaceURIs
  60. minidom gobbles up <NamespaceUris></NamespaceUris> elements, without a decent
  61. way to reliably access this dom2 <uri></uri> elements (only attribute xmlns= are
  62. accessible using minidom). We need them for dereferencing though... This
  63. function attempts to do just that.
  64. returns: Nothing
  65. """
  66. infile = open(self.originXML)
  67. foundURIs = False
  68. nsline = ""
  69. line = infile.readline()
  70. for line in infile:
  71. if "<namespaceuris>" in line.lower():
  72. foundURIs = True
  73. elif "</namespaceuris>" in line.lower():
  74. foundURIs = False
  75. nsline = nsline + line
  76. break
  77. if foundURIs:
  78. nsline = nsline + line
  79. if len(nsline) > 0:
  80. ns = dom.parseString(nsline).getElementsByTagName("NamespaceUris")
  81. for uri in ns[0].childNodes:
  82. if uri.nodeType != uri.ELEMENT_NODE:
  83. continue
  84. self.referencedNamesSpaceUris.append(uri.firstChild.data)
  85. infile.close()
  86. def analyze(self):
  87. """ analyze()
  88. analyze will gather information about the nodes and references contained in a XML File
  89. to facilitate later preprocessing stages that adresss XML dependency issues
  90. returns: No return value
  91. """
  92. nodeIds = []
  93. ns = self.nodeset.getElementsByTagName("UANodeSet")
  94. # We need to find out what the namespace calls itself and other referenced, as numeric id's are pretty
  95. # useless sans linked nodes. There is two information sources...
  96. self.extractNamespaceURIs() # From <URI>...</URI> definitions
  97. for key in ns[0].attributes.keys(): # from xmlns:sX attributes
  98. if "xmlns:" in key: # Any key: we will be removing these qualifiers from Values later
  99. self.namespaceQualifiers.append(key.replace("xmlns:",""))
  100. if "xmlns:s" in key: # get a numeric nsId and modelname/uri
  101. self.namespaceOrder.append((int(key.replace("xmlns:s","")), ns[0].getAttribute(key)))
  102. # Get all nodeIds contained in this XML
  103. for nd in ns[0].childNodes:
  104. if nd.nodeType != nd.ELEMENT_NODE:
  105. continue
  106. if nd.hasAttribute(u'NodeId'):
  107. self.containedNodes.append( (opcua_node_id_t(nd.getAttribute(u'NodeId')), nd) )
  108. refs = nd.getElementsByTagName(u'References')[0]
  109. for ref in refs.childNodes:
  110. if ref.nodeType == ref.ELEMENT_NODE:
  111. self.referencedNodes.append( (opcua_node_id_t(ref.firstChild.data), ref) )
  112. log(self, "Nodes: " + str(len(self.containedNodes)) + " References: " + str(len(self.referencedNodes)), LOG_LEVEL_DEBUG)
  113. def getNamespaceId(self):
  114. """ namespaceId()
  115. Counts the namespace IDs in all nodes of this XML and picks the most used
  116. namespace as the numeric identifier of this data model.
  117. returns: Integer ID of the most propable/most used namespace in this XML
  118. """
  119. max = 0;
  120. namespaceIdGuessed = 0;
  121. idDict = {}
  122. for ndid in self.containedNodes:
  123. if not idDict.has_key(ndid[0].ns):
  124. idDict[ndid[0].ns] = 1
  125. else:
  126. idDict[ndid[0].ns] = idDict[ndid[0].ns] + 1
  127. for entry in idDict:
  128. if idDict[entry] > max:
  129. max = idDict[entry]
  130. namespaceIdGuessed = entry
  131. log(self, "XML Contents are propably in namespace " + str(entry) + " (used by " + str(idDict[entry]) + " Nodes)", LOG_LEVEL_DEBUG)
  132. return namespaceIdGuessed
  133. def getReferencedNamespaceUri(self, nsId):
  134. """ getReferencedNamespaceUri
  135. returns an URL that hopefully corresponds to the nsId that was used to reference this model
  136. return: URI string corresponding to nsId
  137. """
  138. # Might be the more reliable method: Get the URI from the xmlns attributes (they have numers)
  139. if len(self.namespaceOrder) > 0:
  140. for el in self.namespaceOrder:
  141. if el[0] == nsId:
  142. return el[1]
  143. # Fallback:
  144. # Some models do not have xmlns:sX attributes, but still <URI>s (usually when they only reference NS0)
  145. if len(self.referencedNamesSpaceUris) > 0 and len(self.referencedNamesSpaceUris) >= nsId-1:
  146. return self.referencedNamesSpaceUris[nsId-1]
  147. #Nope, not found.
  148. return ""
  149. def getNamespaceDependencies(self):
  150. deps = []
  151. for ndid in self.referencedNodes:
  152. if not ndid[0].ns in deps:
  153. deps.append(ndid[0].ns)
  154. return deps
  155. def finalize(self):
  156. outfile = self.targetXML[0]
  157. outline = self.nodeset.toxml()
  158. for qualifier in self.namespaceQualifiers:
  159. rq = qualifier+":"
  160. outline = outline.replace(rq.decode('UTF-8'), "")
  161. os.write(outfile, outline.encode('UTF-8'))
  162. os.close(outfile)
  163. def reassignReferencedNamespaceId(self, currentNsId, newNsId):
  164. """ reassignReferencedNamespaceId
  165. Iterates over all references in this document, find references to currentNsId and changes them to newNsId.
  166. NodeIds themselves are not altered.
  167. returns: nothing
  168. """
  169. for refNd in self.referencedNodes:
  170. if refNd[0].ns == currentNsId:
  171. refNd[1].firstChild.data = refNd[1].firstChild.data.replace("ns="+str(currentNsId), "ns="+str(newNsId))
  172. refNd[0].ns = newNsId
  173. refNd[0].toString()
  174. def reassignNamespaceId(self, currentNsId, newNsId):
  175. """ reassignNamespaceId
  176. Iterates over all nodes in this document, find those in namespace currentNsId and changes them to newNsId.
  177. returns: nothing
  178. """
  179. log(self, "Migrating nodes /w ns index " + str(currentNsId) + " to " + str(newNsId), LOG_LEVEL_DEBUG)
  180. for nd in self.containedNodes:
  181. if nd[0].ns == currentNsId:
  182. # In our own document, update any references to this node
  183. for refNd in self.referencedNodes:
  184. if refNd[0].ns == currentNsId and refNd[0] == nd[0]:
  185. refNd[1].firstChild.data = refNd[1].firstChild.data.replace("ns="+str(currentNsId), "ns="+str(newNsId))
  186. refNd[0].ns = newNsId
  187. refNd[0].toString()
  188. nd[1].setAttribute(u'NodeId', nd[1].getAttribute(u'NodeId').replace("ns="+str(currentNsId), "ns="+str(newNsId)))
  189. nd[0].ns = newNsId
  190. nd[0].toString()
  191. class open62541_XMLPreprocessor:
  192. preProcDocuments = []
  193. def __init__(self):
  194. self.preProcDocuments = []
  195. def addDocument(self, documentPath):
  196. self.preProcDocuments.append(preProcessDocument(documentPath))
  197. def removePreprocessedFiles(self):
  198. for doc in self.preProcDocuments:
  199. doc.clean()
  200. def getPreProcessedFiles(self):
  201. files = []
  202. for doc in self.preProcDocuments:
  203. if (doc.parseOK):
  204. files.append(doc.getTargetXMLName())
  205. return files
  206. def testModelCongruencyAgainstReferences(self, doc, refs):
  207. """ testModelCongruencyAgainstReferences
  208. Counts how many of the nodes referencef in refs can be found in the model
  209. doc.
  210. returns: double corresponding to the percentage of hits
  211. """
  212. sspace = len(refs)
  213. if sspace == 0:
  214. return float(0)
  215. found = 0
  216. for ref in refs:
  217. for n in doc.containedNodes:
  218. if str(ref) == str(n[0]):
  219. print ref, n[0]
  220. found = found + 1
  221. break
  222. return float(found)/float(sspace)
  223. def preprocess_assignUniqueNsIds(self):
  224. nsdep = []
  225. docLst = []
  226. # Search for namespace 0('s) - plural possible if user is overwriting NS0 defaults
  227. # Remove them from the list of namespaces, zero does not get demangled
  228. for doc in self.preProcDocuments:
  229. if doc.getNamespaceId() == 0:
  230. docLst.append(doc)
  231. for doc in docLst:
  232. self.preProcDocuments.remove(doc)
  233. # Reassign namespace id's to be in ascending order
  234. nsidx = 1 # next namespace id to assign on collision (first one will be "2")
  235. for doc in self.preProcDocuments:
  236. nsidx = nsidx + 1
  237. nsid = doc.getNamespaceId()
  238. doc.reassignNamespaceId(nsid, nsidx)
  239. docLst.append(doc)
  240. log(self, "Document " + doc.originXML + " is now namespace " + str(nsidx), LOG_LEVEL_INFO)
  241. self.preProcDocuments = docLst
  242. def getUsedNamespaceArrayNames(self):
  243. """ getUsedNamespaceArrayNames
  244. Returns the XML xmlns:s1 or <URI>[0] of each XML document (if contained/possible)
  245. returns: dict of int:nsId -> string:url
  246. """
  247. nsName = {}
  248. for doc in self.preProcDocuments:
  249. uri = doc.getReferencedNamespaceUri(1)
  250. if uri == None:
  251. uri = "http://modeluri.not/retrievable/from/xml"
  252. nsName[doc.getNamespaceId()] = doc.getReferencedNamespaceUri(1)
  253. return nsName
  254. def preprocess_linkDependantModels(self):
  255. revertToStochastic = [] # (doc, int id), where id was not resolvable using model URIs
  256. # Attemp to identify the model relations by using model URIs in xmlns:sX or <URI> contents
  257. for doc in self.preProcDocuments:
  258. nsid = doc.getNamespaceId()
  259. dependencies = doc.getNamespaceDependencies()
  260. for d in dependencies:
  261. if d != nsid and d != 0:
  262. # Attempt to identify the namespace URI this d referes to...
  263. nsUri = doc.getReferencedNamespaceUri(d) # FIXME: This could actually fail and return ""!
  264. log(self, "Need a namespace referenced as " + str(d) + ". Which hopefully is " + nsUri, LOG_LEVEL_INFO)
  265. targetDoc = None
  266. for tgt in self.preProcDocuments:
  267. # That model, whose URI is known but its current id is not, will
  268. # refer have referred to itself as "1"
  269. if tgt.getReferencedNamespaceUri(1) == nsUri:
  270. targetDoc = tgt
  271. break
  272. if not targetDoc == None:
  273. # Found the model... relink the references
  274. doc.reassignReferencedNamespaceId(d, targetDoc.getNamespaceId())
  275. continue
  276. else:
  277. revertToStochastic.append((doc, d))
  278. log(self, "Failed to reliably identify which XML/Model " + os.path.basename(doc.originXML) + " calls ns=" +str(d), LOG_LEVEL_WARN)
  279. for (doc, d) in revertToStochastic:
  280. log(self, "Attempting to find stochastic match for target namespace ns=" + str(d) + " of " + os.path.basename(doc.originXML), LOG_LEVEL_WARN)
  281. # Copy all references to the given namespace
  282. refs = []
  283. matches = [] # list of (match%, targetDoc) to pick from later
  284. for ref in doc.referencedNodes:
  285. if ref[0].ns == d:
  286. refs.append(opcua_node_id_t(str(ref[0])))
  287. for tDoc in self.preProcDocuments:
  288. tDocId = tDoc.getNamespaceId()
  289. # Scenario: If these references did target this documents namespace...
  290. for r in refs:
  291. r.ns = tDocId
  292. r.toString()
  293. # ... how many of them would be found!?
  294. c = self.testModelCongruencyAgainstReferences(tDoc, refs)
  295. print c
  296. if c>0:
  297. matches.append(c, tDoc)
  298. best = (0, None)
  299. for m in matches:
  300. print m[0]
  301. if m[0] > best[0]:
  302. best = m
  303. if best[1] != None:
  304. log(self, "Best match (" + str(best[1]*100) + "%) for what " + os.path.basename(doc.originXML) + " refers to as ns="+str(d)+" was " + os.path.basename(best[1].originXML), LOG_LEVEL_WARN)
  305. doc.reassignReferencedNamespaceId(d, best[1].getNamespaceId())
  306. else:
  307. log(self, "Failed to find a match for what " + os.path.basename(doc.originXML) + " refers to as ns=" + str(d) ,LOG_LEVEL_ERROR )
  308. def preprocessAll(self):
  309. ##
  310. ## First: Gather statistics about the namespaces:
  311. for doc in self.preProcDocuments:
  312. doc.analyze()
  313. # Preprocess step: Remove XML specific Naming scheme ("uax:")
  314. # FIXME: Not implemented
  315. ##
  316. ## Preprocess step: Check namespace ID multiplicity and reassign IDs if necessary
  317. ##
  318. self.preprocess_assignUniqueNsIds()
  319. self.preprocess_linkDependantModels()
  320. ##
  321. ## Prep step: prevent any XML from using namespace 1 (reserved for instances)
  322. ## FIXME: Not implemented
  323. ##
  324. ## Final: Write modified XML tmp files
  325. for doc in self.preProcDocuments:
  326. doc.finalize()
  327. return True