Ejemplo n.º 1
0
def request_filter(hours, no_verify, f_type=FILTER_TASKS, duration=None):

    logger = logging.getLogger('request.filter')

    # Disable certificate verification if needed.
    if no_verify:
        requests.packages.urllib3.disable_warnings()
        ssl._create_default_https_context = ssl._create_unverified_context
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE

    # Build the filter spec.
    if FILTER_TASKS == f_type:
        time_filter = vim.TaskFilterSpec.ByTime()
    elif FILTER_EVENTS == f_type:
        time_filter = vim.event.EventFilterSpec.ByTime()
    now = datetime.now()
    time_filter.timeType = vim.TaskFilterSpec.TimeOption.startedTime
    time_filter.beginTime = now - timedelta(hours=hours)
    if duration:
        time_filter.endTime = time_filter.beginTime + timedelta(hours=duration)
    else:
        time_filter.endTime = now
    if FILTER_TASKS == f_type:
        filter_spec = vim.TaskFilterSpec(time=time_filter)
    elif FILTER_EVENTS == f_type:
        filter_spec = vim.event.EventFilterSpec(time=time_filter)

    return filter_spec
Ejemplo n.º 2
0
def get_task_entity(content, moid=None):
    if not moid:
        return
    containerContent = content.taskManager
    tasks = containerContent.CreateCollectorForTasks(vim.TaskFilterSpec())
    tasks.ResetCollector()
    all_tasks = tasks.ReadNextTasks(999)
    tasks = []
    for task in all_tasks:
        tasks.append(task.key)
        if task.key == moid:
            results = {
                'task_id': str(task.key),
                'entity_name': str(task.entityName),
                'task_description_id': str(task.descriptionId),
                'task_state': str(task.state),
                'task_result': str(task.result)
            }
            if task.entity:
                entity = str(task.entity).strip("'")
                vimType, extId = entity.split(':')
                results.update({
                    'entity': str(entity),
                    'vim_type': vimType,
                    'ext_id': extId
                })
            if task.error:
                results.update({'error_message': str(task.error.msg)})
        elif moid not in tasks:
            results = {'task_id': moid, 'error_message': 'Task not found.'}

    return results
Ejemplo n.º 3
0
    def _get_task_collector(self):
        # set filter to get TaskInfo which is queued in the vSphere after executing this Sensor
        time_filter = vim.TaskFilterSpec.ByTime()
        time_filter.timeType = vim.TaskFilterSpec.TimeOption.queuedTime
        time_filter.beginTime = datetime.now()

        filter_spec = vim.TaskFilterSpec(time=time_filter)

        try:
            return self.si_content.taskManager.CreateCollectorForTasks(filter=filter_spec)
        except Exception as e:
            self._log.error(e)
Ejemplo n.º 4
0
def main():
    """
    Simple command-line program for listing tasks .
    """

    args = get_args()
    try:
        service_instance = None
        ssl._create_default_https_context = ssl._create_unverified_context
        try:
            service_instance = connect.SmartConnect(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=int(args.port)
           )
        except IOError as e_x:
            pass
        if not service_instance:
            print "Could not connect to the specified host" \
					"uservice_instanceng given credentials \
					%s %s  %s %s " %(args.host, args.user, args.password, args.port)
            return -1

        atexit.register(connect.Disconnect, service_instance)
        content = service_instance.RetrieveContent()
        task_manager = content.taskManager
        spec_byuser = vim.TaskFilterSpec.ByUsername(userList=args.user)
        tasks = task_manager.CreateCollectorForTasks\
				(vim.TaskFilterSpec(userName=spec_byuser))
        tasks.ResetCollector()
        alltasks = tasks.ReadNextTasks(999)
        yesterday = datetime.now() - timedelta(1) # Get yesterday's time
        eastern = pytz.timezone('US/Eastern')
        for task in alltasks:
            if task.startTime > eastern.localize(yesterday):
                print str(task.startTime) + ' ' + task.entityName + \
								 ' ' + task.state + ' ' + task.descriptionId
        print 'Destroying collector'
        tasks.DestroyCollector()

    except vmodl.MethodFault as e_x:
        print "Caught vmodl fault : " + e_x.msg
        return -1
    except Exception as e_x:
        print "Caught exception : " + str(e_x)
        return -1

    return 0
Ejemplo n.º 5
0
 def get_task_history(self, vm):
     """
     50% dead code.. might be replaced by overall_tasks()
     """
     taskManager = self.si.content.taskManager
     filterspec = vim.TaskFilterSpec()
     filterspec.entity = vim.TaskFilterSpec.ByEntity(entity=vm,recursion='all')
     try:
         collector = taskManager.CreateCollectorForTasks(filterspec)
     except:
         log.debug("Could not instantiate collector. retrying..")
         return [], []
     prev_tasks = collector.ReadPrev(4)
     next_tasks = collector.ReadNext(4)
     return prev_tasks, next_tasks
Ejemplo n.º 6
0
 def get_task(self, id):
     result = []
     taskManager = self.SI.content.taskManager
     tasks = taskManager.CreateCollectorForTasks(vim.TaskFilterSpec(eventChainId=[int(id)]))
     tasks.ResetCollector()
     try:
         alltasks = tasks.ReadNextTasks(999)
     except Exception as exc:
         raise vCenterException(exc)
     else:
         for task_item in alltasks:
             try:
                 item = self.format_task(task_item)
                 result.append(item)
             except Exception as exc:
                 raise vCenterException(exc)
         tasks.DestroyCollector()
     return result
Ejemplo n.º 7
0
 def list_running_task(self):
     result = []
     taskManager = self.SI.content.taskManager
     tasks = taskManager.CreateCollectorForTasks(vim.TaskFilterSpec(state='running'))
     tasks.ResetCollector()
     try:
         alltasks = tasks.ReadNextTasks(999)
     except Exception as exc:
         raise vCenterException(exc)
     else:
         for task_item in alltasks:
             try:
                 item = self.format_task(task_item)
                 result.append(item)
             except Exception as exc:
                 raise vCenterException(exc)
         tasks.DestroyCollector()
     return result
Ejemplo n.º 8
0
def checkTask(vmn, content):
    taskManager = content.taskManager
    specByuser = vim.TaskFilterSpec()
    specByuser.entity = vim.TaskFilterSpec.ByEntity(entity=vmn,
                                                    recursion='all')
    #print (specByuser.entity)
    tasks = taskManager.CreateCollectorForTasks(specByuser)

    #print(tasks)
    tasks.ResetCollector()
    alltasks = tasks.ReadNextTasks(10)[0]

    #print (alltasks.completeTime)
    #print(alltasks)

    if alltasks.completeTime != None:
        print("This server is not busy.")
        busybee = False
    else:
        #print("This server is busy.")
        busybee = True

    return busybee
#!/bin/env python
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import ssl

context = ssl._create_unverified_context()

si = SmartConnect(host="ホスト名/IPアドレス",
                  user="******",
                  pwd="パスワード",
                  port=443,
                  sslContext=context)

content = si.RetrieveContent()

taskFilterSpec = vim.TaskFilterSpec()
eventFilterSpec = vim.event.EventFilterSpec()
task_controller = content.taskManager.CreateCollectorForTasks(
    filter=taskFilterSpec)
event_controller = content.eventManager.CreateCollectorForEvents(
    filter=eventFilterSpec)
task_list = task_controller.latestPage
event_list = event_controller.latestPage

print("-------Task List-------")
for task in task_list:
    print("Task Name: %s" % task.name)
    print("Status: %s" % task.state)
    print("Entity: %s" % task.entityName)
    print("Date: %s" % task.completeTime)