Project

General

Profile

Files » ansiblehostsmanager.py

Legrand François, 01/12/2018 02:39 PM

 
#!/usr/bin/python3
## @package ansiblehostmanager
# AHM, Ansible Hosts Manager is a python 3 interface to manage the inventory file (hosts file) of ansible
#
#

from PyQt4 import QtGui, QtCore
import sys, re, traceback, os.path, time

import interface_ansible

## Special groups
ungrouped = "ungrouped"
alls = "all"
specials = [ungrouped,alls]

## Class derived from QListWidget
class MyQListWidget(QtGui.QListWidget):
def __init__(self, parent=None, def_name=None):
if def_name is None:
(filename, line_number, function_name, text) = traceback.extract_stack()[-2]
def_name = text[:text.find('=')].strip().lstrip("self.")
self.defined_name = def_name
super(MyQListWidget, self).__init__(parent)
self.acceptfrom = []
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
#self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.setAcceptDrops(True)
### be careful #self.itemPressed.connect(self.item_Press)
self.selectedItem = ""
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.connect(self, QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.onrightclick)

## Implementation of right click
# Will be used to delete objects
def onrightclick(self, pos):
self.emit(QtCore.SIGNAL("rightclick"), pos)

def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(MyQListWidget, self).dragEnterEvent(event)
event.accept()

def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(MyQListWidget, self).dragMoveEvent(event)
event.accept()

def dropEvent(self, event):
if (event.source().defined_name in self.acceptfrom) or (event.source().defined_name == self.defined_name):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.MoveAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:

event.setDropAction(QtCore.Qt.MoveAction)
super(MyQListWidget, self).dropEvent(event)
self.emit(QtCore.SIGNAL("dropped"), event.source().defined_name)
event.accept()
# self.emit(QtCore.SIGNAL("inserted"))

## Catch events
# Raise signal "modified" when child is removed.
# This ensure that all the drag and drop events are finished so the lists are up to date
def event(self, QEvent):
res = super(MyQListWidget, self).event(QEvent)
#Raise signal modified when QEvent.type = ChildRemoved
if QEvent.type() == QtCore.QEvent.ChildRemoved :
self.emit(QtCore.SIGNAL("modified"))
return res

## Return all the items as a list
def getallitems(self):
items = []
for index in range(self.count()):
items.append(self.item(index))
return items


## Class to manage all the data of the Ansible hosts file
class AnsibleHostFile(object):
## Constructor
# Structure of the datas is the following:
# hosts : list of all hosts names
# groups : list of all groups names
# cgroups : list of all cgroups (children groups) names
# attributes : list of all attributes
# grouphosts : dictionary with group name as key and list of hosts in that group as value
# cgroupgroups : dictionary with cgroup name as key and list of groups or cgroups in that cgroup as value
# groupattributes : dictionary with group or cgroup name as key and list of attributes for that group/cgroup
# hostattributes : dictionary with host name as key and list of attributes for that host
def __init__(self):
self.hosts = []
self.groups = []
self.cgroups = []
self.attributes = []
self.grouphosts = {}
self.cgroupgroups = {}
self.groupattributes = {}
# self.cgroupcgroups = {}
self.hostattributes = {}
for gr in specials:
self.addgroup(gr)

def reset(self):
self.groups.clear()
self.hosts.clear()
self.attributes.clear()
self.cgroups.clear()
self.grouphosts.clear()
self.groupattributes.clear()
self.cgroupgroups.clear()
self.hostattributes.clear()
for gr in specials:
self.addgroup(gr)

## Function to check integrity of data
# It will check that same name is not use for host, group or cgroup and that members in cgroups are really defined as group or cgroup
def check_integrity(self):
message = ""
for host in self.hosts:
message += self.check_hostname(host)
for group in self.groups:
message += self.check_groupname(group)
#groups in cgroupgroups have to be a group or cgroup
for cgroup, groups in self.cgroupgroups.items():
for group in groups:
if group not in self.groups and group not in self.cgroups :
message += "\nError : group " + group + " appears in Cgroup "+cgroup+" but is not defined."
return "\n".join(set(message.split('\n')))

## Check that host name is not already used as group or cgroup name
def check_hostname(self,host):
message = ""
if host in self.groups:
message += "\nDuplicate name : " + host + " defined as host and group"
if host in self.cgroups:
message += "\nDuplicate name : " + host + " defined as host and Cgroup"
return message

## Check that group name is not already used as host or cgroup name
def check_groupname(self,group):
message = ""
if group in self.hosts:
message += "\nDuplicate name : " + group + " defined as host and group"
if group in self.cgroups:
message += "\nDuplicate name : " + group + " defined as group and Cgroup"
return message

## Check that cgroup name is not already used as host or group name
def check_cgroupname(self,cgroup):
message = ""
if cgroup in self.hosts:
message += "\nDuplicate name : " + cgroup + " defined as host and group"
if cgroup in self.groups:
message += "\nDuplicate name : " + cgroup + " defined as group and Cgroup"
return message

## Add host to the list of hosts
def addhost(self, host):
if host not in self.hosts:
self.hosts.append(host)

## Return the list of hosts
def gethosts(self):
return self.hosts

## Return hostname if in hosts list or None if not
def gethost(self, hostname):
if hostname in self.hosts:
return hostname
else:
return None

## Delete host from list of hosts and from group it was in
def delhost(self, host):
if host in self.hosts:
self.hosts.remove(host)
for group in self.grouphosts:
self.delhosttogroup(host, group)

## Add new group in list of groups (and in grouphosts)
def addgroup(self, group):
if group not in self.groups:
self.groups.append(group)
if group not in self.grouphosts:
grouphost = self.grouphosts.setdefault(group, [])

## Delete a group from groups list and from grouphosts and cgroupgroups
def delgroup(self, group):
if group in specials:
return
if group in self.groups:
self.groups.remove(group)
del self.grouphosts[group]
for cgroup in self.cgroupgroups:
self.delgrouptocgroup(group,cgroup)

## Return group if it exists or None if not
def getgroup(self, group):
if group in self.groups:
return group
else:
return None

## Return all groups
def getgroups(self):
return self.groups

## Add new cgroup in list of cgroups (and in cgroupgroups)
def addcgroup(self, cgroup):
if cgroup not in self.cgroups:
self.cgroups.append(cgroup)
if cgroup not in self.cgroupgroups:
cgroupgroups = self.cgroupgroups.setdefault(cgroup, [])

## Delete cgroup
def delcgroup(self, cgroup):
if cgroup in self.cgroups:
self.cgroups.remove(cgroup)
del self.cgroupgroups[cgroup]

## Return cgroup if it exists or None if not
def getcgroup(self, cgroup):
if cgroup in self.cgroups:
return cgroup
else:
return None

## Return all cgroups
def getcgroups(self):
return self.cgroups

## Add attribute to the list of attributes
def addattribute(self, attribute):
if attribute not in self.attributes:
self.attributes.append(attribute)
# self.attributes.update({attribute.name:attribute})

## Delete attribute
def delattribute(self, attribute):
if attribute in self.attributes:
self.attributes.remove(attribute)
for group in self.groupattributes:
self.delattributetogroup(attribute,group)
self.delattributetocgroup(attribute,group)
for host in self.hostattributes:
self.delattributetohost(attribute,host)

## Return all attributes
def getattributes(self):
return self.attributes

## Return all attributes
def gethostsattributes(self):
return self.attributes

## Return attribute if it exists or None if not
def getattribute(self, attribute):
if attribute in self.attributes:
return attribute
else:
return None

## Add host to group
def addhosttogroup(self, host, group):
#self.addgroup(group)
#self.addhost(host)
grouphost = self.grouphosts.setdefault(group, [])
if host not in grouphost:
grouphost.append(host)

## Add group to host
def addgrouptohost(self, group, host):
self.addhosttogroup(host, group)

## Remove host from group
def delhosttogroup(self, host, group):
grouphost = self.grouphosts.setdefault(group, [])
if host in grouphost:
grouphost.remove(host)

## Add group to cgroup
def addgrouptocgroup(self, group, cgroup):
#self.addgroup(group)
#self.addcgroup(cgroup)
cgroupgroups = self.cgroupgroups.setdefault(cgroup, [])
if group not in cgroupgroups:
cgroupgroups.append(group)

## Remove group from cgroup
def delgrouptocgroup(self, group, cgroup):
cgroupgroups = self.cgroupgroups.setdefault(cgroup, [])
if group in cgroupgroups:
cgroupgroups.remove(group)

## Add attribute to host
def addattributetohost(self, attribute, host):
#self.addattribute(attribute)
#self.addhost(host)
attributes = self.hostattributes.setdefault(host, [])
if attribute not in attributes:
attributes.append(attribute)
# self.hostattributes.update({host.name:attribute.name})

## Remove attribute from host
def delattributetohost(self, attribute, host):
hostattributes = self.hostattributes.setdefault(host, [])
if attribute in hostattributes:
hostattributes.remove(attribute)

## Add attribute to group
def addattributetogroup(self, attribute, group):
self.addattribute(attribute)
#self.addgroup(group)
groupattribute = self.groupattributes.setdefault(group, [])
if attribute not in groupattribute:
groupattribute.append(attribute)
# self.groupattributes.update({group.name:attribute.name})

## Remove attribute from group
def delattributetogroup(self, attribute, group):
groupattributes = self.groupattributes.setdefault(group, [])
if attribute in groupattributes:
groupattributes.remove(attribute)

## Add attribute to cgroup
def addattributetocgroup(self, attribute, cgroup):
#self.addattribute(attribute)
#self.addgroup(group)
cgroupattribute = self.groupattributes.setdefault(cgroup, [])
if attribute not in cgroupattribute:
cgroupattribute.append(attribute)
# self.groupattributes.update({group.name:attribute.name})

## Remove attribute from cgroup
def delattributetocgroup(self, attribute, cgroup):
cgroupattributes = self.groupattributes.setdefault(cgroup, [])
if attribute in cgroupattributes:
cgroupattributes.remove(attribute)

## Return dictionary with group name as key and hostname as value for the required host name
def getgroupsforhost(self, hostname):
subdict = dict((k, v) for k, v in self.grouphosts.items() if hostname in v)
return subdict

## Return dictionary with cgroup name as key and group name as value for the required cgroup name
def getgroupforcgroup(self, cgroup):
subdict = dict((k, v) for k, v in self.cgroupgroups.items() if cgroup == k)
return subdict

# def getcgroupforcgroup(self, cgroup):
# subdict = dict((k, v) for k, v in self.cgroupcgroups.items() if cgroup == k)
# return subdict

## Return dictionary with group name as key and attribute as value for the required attribute
def getgroupforattribute(self, attribute):
subdict1 = dict((k, v) for k, v in self.groupattributes.items() if attribute in v)
#need to filter group (and not cgroup)
subdict = dict((k, v) for k, v in subdict1.items() if k in self.groups)
return subdict

## Return dictionary with cgroup name as key and attribute as value for the required attribute
def getcgroupforattribute(self, attribute):
subdict1 = dict((k, v) for k, v in self.groupattributes.items() if attribute in v)
#need to filter cgroup (and not group)
subdict = dict((k, v) for k, v in subdict1.items() if k in self.cgroups)
return subdict

## Return dictionary with host name as key and attribute as value for the required host name
def getattributesforhost(self, hostname):
subdict = dict((k, v) for k, v in self.hostattributes.items() if hostname == k)
return subdict

## Return dictionary with host name as key and attribute as value for the required attribute
def gethostsforattribute(self, attributename):
subdict = dict((k, v) for k, v in self.hostattributes.items() if attributename in v)
return subdict

## Return dictionary with group name as key and attribute as value for required the group name
def getattributesforgroup(self,groupname):
subdict = dict((k, v) for k, v in self.groupattributes.items() if groupname == k)
return subdict

## Return dictionary with group name as key and host name as value for required the group name
def gethostsforgroup(self, groupname):
subdict = dict((k, v) for k, v in self.grouphosts.items() if groupname == k)
return subdict

## Return a sorted list
def get_items(self,liste):
#return liste.items()
return sorted(liste.items())

## Function to generate the ansible host file
# It will first check the integrity of the date and eventually include some warnings
# then it will list all ungroupped hosts
# then attributes for group "all"
# then groups in alphabetical order
# then cgroups in alphabetical order
def export_ansible(self):
self.update_ungroupped()
export = "# Ansible host file generated by the Ansible Hosts Manager \n"

check_integrity_msg = self.check_integrity()
if check_integrity_msg is not "":
export += "\n#Check integrity result:"
export += check_integrity_msg.replace("\n","\n#")+"\n\n"

# We start by ungrouped and follow by all then the rest
group = self.grouphosts.setdefault(ungrouped, [])
for host in group:
export += host + " "
attributes = self.hostattributes.setdefault(host, [])
for attribute in sorted(attributes):
export += " " + attribute
export += "\n"

listattr = ""

# Variable for group all
attributes = self.groupattributes.setdefault(alls, [])
if group is not None:
for attribute in attributes:
listattr += attribute+"\n"
if listattr != "":
export += "\n[" + alls + ":vars]\n"+listattr

# All groups and groups vars (attributes)
for group in self.get_items(self.grouphosts):
#if group[0] == alls:
# if group[0] in self.groupattributes:
# for attribute in sorted(self.groupattributes[group[0]]):
# listattr += attribute+"\n"
# if listattr != "":
# export += "\n[" + group[0] + ":vars]\n"+listattr

if group[0] not in specials:
export += "\n[" + group[0] + "]\n"
for host in group[1]:
export += host
attributes = self.hostattributes.setdefault(host, [])
for attribute in sorted(attributes):
export += " " + attribute
export += "\n"
listattr = ""
if group[0] in self.groupattributes:
for attribute in sorted(self.groupattributes[group[0]]):
listattr += attribute+"\n"
if listattr != "":
export += "\n[" + group[0] + ":vars]\n"+listattr

# All cgroups and vars
for cgroup in self.get_items(self.cgroupgroups):
export += "\n[" + cgroup[0] + ":children]\n"
for group in cgroup[1]:
export += group + "\n"
#attributes = self.hostattributes.setdefault(group, [])
#for attribute in sorted(attributes):
# export += " ------------------------------ " + attribute
#export += "\n"
listattr = ""
if cgroup[0] in self.groupattributes:
for attribute in sorted(self.groupattributes[cgroup[0]]):
listattr += attribute+"\n"
if listattr != "":
export += "\n[" + cgroup[0] + ":vars]\n"+listattr
return export

## Function to manage the list of "ungroupped" hosts.
# It will search for the presence of any host in the grouphost list
# and put hosts which are not in a group in the "ungroupped" group
def update_ungroupped(self):
for host in self.gethosts():
for group in self.getgroupsforhost(host):
# If host is in a group (not ungroupped) then remove it from ungroupped
if group != ungrouped:
self.delhosttogroup(host,ungrouped)
break
else:
self.addhosttogroup(host,ungrouped)

## Class to manage the graphic interface
class ImageViewer(QtGui.QMainWindow, interface_ansible.Ui_MainWindow):
def __init__(self, parent=None):
super(ImageViewer, self).__init__(parent)
self.ansible = AnsibleHostFile()

self.setupUi(self)

# Define connectors
self.tabs.currentChanged.connect(self.ontabchange)
self.actionload_hostsfile.triggered.connect(self.load_hostsfile)
self.Loadhostfile.clicked.connect(self.load_hostsfile)
self.actionSauver.triggered.connect(self.save_hostsfile)
self.Savehostfile.clicked.connect(self.save_hostsfile)
self.actionQuitter.triggered.connect(self.quit)

# Tab Hosts
QtCore.QObject.connect(self.addhost, QtCore.SIGNAL("clicked()"), self.clic_addnewhost)
QtCore.QObject.connect(self.hosttoadd, QtCore.SIGNAL("returnPressed()"), self.clic_addnewhost)
self.hostslist.itemSelectionChanged.connect(self.update_listhostgroups)
QtCore.QObject.connect(self.hostgroupslist, QtCore.SIGNAL("dropped"), self.add_group_to_host)
QtCore.QObject.connect(self.availablegroupslist, QtCore.SIGNAL("dropped"), self.remove_group_to_host)
QtCore.QObject.connect(self.hostattributeslist, QtCore.SIGNAL("dropped"), self.add_attribute_to_host)
QtCore.QObject.connect(self.availableattributeslist, QtCore.SIGNAL("dropped"), self.remove_attribute_to_host)
QtCore.QObject.connect(self.hostslist, QtCore.SIGNAL("rightclick"), self.delhost)

# Tab Groups
QtCore.QObject.connect(self.addgroup, QtCore.SIGNAL("clicked()"), self.clic_addnewgroup)
QtCore.QObject.connect(self.grouptoadd, QtCore.SIGNAL("returnPressed()"), self.clic_addnewgroup)
self.groupslist.itemSelectionChanged.connect(self.update_listgrouphosts)
#QtCore.QObject.connect(self.grouphostslist, QtCore.SIGNAL("dropped"), self.add_host_to_group)
QtCore.QObject.connect(self.grouphostslist, QtCore.SIGNAL("modified"), self.reload_grouphosts)
QtCore.QObject.connect(self.availablehostslist_2, QtCore.SIGNAL("modified"), self.reload_grouphosts)
#QtCore.QObject.connect(self.availablehostslist_2, QtCore.SIGNAL("dropped"), self.remove_host_to_group)
QtCore.QObject.connect(self.groupslist, QtCore.SIGNAL("rightclick"), self.delgroup)
QtCore.QObject.connect(self.groupattributeslist, QtCore.SIGNAL("dropped"), self.add_attribute_to_group)
QtCore.QObject.connect(self.availableattributeslist_2, QtCore.SIGNAL("dropped"), self.remove_attribute_to_group)

# Tab cgroups
QtCore.QObject.connect(self.addcgroup, QtCore.SIGNAL("clicked()"), self.clic_addnewcgroup)
QtCore.QObject.connect(self.cgrouptoadd, QtCore.SIGNAL("returnPressed()"), self.clic_addnewcgroup)
self.cgroupslist.itemSelectionChanged.connect(self.update_listcgroupgroups)
#QtCore.QObject.connect(self.groupcgroupslist, QtCore.SIGNAL("dropped"), self.add_group_to_cgroup)
QtCore.QObject.connect(self.groupcgroupslist, QtCore.SIGNAL("modified"), self.reload_cgroupgroups)
QtCore.QObject.connect(self.availablegroupslist_2, QtCore.SIGNAL("modified"), self.reload_cgroupgroups)
#QtCore.QObject.connect(self.availablegroupslist_2, QtCore.SIGNAL("dropped"), self.remove_group_to_cgroup)
QtCore.QObject.connect(self.cgroupslist, QtCore.SIGNAL("rightclick"), self.delcgroup)
QtCore.QObject.connect(self.cgroupattributeslist, QtCore.SIGNAL("dropped"), self.add_attribute_to_cgroup)
QtCore.QObject.connect(self.availableattributeslist_3, QtCore.SIGNAL("dropped"), self.remove_attribute_to_cgroup)

# Tab attributes
QtCore.QObject.connect(self.addattribute, QtCore.SIGNAL("clicked()"), self.addnewattribute)
QtCore.QObject.connect(self.attributetoadd, QtCore.SIGNAL("returnPressed()"), self.addnewattribute)
self.attributeslist.itemSelectionChanged.connect(self.update_listattributegroup)
QtCore.QObject.connect(self.attributehostslist, QtCore.SIGNAL("dropped"), self.add_host_to_attribute)
QtCore.QObject.connect(self.availablehostslist_3, QtCore.SIGNAL("dropped"), self.remove_host_to_attribute)
QtCore.QObject.connect(self.attributegroupslist, QtCore.SIGNAL("dropped"), self.add_group_to_attribute)
QtCore.QObject.connect(self.availablegroupslist_3, QtCore.SIGNAL("dropped"), self.remove_group_to_attribute)
QtCore.QObject.connect(self.attributecgroupslist, QtCore.SIGNAL("dropped"), self.add_cgroup_to_attribute)
QtCore.QObject.connect(self.availablecgroupslist, QtCore.SIGNAL("dropped"), self.remove_cgroup_to_attribute)
QtCore.QObject.connect(self.attributeslist, QtCore.SIGNAL("rightclick"), self.delattribute)

## This to define the list between which drag and drop is authorized
self.hostgroupslist.acceptfrom = ["availablegroupslist"]
self.availablegroupslist.acceptfrom = ["hostgroupslist"]
self.groupattributeslist.acceptfrom = ["availableattributeslist_2"]
self.availableattributeslist_2.acceptfrom = ["groupattributeslist"]
self.hostattributeslist.acceptfrom = ["availableattributeslist"]
self.availableattributeslist.acceptfrom = ["hostattributeslist"]
self.grouphostslist.acceptfrom = ["availablehostslist_2"]
self.availablehostslist_2.acceptfrom = ["grouphostslist"]
self.groupcgroupslist.acceptfrom = ["availablegroupslist_2"]
self.availablegroupslist_2.acceptfrom = ["groupcgroupslist"]
self.cgroupattributeslist.acceptfrom = ["availableattributeslist_3"]
self.availableattributeslist_3.acceptfrom = ["cgroupattributeslist"]
self.attributegroupslist.acceptfrom = ["availablegroupslist_3"]
self.availablegroupslist_3.acceptfrom = ["attributegroupslist"]
self.attributecgroupslist.acceptfrom =["availablecgroupslist"]
self.availablecgroupslist.acceptfrom = ["attributecgroupslist"]
self.attributehostslist.acceptfrom = ["availablehostslist_3"]
self.availablehostslist_3.acceptfrom = ["attributehostslist"]

## Set the current tab to host view
self.tabs.setCurrentIndex(0)


def quit(self):
print("bye bye")
sys.exit(0)

def save_hostsfile(self):
filename = QtGui.QFileDialog.getOpenFileName(self, 'File to save')
if filename != "":
if os.path.isfile(filename):
warn_msg = "File exists. Do you want to overwrite ?"
reply = QtGui.QMessageBox.question(self, 'Message',warn_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

if reply == QtGui.QMessageBox.No:
return

file = open(filename, 'w')
result = self.ansible.export_ansible()
file.write(result)
file.close()


## On tab change event catcher
# will update lists of the new tab to get modification made previously
# will generate the new hosts file when tab "view hosts file" is activated
def ontabchange(self,i):
if i == 0:
self.update_liststabhosts()
elif i == 1:
self.update_liststabgroups()
elif i == 2:
self.update_liststabcgroups()
elif i == 3:
self.update_liststabattributes()
elif i == 4:
result = self.ansible.export_ansible()
self.textEdit.setText(result)
#QtGui.QMessageBox.information(self,
# "Tab Index Changed!",
# "Current Tab Index: %d" % i ) #changed!


## Delete a host
# will ask for confirmation
def delhost(self, pos):
menu = QtGui.QMenu(self)
texte = ""
for host in self.hostslist.selectedItems():
texte += host.text() + " "
delAction = menu.addAction("Delete " + texte)
action = menu.exec_(self.hostslist.mapToGlobal(pos))
if action == delAction:
for hostname in self.hostslist.selectedItems():
warn_msg = "Are you sure you want to delete host " + hostname.text() + " ?"
reply = QtGui.QMessageBox.question(self, 'Message', warn_msg, QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
self.ansible.delhost(hostname.text())
self.update_listallhosts()

## Delete a group
# will ask for confirmation
def delgroup(self, pos):
menu = QtGui.QMenu(self)
texte = ""
for group in self.groupslist.selectedItems():
if group.text() in specials:
return
texte += group.text() + " "
delAction = menu.addAction("Delete " + texte)
action = menu.exec_(self.groupslist.mapToGlobal(pos))
if action == delAction:
for groupname in self.groupslist.selectedItems():
# hostname = self.hostslist.selectedItem.text()
# host=host(hostname)
warn_msg = "Are you sure you want to delete group "+groupname.text()+" ?"
reply = QtGui.QMessageBox.question(self, 'Message', warn_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
self.ansible.delgroup(groupname.text())
self.update_listallgroups()

## Delete a cgroup
# will ask for confirmation
def delcgroup(self, pos):
menu = QtGui.QMenu(self)
texte = ""
for cgroup in self.cgroupslist.selectedItems():
texte += cgroup.text() + " "
delAction = menu.addAction("Delete " + texte)
action = menu.exec_(self.cgroupslist.mapToGlobal(pos))
if action == delAction:
for cgroupname in self.cgroupslist.selectedItems():
warn_msg = "Are you sure you want to delete Cgroup " + cgroupname.text() + " ?"
reply = QtGui.QMessageBox.question(self, 'Message', warn_msg, QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
self.ansible.delcgroup(cgroupname.text())
self.update_listallcgroups()

## Delete an attribute
# will ask for confirmation
def delattribute(self,pos):
menu = QtGui.QMenu(self)
texte = ""
for attribute in self.attributeslist.selectedItems():
texte += attribute.text() + " "
delAction = menu.addAction("Delete " + texte)
action = menu.exec_(self.attributeslist.mapToGlobal(pos))
if action == delAction:
for attributename in self.attributeslist.selectedItems():
warn_msg = "Are you sure you want to delete attribute " + attributename.text() + " ?"
reply = QtGui.QMessageBox.question(self, 'Message', warn_msg, QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
self.ansible.delattribute(attributename.text())
self.update_listallattributes()


## function to load a hosts file
def load_hostsfile(self):
self.ansible.reset()
filename = QtGui.QFileDialog.getOpenFileName(self,'File to open')
#filename = "hosts"
file = open(filename, 'r')
current_group = ungrouped
cgroup = False
vargroup = False
while 1:
line = file.readline()
if not line:
break
line = line.strip(" \t\n\r")

if len(line) > 1:
# Pass comments and empty lines
if line[0] == "#":
pass
elif line == '':
pass
# Detect groups
elif line[0] == "[":
# Get name of group (part between []
newgroupname = re.search('^\[(.*)\]', line).group(1)
# Search for cgroup
lcgroup = re.search('(.*):children', newgroupname)

if lcgroup is None:
cgroup = False
groupvar = re.search('(.*):vars', newgroupname)
if groupvar is None:
self.ansible.addgroup(newgroupname)
vargroup = False
else:
newgroupname = groupvar.group(1)
vargroup = True
#self.ansible.addgroup(newgroupname) #PB No way to know if group or cgroup if not defined before !

else:
newgroupname = lcgroup.group(1)
self.ansible.addcgroup(lcgroup.group(1))
cgroup = True
vargroup = False
current_group = newgroupname
# newgroup = group(newgroupname)
# Add group to the list of groups if not already here


# Read host and attributes
else:
if not vargroup:
self.addnewhost(line, current_group, cgroup)
else:
self.addgroupattribute(line,current_group)
self.update_alllists()
check_result=self.ansible.check_integrity()
if check_result:
message = QtGui.QMessageBox()
message.setIcon(QtGui.QMessageBox.Warning)
message.setText(check_result)
message.exec()

def addgroupattribute(self,line=None, group=None):
self.ansible.addattributetogroup(line,group)

## Function activated for manual add a new host from the interface
# Check the existence of host name as group or cgroup name and popup a warning before calling addnewhost()
def clic_addnewhost(self):
hostname = self.hosttoadd.text()
warn_msg = self.ansible.check_hostname(hostname)
if warn_msg is not "":
warn_msg += "\nAre you sure you want to add host " + hostname + " ?"
reply = QtGui.QMessageBox.question(self, 'Message', warn_msg, QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
self.addnewhost(hostname)
else:
self.addnewhost(hostname)

## Add a new host
# called by clic_addnewhost() or load_hostsfile()
def addnewhost(self, line=None, group=None, cgroup=False):
if line is None:
line = self.hosttoadd.text()
if line == "":
return

if group is None:
group = ungrouped
cgroup = False
hostname = line.split()

if cgroup:
newgroup = hostname[0]
cgroup = group
#Not adding group because we don't know if it's a group or cgroup
#self.ansible.addgroup(newgroup)
self.ansible.addgrouptocgroup(newgroup, cgroup)
else:
newhost = hostname[0]
self.ansible.addhost(newhost)
if len(hostname) > 1:
for i in range(1, len(hostname)):
attribute = hostname[i].split('=')
if len(attribute) > 1:
newattribute = attribute[0] + "=" + attribute[1]
self.ansible.addattribute(newattribute)
self.ansible.addattributetohost(newattribute, newhost)
self.ansible.addhosttogroup(newhost, group)
self.update_listallattributes()
self.update_listallhosts()
self.hosttoadd.clear()

## Function activated for manual add a new group from the interface
# Check the existence of group name as host or cgroup name and popup a warning before calling addnewgroup()
def clic_addnewgroup(self):
groupname = self.grouptoadd.text()
warn_msg = self.ansible.check_groupname(groupname)
if warn_msg is not "":
warn_msg += "\nAre you sure you want to add group " + groupname + " ?"
reply = QtGui.QMessageBox.question(self, 'Message', warn_msg, QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
self.addnewgroup(groupname)
else:
self.addnewgroup(groupname)

## Add a new group
# called by clic_addnewgroup() or load_hostsfile()
def addnewgroup(self, newgroupname=None):
if newgroupname is None:
newgroupname = self.grouptoadd.text()
if newgroupname == "":
return
# Add group to the list of groups if not already here
if newgroupname not in self.ansible.groups:
self.ansible.addgroup(newgroupname)
self.update_listallgroups()
self.grouptoadd.clear()

## Function activated for manual add a new cgroup from the interface
# Check the existence of cgroup name as host or group name and popup a warning before calling addnewcgroup()
def clic_addnewcgroup(self):
cgroupname = self.cgrouptoadd.text()
warn_msg = self.ansible.check_cgroupname(cgroupname)
if warn_msg is not "":
warn_msg += "\nAre you sure you want to add Cgroup " + cgroupname + " ?"
reply = QtGui.QMessageBox.question(self, 'Message', warn_msg, QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
self.addnewcgroup(cgroupname)
else:
self.addnewcgroup(cgroupname)

## Add a new cgroup
# called by clic_addnewcgroup() or load_hostsfile()
def addnewcgroup(self, newcgroupname=None):
if newcgroupname is None:
newcgroupname = self.cgrouptoadd.text()
if newcgroupname == "":
return
# Add group to the list of groups if not already here
if newcgroupname not in self.ansible.cgroups:
self.ansible.addcgroup(newcgroupname)
self.update_listallcgroups()
self.cgrouptoadd.clear()

## Add a new attribute
def addnewattribute(self, newattributename=None):
if newattributename is None:
newattributename = self.attributetoadd.text()
if newattributename == "":
return
if newattributename not in self.ansible.attributes:
self.ansible.addattribute(newattributename)
self.update_listallattributes()
self.attributetoadd.clear()

def update_listhostgroups(self):
self.hostgroupslist.clear()
self.update_listavailablegroups()
if self.hostslist.currentItem() is not None:
selected_host = str(self.hostslist.currentItem().text())
for group in self.ansible.getgroupsforhost(selected_host).items():
# Add it to the list of groups for this host
# self.hostgroupslist.addItem(group[0])
if group[0] not in specials:
QtGui.QListWidgetItem(group[0], self.hostgroupslist)
# Remove it from the available groups
for item in self.availablegroupslist.findItems(group[0], QtCore.Qt.MatchExactly):
self.availablegroupslist.takeItem(self.availablegroupslist.row(item))
self.update_listhostattributes()

def update_listgrouphosts(self):
self.grouphostslist.clear()
self.update_listavailablehosts()
if self.groupslist.currentItem() is not None:
selected_group = str(self.groupslist.currentItem().text())
for hosts in self.ansible.gethostsforgroup(selected_group).items():
for host in hosts[1]:
# Add it to the list of hosts for this group
QtGui.QListWidgetItem(host, self.grouphostslist)
# Remove it from the available groups
for item in self.availablehostslist_2.findItems(host, QtCore.Qt.MatchExactly):
self.availablehostslist_2.takeItem(self.availablehostslist_2.row(item))
self.update_listgroupattributes()

def update_listcgroupgroups(self):
self.groupcgroupslist.clear()
self.update_listavailablegroups_2()
if self.cgroupslist.currentItem() is not None:
selected_cgroup = str(self.cgroupslist.currentItem().text())
for item in self.availablegroupslist_2.findItems(selected_cgroup, QtCore.Qt.MatchExactly):
self.availablegroupslist_2.takeItem(self.availablegroupslist_2.row(item))
for groups in self.ansible.getgroupforcgroup(selected_cgroup).items():
# Add it to the list of hosts for this group
for group in groups[1]:
QtGui.QListWidgetItem(group, self.groupcgroupslist)
# Remove it from the available groups
for item in self.availablegroupslist_2.findItems(group, QtCore.Qt.MatchExactly):
self.availablegroupslist_2.takeItem(self.availablegroupslist_2.row(item))
self.update_listcgroupattributes()

def update_listattributehosts(self):
self.attributehostslist.clear()
self.update_listavailablehosts_3()
if self.attributeslist.currentItem() is not None:
selected_attribute = str(self.attributeslist.currentItem().text())
for hosts in self.ansible.gethostsforattribute(selected_attribute).items():
# Add it to the list of hosts for this group
QtGui.QListWidgetItem(hosts[0], self.attributehostslist)
# Remove it from the available groups
for item in self.availablehostslist_3.findItems(hosts[0], QtCore.Qt.MatchExactly):
self.availablehostslist_3.takeItem(self.availablehostslist_3.row(item))

def update_listattributegroup(self):
self.attributegroupslist.clear()
self.update_listavailablegroups_3()
if self.attributeslist.currentItem() is not None:
selected_attribute = str(self.attributeslist.currentItem().text())
for groups in self.ansible.getgroupforattribute(selected_attribute).items():
# Add it to the list of hosts for this group
QtGui.QListWidgetItem(groups[0], self.attributegroupslist)
# Remove it from the available groups
for item in self.availablegroupslist_3.findItems(groups[0], QtCore.Qt.MatchExactly):
self.availablegroupslist_3.takeItem(self.availablegroupslist_3.row(item))
self.update_listattributecgroup()
self.update_listattributehosts()

def update_listattributecgroup(self):
self.attributecgroupslist.clear()
self.update_listavailablecgroups()
if self.attributeslist.currentItem() is not None:
selected_attribute = str(self.attributeslist.currentItem().text())
for cgroups in self.ansible.getcgroupforattribute(selected_attribute).items():
# Add it to the list of hosts for this group
QtGui.QListWidgetItem(cgroups[0], self.attributecgroupslist)
# Remove it from the available groups
for item in self.availablecgroupslist.findItems(cgroups[0], QtCore.Qt.MatchExactly):
self.availablecgroupslist.takeItem(self.availablecgroupslist.row(item))
#self.update_listgroupattributes()

def update_listhostattributes(self):
self.hostattributeslist.clear()
self.update_listavailableattributes()
if self.hostslist.currentItem() is not None:
selected_host = str(self.hostslist.currentItem().text())
for attributes in self.ansible.getattributesforhost(selected_host).items():
for attribute in attributes[1]:
QtGui.QListWidgetItem(attribute, self.hostattributeslist)
for item in self.availableattributeslist.findItems(attribute, QtCore.Qt.MatchExactly):
self.availableattributeslist.takeItem(self.availableattributeslist.row(item))

def update_listgroupattributes(self):
self.groupattributeslist.clear()
self.update_listallattributes()
if self.groupslist.currentItem() is not None:
selected_group = str(self.groupslist.currentItem().text())
for attributes in self.ansible.getattributesforgroup(selected_group).items():
for attribute in attributes[1]:
QtGui.QListWidgetItem(attribute, self.groupattributeslist)
for item in self.availableattributeslist_2.findItems(attribute, QtCore.Qt.MatchExactly):
self.availableattributeslist_2.takeItem(self.availableattributeslist_2.row(item))

def update_listcgroupattributes(self):
self.cgroupattributeslist.clear()
self.update_listallattributes()
if self.cgroupslist.currentItem() is not None:
selected_group = str(self.cgroupslist.currentItem().text())
for attributes in self.ansible.getattributesforgroup(selected_group).items():
for attribute in attributes[1]:
QtGui.QListWidgetItem(attribute, self.cgroupattributeslist)
for item in self.availableattributeslist_3.findItems(attribute, QtCore.Qt.MatchExactly):
self.availableattributeslist_3.takeItem(self.availableattributeslist_3.row(item))

def update_listhosts(self):
self.hostslist.clear()
for host in self.ansible.gethosts():
# self.hostslist.addItem(host[0])
QtGui.QListWidgetItem(host, self.hostslist)

def update_listgroups(self):
self.groupslist.clear()
for group in self.ansible.getgroups():
self.groupslist.addItem(group)

def update_listcgroups(self):
self.cgroupslist.clear()
for cgroup in self.ansible.getcgroups():
# self.cgroupslist.addItem(cgroup[0])
QtGui.QListWidgetItem(cgroup, self.cgroupslist)

def update_listattributes(self):
self.attributeslist.clear()
for attribute in self.ansible.gethostsattributes():
# self.attributeslist.addItem(attribute[1].name)
QtGui.QListWidgetItem(attribute, self.attributeslist)
# self.attributeslist.addItem(key+"="+value.value)

def update_listavailablegroups(self):
self.availablegroupslist.clear()
# for group in self.ansible.groups.items():
for group in self.ansible.getgroups():
if group not in specials:
# self.availablegroupslist.addItem(group[0])
QtGui.QListWidgetItem(group, self.availablegroupslist)

def update_listavailablegroups_2(self):
self.availablegroupslist_2.clear()
# for group in self.ansible.groups.items():
for group in self.ansible.getgroups():
if group not in specials:
# self.availablegroupslist.addItem(group[0])
QtGui.QListWidgetItem(group, self.availablegroupslist_2)
for cgroup in self.ansible.getcgroups():
QtGui.QListWidgetItem(cgroup, self.availablegroupslist_2)

def update_listavailablegroups_3(self):
self.availablegroupslist_3.clear()
# for group in self.ansible.groups.items():
for group in self.ansible.getgroups():
if group != ungrouped:
# self.availablegroupslist.addItem(group[0])
QtGui.QListWidgetItem(group, self.availablegroupslist_3)
self.update_listavailablecgroups()

def update_listavailablecgroups(self):
self.availablecgroupslist.clear()
for cgroup in self.ansible.getcgroups():
# self.cgroupslist.addItem(cgroup[0])
QtGui.QListWidgetItem(cgroup, self.availablecgroupslist)

def update_listavailablehosts(self):
self.availablehostslist_2.clear()
# for group in self.ansible.groups.items():
for host in self.ansible.gethosts():
# self.availablehostslist_2.addItem(host[0])
QtGui.QListWidgetItem(host, self.availablehostslist_2)

def update_listavailablehosts_3(self):
self.availablehostslist_3.clear()
# for group in self.ansible.groups.items():
for host in self.ansible.gethosts():
# self.availablehostslist_2.addItem(host[0])
QtGui.QListWidgetItem(host, self.availablehostslist_3)

def update_listavailableattributes(self):
self.availableattributeslist.clear()
for attribute in self.ansible.gethostsattributes():
# self.availableattributeslist.addItem(attribute[1].name)
QtGui.QListWidgetItem(attribute, self.availableattributeslist)

def update_listavailableattributes_2(self):
self.availableattributeslist_2.clear()
for attribute in self.ansible.gethostsattributes():
# self.availableattributeslist.addItem(attribute[1].name)
QtGui.QListWidgetItem(attribute, self.availableattributeslist_2)

def update_listavailableattributes_3(self):
self.availableattributeslist_3.clear()
for attribute in self.ansible.gethostsattributes():
# self.availableattributeslist.addItem(attribute[1].name)
QtGui.QListWidgetItem(attribute, self.availableattributeslist_3)

def add_attribute_to_host(self):
#currenthost = None
for host in self.hostslist.selectedItems():
currenthost = host.text()
for attribute in self.availableattributeslist.selectedItems():
currentattribute = attribute.text()
self.ansible.addattributetohost(currentattribute, currenthost)

def remove_attribute_to_host(self):
for host in self.hostslist.selectedItems():
currenthost = host.text()
for attribute in self.hostattributeslist.selectedItems():
currentattribute = attribute.text()
self.ansible.delattributetohost(currentattribute, currenthost)

def add_attribute_to_group(self):
#currenthost = None
for group in self.groupslist.selectedItems():
currentgroup = group.text()
for attribute in self.availableattributeslist_2.selectedItems():
currentattribute = attribute.text()
self.ansible.addattributetogroup(currentattribute, currentgroup)

def remove_attribute_to_group(self):
for group in self.groupslist.selectedItems():
currentgroup = group.text()
for attribute in self.groupattributeslist.selectedItems():
currentattribute = attribute.text()
self.ansible.delattributetogroup(currentattribute, currentgroup)

def add_host_to_attribute(self):
#currenthost = None
for attribute in self.attributeslist.selectedItems():
currentattribute = attribute.text()
for host in self.availablehostslist_3.selectedItems():
currenthost = host.text()
self.ansible.addattributetohost(currentattribute, currenthost)

def remove_host_to_attribute(self):
for attribute in self.attributeslist.selectedItems():
currentattribute = attribute.text()
for host in self.attributehostslist.selectedItems():
currenthost = host.text()
self.ansible.delattributetohost(currentattribute, currenthost)

def add_group_to_attribute(self):
#currenthost = None
for attribute in self.attributeslist.selectedItems():
currentattribute = attribute.text()
for group in self.availablegroupslist_3.selectedItems():
currentgroup = group.text()
self.ansible.addattributetogroup(currentattribute, currentgroup)

def remove_group_to_attribute(self):
for attribute in self.attributeslist.selectedItems():
currentattribute = attribute.text()
for group in self.attributegroupslist.selectedItems():
currentgroup = group.text()
self.ansible.delattributetogroup(currentattribute, currentgroup)

def add_attribute_to_cgroup(self):
#currenthost = None
for cgroup in self.cgroupslist.selectedItems():
currentcgroup = cgroup.text()
for attribute in self.availableattributeslist_3.selectedItems():
currentattribute = attribute.text()
self.ansible.addattributetocgroup(currentattribute, currentcgroup)

def remove_attribute_to_cgroup(self):
for cgroup in self.cgroupslist.selectedItems():
currentcgroup = cgroup.text()
for attribute in self.cgroupattributeslist.selectedItems():
currentattribute = attribute.text()
self.ansible.delattributetocgroup(currentattribute, currentcgroup)

def add_cgroup_to_attribute(self):
#currenthost = None
for attribute in self.attributeslist.selectedItems():
currentattribute = attribute.text()
for cgroup in self.availablecgroupslist.selectedItems():
currentcgroup = cgroup.text()
self.ansible.addattributetocgroup(currentattribute, currentcgroup)

def remove_cgroup_to_attribute(self):
for attribute in self.attributeslist.selectedItems():
currentattribute = attribute.text()
for cgroup in self.attributecgroupslist.selectedItems():
currentcgroup = cgroup.text()
self.ansible.delattributetocgroup(currentattribute, currentcgroup)

def add_group_to_host(self):
# Read groups in hostgroupslist and add host to the group
#currenthost = None
for host in self.hostslist.selectedItems():
currenthost = host.text()
for group in self.availablegroupslist.selectedItems():
currentgroup = group.text()
self.ansible.addhosttogroup(currenthost, currentgroup)
self.ansible.update_ungroupped()

def remove_group_to_host(self):
for host in self.hostslist.selectedItems():
currenthost = host.text()
for group in self.hostgroupslist.selectedItems():
currentgroup = group.text()
self.ansible.delhosttogroup(currenthost, currentgroup)
self.ansible.update_ungroupped()

def add_group_to_cgroup(self):
# Read groups in hostgroupslist and add host to the group
#currentcgroup = None
for cgroup in self.cgroupslist.selectedItems():
currentcgroup = cgroup.text()
for group in self.availablegroupslist_2.selectedItems():
currentgroup = group.text()
self.ansible.addgrouptocgroup(currentgroup, currentcgroup)

def remove_group_to_cgroup(self):
for cgroup in self.cgroupslist.selectedItems():
currentcgroup = cgroup.text()
for group in self.groupcgroupslist.selectedItems():
currentgroup = group.text()
self.ansible.delgrouptocgroup(currentgroup, currentcgroup)

def add_host_to_group(self,prov):
#print("provenance",prov)
# Read groups in hostgroupslist and add host to the group
#currenthost = None
for group in self.groupslist.selectedItems():
currentgroup = group.text()
for host in self.availablehostslist_2.selectedItems():
currenthost = host.text()
self.ansible.addhosttogroup(currenthost, currentgroup)
self.ansible.update_ungroupped()

def reload_grouphosts(self):
for group in self.groupslist.selectedItems():
currentgroup = group.text()
grouphost = self.ansible.grouphosts.setdefault(currentgroup, [])
grouphost.clear()
for host in self.grouphostslist.getallitems():
self.ansible.addhosttogroup(host.text(), currentgroup)

def reload_cgroupgroups(self):
for cgroup in self.cgroupslist.selectedItems():
currentcgroup = cgroup.text()
cgroupgroup = self.ansible.cgroupgroups.setdefault(currentcgroup, [])
cgroupgroup.clear()
for group in self.groupcgroupslist.getallitems():
self.ansible.addgrouptocgroup(group.text(), currentcgroup)

def remove_host_to_group(self):
for group in self.groupslist.selectedItems():
currentgroup = group.text()
for host in self.grouphostslist.selectedItems():
currenthost = host.text()
self.ansible.delhosttogroup(currenthost, currentgroup)
self.ansible.update_ungroupped()

def update_alllists(self):
self.update_listallhosts()
self.update_listallgroups()
self.update_listallcgroups()
self.update_listallattributes()

def update_liststabhosts(self):
#self.update_listhosts()
self.update_listhostgroups()
self.update_listavailablegroups()
self.update_listhostattributes()
self.update_listavailableattributes()

def update_liststabgroups(self):
#self.update_listgroups()
self.update_listgrouphosts()
self.update_listavailablehosts()
self.update_listgroupattributes()
self.update_listavailableattributes_2()

def update_liststabcgroups(self):
#self.update_listcgroups()
self.update_listcgroupgroups()
self.update_listavailablegroups_2()
self.update_listcgroupattributes()
self.update_listavailableattributes_3()

def update_liststabattributes(self):
#self.update_listattributes()
self.update_listattributehosts()
self.update_listavailablehosts_3()
self.update_listattributegroup()
self.update_listavailablegroups_3()
self.update_listattributecgroup()
self.update_listavailablecgroups()

def update_listallhosts(self):
self.update_listhosts()
self.update_listavailablehosts()

def update_listallgroups(self):
self.update_listgroups()
self.update_listavailablegroups()
self.update_listavailablegroups_2()
self.update_listavailablegroups_3()

def update_listallcgroups(self):
self.update_listavailablecgroups()
self.update_listcgroups()

def update_listallattributes(self):
self.update_listattributes()
self.update_listavailableattributes()
self.update_listavailableattributes_2()
self.update_listavailableattributes_3()

def main(self):
self.show()

if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
imageViewer = ImageViewer()
imageViewer.main()
app.exec_()
(2-2/2)