from celery.task.control import inspect


def get_resource_bag_task(res_id):
    i = inspect()
    active_jobs = i.active()
    reserved_jobs = i.reserved()
    scheduled_jobs = i.scheduled()
    if active_jobs:
        workers = active_jobs.keys()
        for worker in workers:
            for job in active_jobs[worker]:
                if job['name'] == 'hs_core.tasks.create_bag_by_irods':
                    if res_id in job['args']:
                        return job['id']
    if reserved_jobs:
        workers = reserved_jobs.keys()
        for worker in workers:
            for job in reserved_jobs[worker]:
                if job['name'] == 'hs_core.tasks.create_bag_by_irods':
                    if res_id in job['args']:
                        return job['id']
    if scheduled_jobs:
        workers = scheduled_jobs.keys()
        for worker in workers:
            for job in scheduled_jobs[worker]:
                if job['name'] == 'hs_core.tasks.create_bag_by_irods':
                    if res_id in job['args']:
                        return job['id']
    return None

@@ -43,172 +43,105 @@
 def 
-get_resource_bag_task(res_id):%0A    i = inspect()%0A    active_jobs = i.active()%0A    reserved_jobs = i.reserved()%0A    scheduled_jobs = i.scheduled()%0A    if active_jobs
+_retrieve_job_id(res_id, job_dict, job_name='hs_core.tasks.create_bag_by_irods'):%0A    if job_dict
 :%0A  
@@ -156,27 +156,24 @@
 rkers = 
-active_jobs
+job_dict
 .keys()%0A
@@ -230,19 +230,16 @@
  in 
-active_jobs
+job_dict
 %5Bwor
@@ -282,43 +282,16 @@
  == 
-'hs_core.tasks.create_bag_by_irods'
+job_name
 :%0A  
@@ -383,361 +383,266 @@
     
-if reserved_jobs:%0A        workers = reserved_jobs.keys()%0A        for worker in workers:%0A            for job in reser
+return None%0A%0A%0Adef get_resource_bag_task(res_id):%0A    i = inspect()%0A    acti
 ve
-d
 _jobs
-%5Bworker%5D:%0A             
+ = i.active()%0A
    
-if
  job
-%5B'name'%5D == 'hs_core.tasks.create_bag_by_irods':%0A                    if res_id in job%5B'args'%5D:%0A                        return job%5B'id'%5D%0A    if scheduled_jobs:%0A        workers = schedul
+_id = _retrieve_job_id(res_id, active_jobs)%0A    if not job_id:%0A        reserved_jobs = i.reserved()%0A        job_id = _retrieve_job_id(res_id, reserv
 ed_jobs
-.keys(
 )%0A  
@@ -647,37 +647,29 @@
         
-for worker in workers
+if not job_id
 :%0A      
@@ -674,27 +674,16 @@
         
-for job in 
 schedule
@@ -688,31 +688,33 @@
 led_jobs
-%5Bworker%5D:%0A     
+ = i.scheduled()%0A
         
@@ -720,162 +720,74 @@
     
-if
  job
-%5B'name'%5D == 'hs_core.tasks.create_bag_by_irods':%0A                    if res_id in job%5B'args'%5D:%0A                        return job%5B'id'%5D%0A    return None
+_id = _retrieve_job_id(res_id, scheduled_jobs)%0A%0A    return job_id
 %0A

address code review