Returns True if the current pod is the first replica in Kubernetes cluster.
438532
def is_first_instance_k8s(current_pod_name=None):
    
    current_pod_name = current_pod_name or os.environ.get('POD_NAME')
    if not current_pod_name:
        raise StackInterrogationException('Pod name not known')

    namespace = 'money-to-prisoners-%s' % settings.ENVIRONMENT
    try:
        load_incluster_config()
    except ConfigException as e:
        raise StackInterrogationException(e)
    try:
        response = k8s_client.CoreV1Api().list_namespaced_pod(
            namespace=namespace,
            label_selector='app=%s' % settings.APP,
            watch=False,
        )
    except ApiException as e:
        raise StackInterrogationException(e)
    pod_names = sorted(pod.metadata.name for pod in filter(lambda pod: pod.status.phase == 'Running', response.items))
    return bool(pod_names and pod_names[0] == current_pod_name)
97873
def get_dump_best_secondary(self, max_repl_lag=None):
        
        secondary_lag_tuples = []

        primary_member = self.get_primary_member()
        if not primary_member:
            raise MongoctlException("Unable to determine primary member for"
                                    " cluster '%s'" % self.id)

        master_status = primary_member.get_server().get_member_rs_status()

        if not master_status:
            raise MongoctlException("Unable to determine replicaset status for"
                                    " primary member '%s'" %
                                    primary_member.get_server().id)

        for member in self.get_members():
            if member.get_server().is_secondary():
                repl_lag = member.get_server().get_repl_lag(master_status)
                if max_repl_lag and  repl_lag > max_repl_lag:
                    log_info("Excluding member '%s' because it's repl lag "
                             "(in seconds)%s is more than max %s. " %
                             (member.get_server().id,
                              repl_lag, max_repl_lag))
                    continue
                secondary_lag_tuples.append((member,repl_lag))

        def best_secondary_comp(x, y):
            x_mem, x_lag = x
            y_mem, y_lag = y
            if x_mem.is_passive():
                if y_mem.is_passive():
                    return x_lag - y_lag
                else:
                    return -1
            elif y_mem.is_passive():
                return 1
            else:
                return x_lag - y_lag

        if secondary_lag_tuples:
            secondary_lag_tuples.sort(best_secondary_comp)
            return secondary_lag_tuples[0][0]
756126
function _doesEventContainsNestedStackId(stack) {
    if (stack.ResourceType !== 'AWS::CloudFormation::Stack') {
        return false;
    }
    if (stack.ResourceStatusReason !== 'Resource creation Initiated') {
        return false;
    }
    if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') {
        return false;
    }
    if (_.isNil(stack.PhysicalResourceId)) {
        return false;
    }

    return _hasLabelNestedStackName(stack.PhysicalResourceId);
}
242460
def is_cluster_ssh_available(cluster_instances, opts):
    
    for i in cluster_instances:
        dns_name = get_dns_name(i, opts.private_ips)
        if not is_ssh_available(host=dns_name, opts=opts):
            return False
    else:
        return True
902245
public final function is_first() {
        $order = get_config($this->get_subtype() . '_' . $this->get_type(), 'sortorder');

        if ($order == 0) {
            return true;
        }
        return false;
    }
696083
protected boolean isHadoopCluster() {
        boolean isHadoopCluster = false;
        try {
            isHadoopCluster = Shell.getHadoopHome() != null;
        } catch (IOException e) {
            // ignore - false is default setting
        }
        return isHadoopCluster;
    }
779845
def remove_first(self):
        

        if self.head is None:
            return False

        self.head = self.head.next_node
        return True
568774
public synchronized boolean startUpgrade() throws IOException {
    if(upgradeState) {  // upgrade is already in progress
      assert currentUpgrades != null : 
        "UpgradeManagerDatanode.currentUpgrades is null.";
      UpgradeObjectDatanode curUO = (UpgradeObjectDatanode)currentUpgrades.first();
      curUO.startUpgrade();
      return true;
    }
    if(broadcastCommand != null) {
      if(broadcastCommand.getVersion() > this.getUpgradeVersion()) {
        // stop broadcasting, the cluster moved on
        // start upgrade for the next version
        broadcastCommand = null;
      } else {
        // the upgrade has been finished by this data-node,
        // but the cluster is still running it, 
        // reply with the broadcast command
        assert currentUpgrades == null : 
          "UpgradeManagerDatanode.currentUpgrades is not null.";
        assert upgradeDaemon == null : 
          "UpgradeManagerDatanode.upgradeDaemon is not null.";
        dataNode.getNSNamenode(namespaceId).processUpgradeCommand(broadcastCommand);
        return true;
      }
    }
    if(currentUpgrades == null)
      currentUpgrades = getDistributedUpgrades();
    if(currentUpgrades == null) {
      DataNode.LOG.info("\n   Distributed upgrade for DataNode version " 
          + getUpgradeVersion() + " to current LV " 
          + FSConstants.LAYOUT_VERSION + " cannot be started. "
          + "The upgrade object is not defined.");
      return false;
    }
    upgradeState = true;
    UpgradeObjectDatanode curUO = (UpgradeObjectDatanode)currentUpgrades.first();
    curUO.setDatanode(dataNode);
    curUO.startUpgrade();
    upgradeDaemon = new Daemon(curUO);
    upgradeDaemon.start();
    DataNode.LOG.info("\n   Distributed upgrade for DataNode " 
        + dataNode.getDatanodeInfo() 
        + " version " + getUpgradeVersion() + " to current LV " 
        + FSConstants.LAYOUT_VERSION + " is started.");
    return true;
  }
1283636
private boolean linkFirst(Node<E> node) {
        // assert lock.isHeldByCurrentThread();
        if (count >= capacity)
            return false;
        Node<E> f = first;
        node.next = f;
        first = node;
        if (last == null)
            last = node;
        else
            f.prev = node;
        ++count;
        notEmpty.signal();
        return true;
    }
1307708
private boolean inWindow(DatanodeDescriptor first, DatanodeDescriptor testing) {

    readLock();
    try {
      RackRingInfo rackInfo = racksMap.get(first.getNetworkLocation());
      assert (rackInfo != null);

      Integer machineId = rackInfo.findNode(first);
      assert (machineId != null);

      final int rackWindowStart = rackInfo.index;

      final RackRingInfo rackTest = racksMap.get(testing.getNetworkLocation());
      assert (rackTest != null);

      final int rackDist = (rackTest.index - rackWindowStart + racks.size())
          % racks.size();

      if (rackDist < rackWindow + 1 && rackTest.index != rackInfo.index) {
        // inside rack window
        final Integer idFirst = rackInfo.findNode(first);
        assert (idFirst != null);

        final int sizeFirstRack = rackInfo.rackNodes.size();
        final int sizeTestRack = rackTest.rackNodes.size();

        final int start = idFirst * sizeTestRack / sizeFirstRack;
        final Integer idTest = rackTest.findNode(testing);
        assert (idTest != null);

        final int dist = (idTest - start + sizeTestRack) % sizeTestRack;

        if (dist < machineWindow) { // inside machine Window
          return true;
        }
      }

      return false;
    } finally {
      readUnlock();
    }
  }
665981
def check(self, instance):
        """"""
        if not self.init_success:
            # Initialization can fail if cgroups are not ready or docker daemon is down. So we retry if needed
            # https://github.com/DataDog/dd-agent/issues/1896
            self.init()

            try:
                if self.docker_util.client is None:
                    message = "Unable to connect to Docker daemon"
                    self.service_check(SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
                                       message=message, tags=self.custom_tags)
                    return
            except Exception as ex:
                self.service_check(SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
                                   message=str(ex), tags=self.custom_tags)
                return

            if not self.init_success:
                # Initialization failed, will try later
                return

        try:
            # Report image metrics
            if self.collect_image_stats:
                self._count_and_weigh_images()

            if Platform.is_k8s():
                self.kube_pod_tags = {}
                if self.kubeutil:
                    try:
                        self.kube_pod_tags = self.kubeutil.get_kube_pod_tags()
                    except Exception as e:
                        self.log.warning('Could not retrieve kubernetes labels: %s' % str(e))

            # containers running with custom cgroups?
            custom_cgroups = _is_affirmative(instance.get('custom_cgroups', False))

            # Get the list of containers and the index of their names
            health_service_checks = True if self.whitelist_patterns else False
            containers_by_id = self._get_and_count_containers(custom_cgroups, health_service_checks)
            containers_by_id = self._crawl_container_pids(containers_by_id, custom_cgroups)

            # Send events from Docker API
            if self.collect_events or self._service_discovery or not self._disable_net_metrics or self.collect_exit_codes:
                self._process_events(containers_by_id)

            # Report performance container metrics (cpu, mem, net, io)
            self._report_performance_metrics(containers_by_id)

            if self.collect_container_size:
                self._report_container_size(containers_by_id)

            if self.collect_container_count:
                self._report_container_count(containers_by_id)

            if self.collect_volume_count:
                self._report_volume_count()

            # Collect disk stats from Docker info command
            if self.collect_disk_stats:
                self._report_disk_stats()

            if health_service_checks:
                self._send_container_healthcheck_sc(containers_by_id)
        except:
            self.log.exception("Docker_daemon check failed")
            self.warning("Check failed. Will retry at next iteration")

        if self.capped_metrics:
            self.filter_capped_metrics()
1291431
def cluster_exists(self, name):
        """"""
        clusters = self.data['clusters']
        for cluster in clusters:
            if cluster['name'] == name:
                return True
        return False
542460
def _create_kubernetes_state_prometheus_instance(self, instance):
        
        ksm_instance = deepcopy(instance)
        endpoint = instance.get('kube_state_url')
        if endpoint is None:
            raise CheckException("Unable to find kube_state_url in config file.")

        extra_labels = ksm_instance.get('label_joins', {})
        hostname_override = is_affirmative(ksm_instance.get('hostname_override', True))

        ksm_instance.update(
            {
                'namespace': 'kubernetes_state',
                'metrics': [
                    {
                        'kube_daemonset_status_current_number_scheduled': 'daemonset.scheduled',
                        'kube_daemonset_status_desired_number_scheduled': 'daemonset.desired',
                        'kube_daemonset_status_number_misscheduled': 'daemonset.misscheduled',
                        'kube_daemonset_status_number_ready': 'daemonset.ready',
                        'kube_daemonset_updated_number_scheduled': 'daemonset.updated',
                        'kube_deployment_spec_paused': 'deployment.paused',
                        'kube_deployment_spec_replicas': 'deployment.replicas_desired',
                        'kube_deployment_spec_strategy_rollingupdate_max_unavailable': 'deployment.rollingupdate.max_unavailable',  # noqa: E501
                        'kube_deployment_status_replicas': 'deployment.replicas',
                        'kube_deployment_status_replicas_available': 'deployment.replicas_available',
                        'kube_deployment_status_replicas_unavailable': 'deployment.replicas_unavailable',
                        'kube_deployment_status_replicas_updated': 'deployment.replicas_updated',
                        'kube_endpoint_address_available': 'endpoint.address_available',
                        'kube_endpoint_address_not_ready': 'endpoint.address_not_ready',
                        'kube_endpoint_created': 'endpoint.created',
                        'kube_hpa_spec_min_replicas': 'hpa.min_replicas',
                        'kube_hpa_spec_max_replicas': 'hpa.max_replicas',
                        'kube_hpa_status_desired_replicas': 'hpa.desired_replicas',
                        'kube_hpa_status_current_replicas': 'hpa.current_replicas',
                        'kube_hpa_status_condition': 'hpa.condition',
                        'kube_node_status_allocatable_cpu_cores': 'node.cpu_allocatable',
                        'kube_node_status_allocatable_memory_bytes': 'node.memory_allocatable',
                        'kube_node_status_allocatable_pods': 'node.pods_allocatable',
                        'kube_node_status_capacity_cpu_cores': 'node.cpu_capacity',
                        'kube_node_status_capacity_memory_bytes': 'node.memory_capacity',
                        'kube_node_status_capacity_pods': 'node.pods_capacity',
                        'kube_node_status_allocatable_nvidia_gpu_cards': 'node.gpu.cards_allocatable',
                        'kube_node_status_capacity_nvidia_gpu_cards': 'node.gpu.cards_capacity',
                        'kube_pod_container_status_terminated': 'container.terminated',
                        'kube_pod_container_status_waiting': 'container.waiting',
                        'kube_persistentvolumeclaim_status_phase': 'persistentvolumeclaim.status',
                        'kube_persistentvolumeclaim_resource_requests_storage_bytes': 'persistentvolumeclaim.request_storage',  # noqa: E501
                        'kube_pod_container_resource_limits_cpu_cores': 'container.cpu_limit',
                        'kube_pod_container_resource_limits_memory_bytes': 'container.memory_limit',
                        'kube_pod_container_resource_requests_cpu_cores': 'container.cpu_requested',
                        'kube_pod_container_resource_requests_memory_bytes': 'container.memory_requested',
                        'kube_pod_container_status_ready': 'container.ready',
                        'kube_pod_container_status_restarts': 'container.restarts',  # up to kube-state-metrics 1.1.x
                        'kube_pod_container_status_restarts_total': 'container.restarts',  # noqa: E501, from kube-state-metrics 1.2.0
                        'kube_pod_container_status_running': 'container.running',
                        'kube_pod_container_resource_requests_nvidia_gpu_devices': 'container.gpu.request',
                        'kube_pod_container_resource_limits_nvidia_gpu_devices': 'container.gpu.limit',
                        'kube_pod_status_ready': 'pod.ready',
                        'kube_pod_status_scheduled': 'pod.scheduled',
                        'kube_poddisruptionbudget_status_current_healthy': 'pdb.pods_healthy',
                        'kube_poddisruptionbudget_status_desired_healthy': 'pdb.pods_desired',
                        'kube_poddisruptionbudget_status_pod_disruptions_allowed': 'pdb.disruptions_allowed',
                        'kube_poddisruptionbudget_status_expected_pods': 'pdb.pods_total',
                        'kube_replicaset_spec_replicas': 'replicaset.replicas_desired',
                        'kube_replicaset_status_fully_labeled_replicas': 'replicaset.fully_labeled_replicas',
                        'kube_replicaset_status_ready_replicas': 'replicaset.replicas_ready',
                        'kube_replicaset_status_replicas': 'replicaset.replicas',
                        'kube_replicationcontroller_spec_replicas': 'replicationcontroller.replicas_desired',
                        'kube_replicationcontroller_status_available_replicas': 'replicationcontroller.replicas_available',  # noqa: E501
                        'kube_replicationcontroller_status_fully_labeled_replicas': 'replicationcontroller.fully_labeled_replicas',  # noqa: E501
                        'kube_replicationcontroller_status_ready_replicas': 'replicationcontroller.replicas_ready',
                        'kube_replicationcontroller_status_replicas': 'replicationcontroller.replicas',
                        'kube_statefulset_replicas': 'statefulset.replicas_desired',
                        'kube_statefulset_status_replicas': 'statefulset.replicas',
                        'kube_statefulset_status_replicas_current': 'statefulset.replicas_current',
                        'kube_statefulset_status_replicas_ready': 'statefulset.replicas_ready',
                        'kube_statefulset_status_replicas_updated': 'statefulset.replicas_updated',
                    }
                ],
                'ignore_metrics': [
                    # _info, _labels and _created don't convey any metric
                    'kube_cronjob_info',
                    'kube_cronjob_created',
                    'kube_daemonset_created',
                    'kube_deployment_created',
                    'kube_deployment_labels',
                    'kube_job_created',
                    'kube_job_info',
                    'kube_limitrange_created',
                    'kube_namespace_created',
                    'kube_namespace_labels',
                    'kube_node_created',
                    'kube_node_info',
                    'kube_node_labels',
                    'kube_pod_created' 'kube_pod_container_info',
                    'kube_pod_info',
                    'kube_pod_owner',
                    'kube_pod_start_time',
                    'kube_pod_labels',
                    'kube_poddisruptionbudget_created',
                    'kube_replicaset_created',
                    'kube_replicationcontroller_created',
                    'kube_resourcequota_created',
                    'kube_replicaset_owner',
                    'kube_service_created',
                    'kube_service_info',
                    'kube_service_labels',
                    'kube_service_spec_external_ip',
                    'kube_service_status_load_balancer_ingress',
                    'kube_statefulset_labels',
                    'kube_statefulset_created',
                    'kube_statefulset_status_current_revision',
                    'kube_statefulset_status_update_revision',
                    # Already provided by the kubelet integration
                    'kube_pod_container_status_last_terminated_reason',
                    # _generation metrics are more metadata than metrics, no real use case for now
                    'kube_daemonset_metadata_generation',
                    'kube_deployment_metadata_generation',
                    'kube_deployment_status_observed_generation',
                    'kube_replicaset_metadata_generation',
                    'kube_replicaset_status_observed_generation',
                    'kube_replicationcontroller_metadata_generation',
                    'kube_replicationcontroller_status_observed_generation',
                    'kube_statefulset_metadata_generation',
                    'kube_statefulset_status_observed_generation',
                    'kube_hpa_metadata_generation',
                    # kube_node_status_phase and kube_namespace_status_phase have no use case as a service check
                    'kube_namespace_status_phase',
                    'kube_node_status_phase',
                    # These CronJob and Job metrics need use cases to determine how do implement
                    'kube_cronjob_status_active',
                    'kube_cronjob_status_last_schedule_time',
                    'kube_cronjob_spec_suspend',
                    'kube_cronjob_spec_starting_deadline_seconds',
                    'kube_job_spec_active_dealine_seconds',
                    'kube_job_spec_completions',
                    'kube_job_spec_parallelism',
                    'kube_job_status_active',
                    'kube_job_status_completion_time',  # We could compute the duration=completion-start as a gauge
                    'kube_job_status_start_time',
                ],
                'label_joins': {
                    'kube_pod_info': {'label_to_match': 'pod', 'labels_to_get': ['node']},
                    'kube_pod_status_phase': {'label_to_match': 'pod', 'labels_to_get': ['phase']},
                    'kube_persistentvolume_info': {
                        'label_to_match': 'persistentvolume',
                        'labels_to_get': ['storageclass'],
                    },
                    'kube_persistentvolumeclaim_info': {
                        'label_to_match': 'persistentvolumeclaim',
                        'labels_to_get': ['storageclass'],
                    },
                },
                # Defaults that were set when kubernetes_state was based on PrometheusCheck
                'send_monotonic_counter': ksm_instance.get('send_monotonic_counter', False),
                'health_service_check': ksm_instance.get('health_service_check', False),
            }
        )

        ksm_instance['prometheus_url'] = endpoint
        ksm_instance['label_joins'].update(extra_labels)
        if hostname_override:
            ksm_instance['label_to_hostname'] = 'node'
            clustername = get_clustername()
            if clustername != "":
                ksm_instance['label_to_hostname_suffix'] = "-" + clustername

        if 'labels_mapper' in ksm_instance and not isinstance(ksm_instance['labels_mapper'], dict):
            self.log.warning("Option labels_mapper should be a dictionary for {}".format(endpoint))

        return ksm_instance
31442
boolean isStale(ServiceNamespace namespace, long[] newVersions, int replicaIndex) {
        return getFragmentVersions(namespace).isStale(newVersions, replicaIndex);
    }
1076829
def _is_daemonset(self, pod=None):
        

        if 'kubernetes.io/created-by' in pod.annotations:
            parent = json.loads(pod.annotations['kubernetes.io/created-by'])
            if parent['reference']['kind'] == 'DaemonSet':
                return True
        return False
1258068
def _is_healthiest_node(self, members, check_replication_lag=True):
        """"""

        _, my_wal_position = self.state_handler.timeline_wal_position()
        if check_replication_lag and self.is_lagging(my_wal_position):
            logger.info('My wal position exceeds maximum replication lag')
            return False  # Too far behind last reported wal position on master

        if not self.is_standby_cluster() and self.check_timeline():
            cluster_timeline = self.cluster.timeline
            my_timeline = self.state_handler.replica_cached_timeline(cluster_timeline)
            if my_timeline < cluster_timeline:
                logger.info('My timeline %s is behind last known cluster timeline %s', my_timeline, cluster_timeline)
                return False

        # Prepare list of nodes to run check against
        members = [m for m in members if m.name != self.state_handler.name and not m.nofailover and m.api_url]

        if members:
            for st in self.fetch_nodes_statuses(members):
                if st.failover_limitation() is None:
                    if not st.in_recovery:
                        logger.warning('Master (%s) is still alive', st.member.name)
                        return False
                    if my_wal_position < st.wal_position:
                        logger.info('Wal position of %s is ahead of my wal position', st.member.name)
                        return False
        return True
121594
function getClusterVersion(request, mCb) {
			delete request.project;
			v1Container().projects.zones.getServerconfig(request, function (err, response) {
				if (err) {
					return mCb(err);
				}
				let version;
				if (response && response.validMasterVersions && Array.isArray(response.validMasterVersions)
					&& response.validMasterVersions.length > 0) {
					response.validMasterVersions.forEach(function (oneVersion) {
						if (oneVersion.substring(0, 3) === "1.7") {
							version = oneVersion;
							options.soajs.log.debug("Initial Cluster version set to :", version);
						}
					});
					
				} else if (response && response.defaultClusterVersion && !version) {
					version = response.defaultClusterVersion;
					options.soajs.log.debug("Initial Cluster version set to default version :", version);
				} else {
					return mCb({"code": 410, "msg": "Invalid or no kubernetes cluster version found!"})
				}
				return mCb(null, version);
			});
		}