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