import re from ssp.db import * import CommandDirector as cd from MySQLdb import OperationalError def match_hostname(host): try: return InvHost.get(InvHost.name == host) except InvHost.DoesNotExist: return None except OperationalError as e: print(host) print("Operational Error: %s" % e) def patternize_string(string): numbers = re.compile('[0-9]') letters = re.compile('[A-Z]', re.I) string = numbers.sub('1', string) string = letters.sub('0', string) return string def split_on_nth(string, split_character, span=1): """Split string on Nth split_character""" items = string.split(split_character) return [split_character.join(items[i:i + span]) for i in range(0, len(items), span)] def clean_string(input_string): "Utility function to clean strings of any unnecessary stuff" input_string = re.sub('\[\d+\]', '', input_string) return input_string def patternized_split(input_string, nth=1): input_string = clean_string(input_string) if nth > input_string.count("_"): return [input_string] patterned_list = split_on_nth(patternize_string(input_string), "_", nth) if (len(patterned_list) == 1): return [input_string] # if all items match each other: if all([item == patterned_list[0] for item in patterned_list]): return split_on_nth(input_string, "_", nth) else: return patternized_split(input_string, nth + 1) def main(): connect_env('dev') cli = cd.CommandDirectorCLI('a150495', 'xxxx') match = 0 counter = 0 unmatched = [] for server in cli.servers: for server_group in [app.application_name for app in server.applications]: try: for hostname in patternized_split(server_group): if match_hostname(hostname): match += 1 else: unmatched.append(hostname) counter += 1 except TypeError: print("Error: %s\n%s" % (server_group, hostname)) print "Matched %d out of %d: %f%% matched" % (match, counter, float(match) / float(counter) * 100) if __name__ == '__main__': main()