open62541_XMLPreprocessor.py 14 KB

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