def update_active_tasks(self):
    # Add all active tasks
    self.metric_sources = []
    for service_name, service in self.collector_config.services.iteritems():
      # Save to database.
      # The active field has the default value True.
      service_record, created = Service.objects.get_or_create(
          name=service_name,
          defaults={"metric_url":service.metric_url})
      if not created:
        # Mark it as active if it exists.
        service_record.active = True
        service_record.save()

      for cluster_name, cluster in service.clusters.iteritems():
        cluster_record, created = Cluster.objects.get_or_create(
            service=service_record, name=cluster_name)
        if not created:
          cluster_record.active = True
          cluster_record.save()

        for job_name in service.jobs:
          job_record, created = Job.objects.get_or_create(
              cluster=cluster_record, name=job_name)
          if not created:
            job_record.active = True
            job_record.save()

          job = cluster.jobs[job_name]
          # We assume http port is always base_port + 1
          port = job.base_port + 1
          # support multiple instances
          hosts = job.hosts
          for host_id, host in hosts.iteritems():
            host_name = job.hostnames[host_id]
            for instance_id in range(host.instance_num):
              task_id = deploy_utils.get_task_id(hosts, host_id, instance_id)
              instance_port = deploy_utils.get_base_port(port,instance_id)
              task_record, created = Task.objects.get_or_create(
                job=job_record, task_id=task_id,
                defaults={"host":host_name, "port":instance_port})
              if not created or task_record.host != host_name or (
                task_record.port != instance_port):
                task_record.active = True
                task_record.host = host_name
                task_record.port = instance_port
                task_record.save()
              self.metric_sources.append(
                MetricSource(self.collector_config, task_record))
dataset/ETHPy150Open XiaoMi/minos/owl/collector/management/commands/collect.py/Command.update_active_tasks/original