open62541_XMLPreprocessor.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. #change ids in aliases
  181. ns = self.nodeset.getElementsByTagName("Alias")
  182. for al in ns:
  183. if al.nodeType == al.ELEMENT_NODE:
  184. if al.hasAttribute("Alias"):
  185. al.firstChild.data = al.firstChild.data.replace("ns=" + str(currentNsId), "ns=" + str(newNsId))
  186. logger.debug("Migrating nodes /w ns index " + str(currentNsId) + " to " + str(newNsId))
  187. for nd in self.containedNodes:
  188. if nd[0].ns == currentNsId:
  189. # In our own document, update any references to this node
  190. for refNd in self.referencedNodes:
  191. if refNd[0].ns == currentNsId and refNd[0] == nd[0]:
  192. refNd[1].firstChild.data = refNd[1].firstChild.data.replace("ns="+str(currentNsId), "ns="+str(newNsId))
  193. refNd[0].ns = newNsId
  194. refNd[0].toString()
  195. nd[1].setAttribute(u'NodeId', nd[1].getAttribute(u'NodeId').replace("ns="+str(currentNsId), "ns="+str(newNsId)))
  196. nd[0].ns = newNsId
  197. nd[0].toString()
  198. class open62541_XMLPreprocessor:
  199. preProcDocuments = []
  200. def __init__(self):
  201. self.preProcDocuments = []
  202. def addDocument(self, documentPath):
  203. self.preProcDocuments.append(preProcessDocument(documentPath))
  204. def removePreprocessedFiles(self):
  205. for doc in self.preProcDocuments:
  206. doc.clean()
  207. def getPreProcessedFiles(self):
  208. files = []
  209. for doc in self.preProcDocuments:
  210. if (doc.parseOK):
  211. files.append(doc.getTargetXMLName())
  212. return files
  213. def testModelCongruencyAgainstReferences(self, doc, refs):
  214. """ testModelCongruencyAgainstReferences
  215. Counts how many of the nodes referencef in refs can be found in the model
  216. doc.
  217. returns: double corresponding to the percentage of hits
  218. """
  219. sspace = len(refs)
  220. if sspace == 0:
  221. return float(0)
  222. found = 0
  223. for ref in refs:
  224. for n in doc.containedNodes:
  225. if str(ref) == str(n[0]):
  226. print(ref, n[0])
  227. found = found + 1
  228. break
  229. return float(found)/float(sspace)
  230. def preprocess_assignUniqueNsIds(self):
  231. nsdep = []
  232. docLst = []
  233. # Search for namespace 0('s) - plural possible if user is overwriting NS0 defaults
  234. # Remove them from the list of namespaces, zero does not get demangled
  235. for doc in self.preProcDocuments:
  236. if doc.getNamespaceId() == 0:
  237. docLst.append(doc)
  238. for doc in docLst:
  239. self.preProcDocuments.remove(doc)
  240. # Reassign namespace id's to be in ascending order
  241. nsidx = 1 # next namespace id to assign on collision (first one will be "2")
  242. for doc in self.preProcDocuments:
  243. nsidx = nsidx + 1
  244. nsid = doc.getNamespaceId()
  245. doc.reassignNamespaceId(nsid, nsidx)
  246. docLst.append(doc)
  247. logger.info("Document " + doc.originXML + " is now namespace " + str(nsidx))
  248. self.preProcDocuments = docLst
  249. def getUsedNamespaceArrayNames(self):
  250. """ getUsedNamespaceArrayNames
  251. Returns the XML xmlns:s1 or <URI>[0] of each XML document (if contained/possible)
  252. returns: dict of int:nsId -> string:url
  253. """
  254. nsName = {}
  255. for doc in self.preProcDocuments:
  256. uri = doc.getReferencedNamespaceUri(1)
  257. if uri == None:
  258. uri = "http://modeluri.not/retrievable/from/xml"
  259. nsName[doc.getNamespaceId()] = doc.getReferencedNamespaceUri(1)
  260. return nsName
  261. def preprocess_linkDependantModels(self):
  262. revertToStochastic = [] # (doc, int id), where id was not resolvable using model URIs
  263. # Attemp to identify the model relations by using model URIs in xmlns:sX or <URI> contents
  264. for doc in self.preProcDocuments:
  265. nsid = doc.getNamespaceId()
  266. dependencies = doc.getNamespaceDependencies()
  267. for d in dependencies:
  268. if d != nsid and d != 0:
  269. # Attempt to identify the namespace URI this d referes to...
  270. nsUri = doc.getReferencedNamespaceUri(d) # FIXME: This could actually fail and return ""!
  271. logger.info("Need a namespace referenced as " + str(d) + ". Which hopefully is " + nsUri)
  272. targetDoc = None
  273. for tgt in self.preProcDocuments:
  274. # That model, whose URI is known but its current id is not, will
  275. # refer have referred to itself as "1"
  276. if tgt.getReferencedNamespaceUri(1) == nsUri:
  277. targetDoc = tgt
  278. break
  279. if not targetDoc == None:
  280. # Found the model... relink the references
  281. doc.reassignReferencedNamespaceId(d, targetDoc.getNamespaceId())
  282. continue
  283. else:
  284. revertToStochastic.append((doc, d))
  285. logger.warn("Failed to reliably identify which XML/Model " + os.path.basename(doc.originXML) + " calls ns=" +str(d))
  286. for (doc, d) in revertToStochastic:
  287. logger.warn("Attempting to find stochastic match for target namespace ns=" + str(d) + " of " + os.path.basename(doc.originXML))
  288. # Copy all references to the given namespace
  289. refs = []
  290. matches = [] # list of (match%, targetDoc) to pick from later
  291. for ref in doc.referencedNodes:
  292. if ref[0].ns == d:
  293. refs.append(opcua_node_id_t(str(ref[0])))
  294. for tDoc in self.preProcDocuments:
  295. tDocId = tDoc.getNamespaceId()
  296. # Scenario: If these references did target this documents namespace...
  297. for r in refs:
  298. r.ns = tDocId
  299. r.toString()
  300. # ... how many of them would be found!?
  301. c = self.testModelCongruencyAgainstReferences(tDoc, refs)
  302. print(c)
  303. if c>0:
  304. matches.append((c, tDoc))
  305. best = (0, None)
  306. for m in matches:
  307. print(m[0])
  308. if m[0] > best[0]:
  309. best = m
  310. if best[1] != None:
  311. 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))
  312. doc.reassignReferencedNamespaceId(d, best[1].getNamespaceId())
  313. else:
  314. logger.error("Failed to find a match for what " + os.path.basename(doc.originXML) + " refers to as ns=" + str(d))
  315. def preprocessAll(self):
  316. ##
  317. ## First: Gather statistics about the namespaces:
  318. for doc in self.preProcDocuments:
  319. doc.analyze()
  320. # Preprocess step: Remove XML specific Naming scheme ("uax:")
  321. # FIXME: Not implemented
  322. ##
  323. ## Preprocess step: Check namespace ID multiplicity and reassign IDs if necessary
  324. ##
  325. self.preprocess_assignUniqueNsIds()
  326. self.preprocess_linkDependantModels()
  327. ##
  328. ## Prep step: prevent any XML from using namespace 1 (reserved for instances)
  329. ## FIXME: Not implemented
  330. ##
  331. ## Final: Write modified XML tmp files
  332. for doc in self.preProcDocuments:
  333. doc.finalize()
  334. return True