Advertisement
Guest User

Untitled

a guest
Nov 27th, 2015
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.16 KB | None | 0 0
  1.  
  2. # class HostRemover
  3. #    __init__()
  4. #    removeHost()
  5. #    __removeFromDiscoveriesJson()
  6. #    __removeFromHostsFiles()
  7. #    __findContentFromAst()
  8. #    __substractNumberOfHosts()
  9. #    __cleanHostFile
  10.  
  11. import os
  12. import sys
  13. import re
  14. import mkFileVisitor
  15. import ast
  16. import json
  17. import fifi
  18.  
  19. class HostRemover():
  20.     def __init__(self, hostname):
  21.         self.hostname = hostname
  22.         self.ownFile = os.path.basename(__file__)
  23.  
  24.     # public class
  25.     # needs a list of files
  26.     def removeHost(self, files, discoveriesJson):
  27.         for filename in files:
  28.             if(self.__removeFromHostsFile(filename)):
  29.                 break
  30.         self.__removeFromDiscoveriesJson(discoveriesJson)
  31.            
  32.     def __removeFromDiscoveriesJson(self, discoveryFile):
  33.         if os.path.isfile(discoveryFile):
  34.             #load discoveries (json-object) and convert it to a list-object
  35.             discoveries = open(discoveryFile).read()
  36.             discoveriesDecoded = json.loads(discoveries)
  37.             newDiscoveries = dict()
  38.            
  39.             # loop the discoveries-list
  40.             # fill new list (without our host)
  41.             for host in discoveriesDecoded:
  42.                 if self.hostname not in host:
  43.                     newDiscoveries[host] = discoveriesDecoded[host]
  44.        
  45.             #convert our new list to an json-object
  46.             newDiscoveries = json.dumps(newDiscoveries)
  47.            
  48.             #save the new discovieres (without our host)
  49.             discoveries = open(discoveryFile,"w")
  50.             discoveries.write(str(newDiscoveries))
  51.             discoveries.close()
  52.         else:
  53.             print self.ownFile + " couldn't read " + os.path.abspath(discoveryFile)
  54.            
  55.     # such a stupid method to parse the host-files :@@@
  56.     def __removeFromHostsFile(self, filename):
  57.        
  58.         with open(filename, "r+") as hostfile:
  59.             hostInFile = False
  60.            
  61.             # loop the hosts-file
  62.             # and check if it contains our host
  63.             for line in hostfile:
  64.                 if self.hostname in line:
  65.                     hostInFile = True
  66.                     break
  67.            
  68.             if hostInFile:
  69.                 # set fileobject to begin
  70.                 hostfile.seek(0)
  71.                
  72.                 # creating new hosts-descriptions without our hosts:
  73.                 newContent = ""
  74.                 newContent += self.__findContentFromAst(filename, "ipaddresses", "update")
  75.                 newContent += self.__findContentFromAst(filename, "host_attributes", "update")
  76.                 newContent += self.__findContentFromAst(filename, "explicit_snmp_communities", "update")
  77.                
  78.                 # in "hosts.mk"-file are some host-descriptions
  79.                 # which are not traceable with python's AST-module:
  80.                 #
  81.                 #       host_contactgroups += [ ..content.. ]
  82.                 #       all_hosts += [ ..content.. ]
  83.                 #       extra_host_conf.setdefault('alias', []).extend( [ ..content.. ] )
  84.                 #       extra_host_conf.setdefault('parents', []).extend( [ ..content.. ] )
  85.                 #
  86.                 # so in the following i need to parse it on another way...
  87.                 contactGroupOrAllHosts = False
  88.                 extraHostConf = False
  89.                
  90.                 for line in hostfile:
  91.                    
  92.                     # check if the line contains necessary keywords
  93.                     if "host_contactgroups +=" in line or "all_hosts +=" in line:
  94.                         contactGroupOrAllHosts = True
  95.                     elif "extra_host_conf.setdefault('" in line:
  96.                         extraHostConf = True
  97.        
  98.                     if contactGroupOrAllHosts:
  99.                         if self.hostname not in line:
  100.                             newContent += line
  101.                         if "]" in line and len(line) < 3:
  102.                             contactGroupOrAllHosts=False
  103.                             newContent += "\n"
  104.                     elif extraHostConf:
  105.                         if "[(u'" in line and self.hostname in line:
  106.                             newContent += "["
  107.    
  108.                         if self.hostname in line and ")])" in line:
  109.                             newContent += "])\n\n"
  110.                         elif self.hostname not in line:
  111.                             newContent += line
  112.                            
  113.                         if ")])" in line:
  114.                             extraHostConf = False
  115.                             newContent += "\n"
  116.        
  117.                 newContent = self.__cleanHostFile(newContent)
  118.  
  119.                 hostfile.seek(0)
  120.                 hostfile.write(newContent)
  121.                 hostfile.truncate()
  122.                 watoFile = filename.split("hosts.mk")[0] + ".wato"
  123.                 self.__subtractNumberOfHosts(watoFile)
  124.                 return True
  125.             else:
  126.                 return False
  127.                
  128.     def __cleanHostFile(self, content):
  129.             # remove empty entries
  130.             content = content.replace("all_hosts += [\n]","")
  131.             content = content.replace("extra_host_conf.setdefault('alias', []).extend(\n[])","")
  132.             content = content.replace("extra_host_conf.setdefault('parents', []).extend(\n[])","")
  133.             content = content.replace("explicit_snmp_communities.update(\n{})","")
  134.             content = content.replace("host_contactgroups += [\n]","")
  135.             content = content.replace("ipaddresses.update(\n{})","")
  136.             content = content.replace("host_attributes.update(\n{})","")
  137.            
  138.             #remove needless line-breaks
  139.             for i in range(0,10):
  140.                 content = content.replace("\n\n\n","\n\n")
  141.                
  142.             return content
  143.        
  144.     # AST = abstract syntax tree
  145.     # .mk-files are also written in python-syntax,
  146.     # so we can find few content with pythons AST-module
  147.     def __findContentFromAst(self, filename, param1, param2):
  148.         fileContent = open(filename).read()
  149.        
  150.         # let us visit the file and seek for the passed parameter.
  151.         # visitor uses the AST-module for parsing the code
  152.         contentVisitor = mkFileVisitor.Visitor(param1, param2)
  153.         contentVisitor.visit(ast.parse(fileContent))
  154.        
  155.         newContent = dict()
  156.        
  157.         # loop visitors result
  158.         # save result as "newContent" without our host
  159.         for host in contentVisitor.result:
  160.             for item in host:
  161.                 if self.hostname not in item:
  162.                     newContent[item] = host[item]
  163.                    
  164.         return param1 + "." + param2 + "(\n" + str(newContent) + ")\n\n"
  165.        
  166.     # This method is written for hidden ".wato"-configuration-files.
  167.     # These files just store the number of hosts in a folder.
  168.     # In addition these files prsent the foldername.
  169.     def __subtractNumberOfHosts(self, filename):
  170.         with open(filename, "r+") as watofile:
  171.             number = 0
  172.             title = ""
  173.            
  174.             for line in watofile:
  175.                 # takes the number of host while using a regular expression:
  176.                 number = re.findall('([0-9]+)', line)[0]
  177.                
  178.                 # stores the folder-title while using split()
  179.                 if "'title': u'" in line:
  180.                     title = line.split("'title': u'")[1].split("'}")[0]
  181.                 else:
  182.                     title = line.split("'title': '")[1].split("'}")[0]
  183.            
  184.             if number:
  185.                 number = int(number)-1
  186.            
  187.             output = "{'attributes': {}, 'num_hosts': " + str(number) + ", 'title': u'" + title + "'}"
  188.            
  189.             watofile.seek(0)
  190.             watofile.write(output)
  191.             watofile.truncate()
  192.  
  193. def main():
  194.     hostname = sys.argv[1]
  195.     try:
  196.         finder = fifi.FileFinder("hosts.mk", root="../../../../etc/check_mk/conf.d/wato/")
  197.         files = finder.findFiles()
  198.     except:
  199.         print sys.exc_info()[0]
  200.    
  201.     remover = HostRemover(hostname)
  202.     remover.removeHost(files, "../discoveries.json")
  203.  
  204.    
  205. if __name__ == '__main__':
  206.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement