open62541_XMLPreprocessor.py 14 KB

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