Esempio n. 1
0
    def run(self):
        time.sleep(self.post_start)
        vm_properties = ["name", "config.guestFullName"]
        while True:
            try:
                self.logger.debug("Checking Windows VM coherency group.")
                if self.connect():
                    self.logger.debug("Connected to vCenter: {}.".format(
                        self.host))
                    cm = ClusterManager(si=self.si, content=self.content)
                    all_vc_vms = self.get_all_vms()
                    all_clusters = self.get_all_clusters()
                    # now it becomes fun...
                    vm_data = self.collect_properties(
                        view_ref=all_vc_vms,
                        obj_type=vim.VirtualMachine,
                        path_set=vm_properties,
                        include_mors=True)

                    # map cluster data into a dictionary
                    clusters = {}
                    for cluster in all_clusters.view:
                        clusters[cluster.name] = {}
                        clusters[cluster.name]['obj'] = cluster
                        windows_vm_group = filter(
                            lambda x: isinstance(x, vim.cluster.VmGroup) and x.
                            name == self.vm_group_name,
                            cluster.configurationEx.group)
                        vm_list = []
                        if len(windows_vm_group) > 0 and isinstance(
                                windows_vm_group[0], vim.cluster.VmGroup):
                            # check if there are VM inside the vm group
                            if len(windows_vm_group[0].vm) > 0:
                                vm_list = map(lambda x: x.name,
                                              windows_vm_group[0].vm)
                        clusters[cluster.name]['windows.vm.group'] = vm_list

                    self.logger.debug("Start iterating VMs...")
                    try:
                        filtered_vm_list = filter(
                            lambda x: self.pattern in x['config.guestFullName']
                            .lower(), vm_data)
                    except KeyError:
                        # probably running during VM creation. continue the cycle with empty vm list.
                        self.logger.error(
                            "KeyError: 'config.guestFullName', continue.")
                        filtered_vm_list = []
                    finally:
                        for vm in filtered_vm_list:
                            cluster_name = vm['obj'].resourcePool.owner.name
                            if vm['name'] not in clusters[cluster_name][
                                    'windows.vm.group']:
                                self.logger.info(
                                    "VM: {} in cluster: {} is not in the VmGroup. Adding it."
                                    .format(vm['name'], cluster_name))
                                # more defensive here... sorry bro.
                                _vmgroup = cm.get_vm_group_by_name(
                                    name=self.vm_group_name,
                                    cluster=clusters[cluster_name]['obj'])
                                if len(_vmgroup) <= 0:
                                    cm.create_vm_group(
                                        clusters[cluster_name]['obj'])
                                _hostgroup = cm.get_host_group_by_name(
                                    name=self.host_group_name,
                                    cluster=clusters[cluster_name]['obj'])
                                if len(_hostgroup) <= 0:
                                    cm.create_host_group(
                                        clusters[cluster_name]['obj'])

                                if not cm.check_avail_res(
                                        vm['obj'],
                                        clusters[cluster_name]['obj']):
                                    if not cm.add_host_to_host_group(
                                            cluster=clusters[cluster_name]
                                        ['obj']):
                                        self.logger.critical(
                                            "Failed to expand HostGroup. Skipping VM add."
                                        )
                                        continue
                                cm.add_vm_to_vm_group(
                                    vm['obj'], clusters[cluster_name]['obj'])
                else:
                    self.logger.critical(
                        "Cannot connect to vcenter: {}.".format(self.host))
                self.logger.debug("Windows VM coherency check complete.")
                self.disconnect()
            except Exception as exc:
                self.logger.error(exc, exc_info=True)
            if self.stopped.wait(self.wait_time):
                self.logger.debug("Break reached.")
                break
Esempio n. 2
0
    def run(self):
        time.sleep(self.post_start)
        vm_properties = ["name", "config.guestFullName"]
        while True:
            try:
                self.logger.debug("Checking Windows VM coherency group.")
                if self.connect():
                    self.logger.debug("Connected to vCenter: {}.".format(self.host))
                    cm = ClusterManager(si=self.si, content=self.content)
                    all_vc_vms = self.get_all_vms()
                    all_clusters = self.get_all_clusters()
                    # now it becomes fun...
                    vm_data = self.collect_properties(view_ref=all_vc_vms,
                                                      obj_type=vim.VirtualMachine,
                                                      path_set=vm_properties,
                                                      include_mors=True)

                    # map cluster data into a dictionary
                    clusters = {}
                    for cluster in all_clusters.view:
                        clusters[cluster.name] = {}
                        clusters[cluster.name]['obj'] = cluster
                        windows_vm_group = filter(
                            lambda x: isinstance(x, vim.cluster.VmGroup) and x.name == self.vm_group_name,
                            cluster.configurationEx.group
                        )
                        vm_list = []
                        if len(windows_vm_group) > 0 and isinstance(windows_vm_group[0], vim.cluster.VmGroup):
                            # check if there are VM inside the vm group
                            if len(windows_vm_group[0].vm) > 0:
                                vm_list = map(lambda x: x.name, windows_vm_group[0].vm)
                        clusters[cluster.name]['windows.vm.group'] = vm_list

                    self.logger.debug("Start iterating VMs...")
                    try:
                        filtered_vm_list = filter(lambda x: self.pattern in x['config.guestFullName'].lower(), vm_data)
                    except KeyError:
                        # probably running during VM creation. continue the cycle with empty vm list.
                        self.logger.error("KeyError: 'config.guestFullName', continue.")
                        filtered_vm_list = []
                    finally:
                        for vm in filtered_vm_list:
                            cluster_name = vm['obj'].resourcePool.owner.name
                            if vm['name'] not in clusters[cluster_name]['windows.vm.group']:
                                self.logger.info("VM: {} in cluster: {} is not in the VmGroup. Adding it.".format(
                                    vm['name'], cluster_name
                                ))
                                # more defensive here... sorry bro.
                                _vmgroup = cm.get_vm_group_by_name(name=self.vm_group_name,
                                                                   cluster=clusters[cluster_name]['obj'])
                                if len(_vmgroup) <= 0:
                                    cm.create_vm_group(clusters[cluster_name]['obj'])
                                _hostgroup = cm.get_host_group_by_name(name=self.host_group_name,
                                                                       cluster=clusters[cluster_name]['obj'])
                                if len(_hostgroup) <= 0:
                                    cm.create_host_group(clusters[cluster_name]['obj'])

                                if not cm.check_avail_res(vm['obj'], clusters[cluster_name]['obj']):
                                    if not cm.add_host_to_host_group(cluster=clusters[cluster_name]['obj']):
                                        self.logger.critical("Failed to expand HostGroup. Skipping VM add.")
                                        continue
                                cm.add_vm_to_vm_group(vm['obj'], clusters[cluster_name]['obj'])
                else:
                    self.logger.critical("Cannot connect to vcenter: {}.".format(self.host))
                self.logger.debug("Windows VM coherency check complete.")
                self.disconnect()
            except Exception as exc:
                self.logger.error(exc, exc_info=True)
            if self.stopped.wait(self.wait_time):
                self.logger.debug("Break reached.")
                break
Esempio n. 3
0
    def run(self):
        while not self.stop:
            try:
                vm = self.executor_queue.get(timeout=10)
            except Queue.Empty:
                continue
            self.logger.info("Received VM from Reactioneer: {}".format(vm.name))
            self.logger.debug('Instancing Cluster Manager.')
            self.connect()
            cm = ClusterManager(self.si, self.content)
            cluster = vm.resourcePool.owner

            self.logger.debug('Identified cluster: {}'.format(cluster.name))

            try:
                # check if the HostGroup exists.
                self.logger.debug("Checking if HostGroup: {} exists.".format(self.host_group_name))
                host_group = cm.get_host_group_by_name(name=self.host_group_name, cluster=cluster)
                if len(host_group) <= 0:
                    # the HostGroup doesnt exists, create it.
                    self.logger.debug("Creating HostGroup: {}.".format(self.host_group_name))
                    cm.create_host_group(cluster)
                else:
                    if not isinstance(host_group[0], vim.cluster.HostGroup):
                        cm.create_host_group(cluster)

                # check if the HostGroup has not enough resources to contain the new VM, in that case add another
                # host to the group.
                try:
                    self.logger.debug('Checking if there is enough power with the current number of hosts...')
                    if not cm.check_avail_res(vm, cluster):
                        # the HostGroup doesn't have enough resources. Add another host to it.
                        self.logger.debug("Adding a new Host to the HostGroup: {}.".format(self.host_group_name))
                        cm.add_host_to_host_group(cluster)
                except HostGroupNotExists:
                    raise

                # check if the VmGroup exists.
                self.logger.debug("Checking if VmGroup: {} exists".format(self.vm_group_name))
                vm_group = cm.get_vm_group_by_name(self.vm_group_name, cluster)
                if len(vm_group) <= 0:
                    # the VmGroup doesn't exists, create it.
                    self.logger.debug("VmGroup: {} doesn't exists. Creating it.".format(self.vm_group_name))
                    cm.create_vm_group(cluster)
                else:
                    if not isinstance(vm_group[0], vim.cluster.VmGroup):
                        self.logger.debug("VmGroup: {} doesn't exists. Creating it.".format(self.vm_group_name))
                        cm.create_vm_group(cluster)

                # finally add the VM to the VmGroup
                self.logger.debug("Adding VM: {} to VmGroup: {}.".format(vm.name, self.vm_group_name))
                if not cm.add_vm_to_vm_group(vm, cluster):
                    self.logger.critical("Failed to add VM: {} to VmGroup: {}".format(vm.name, self.vm_group_name))
                    # TODO: raise a Nagios alarm.

                if self.create_affinity_rule == '1':
                    # check if the affinity rule exists or not
                    if not cm.get_affinity_rule_by_name(self.windows_affinity_rule_name, cluster):
                        self.logger.info("The affinity rule: {} doesn't exists.".format(
                            self.windows_affinity_rule_name
                        ))
                        self.logger.info("Creating affinity rule: {}.".format(self.windows_affinity_rule_name))
                        cm.add_affinity_rule(cluster)
                else:
                    self.logger.info("Affinity rule not checked according to config.")

            except HostGroupNotExists:
                # TODO: raise a Nagios alarm
                self.logger.critical("Failed to handle HostGroup: {}. Aborting.".format(self.host_group_name))
                self.executor_queue.task_done()
            except VmGroupNotExists:
                # TODO: raise a Nagios alarm
                self.logger.critical("Failed to handle VmGroup: {}. Aborting".format(self.vm_group_name))
                self.executor_queue.task_done()

            self.executor_queue.task_done()
            self.logger.info('VM: {} finally processed correctly.\n\n'.format(vm.name))