<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.kafka.trogdor.coordinator;

import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.kafka.common.utils.Exit;
import org.apache.kafka.common.utils.KafkaThread;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.trogdor.common.Node;
import org.apache.kafka.trogdor.common.Platform;
import org.apache.kafka.trogdor.fault.Fault;
import org.apache.kafka.trogdor.fault.FaultSet;
import org.apache.kafka.trogdor.fault.FaultSpec;
import org.apache.kafka.trogdor.fault.FaultState;
import org.apache.kafka.trogdor.rest.CoordinatorFaultsResponse;
import org.apache.kafka.trogdor.rest.CreateCoordinatorFaultRequest;
import org.apache.kafka.trogdor.rest.JsonRestServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static net.sourceforge.argparse4j.impl.Arguments.store;

/**
 * The Trogdor coordinator.
 *
 * The coordinator manages the agent processes in the cluster. 
 */
public final class Coordinator {
    private static final Logger log = LoggerFactory.getLogger(Coordinator.class);

    /**
     * The clock to use for this coordinator.
     */
    private final Time time;

    /**
     * The start time in milliseconds.
     */
    private final long startTimeMs;

    /**
     * The platform.
     */
    private final Platform platform;

    /**
     * NodeManager objects for each node in the cluster.
     */
    private final Map<String, NodeManager> nodeManagers;

    /**
     * The lock protecting shutdown and faultQueue.
     */
    private final ReentrantLock lock = new ReentrantLock();

    /**
     * The condition variable which the coordinator thread waits on.
     */
    private final Condition cond = lock.newCondition();

    /**
     * The coordinator runnable.
     */
    private final CoordinatorRunnable runnable;

    /**
     * The REST server.
     */
    private final JsonRestServer restServer;

    /**
     * The coordinator thread.
     */
    private final KafkaThread thread;

    /**
     * True if the server is shutting down.
     */
    private boolean shutdown = false;

    /**
     * The set of faults which have been scheduled.
     */
    private final FaultSet pendingFaults = new FaultSet();

    /**
     * The set of faults which have been sent to the agents.
     */
    private final FaultSet doneFaults = new FaultSet();

    class CoordinatorRunnable implements Runnable {
        @Override
        public void run() {
            log.info("Starting main service thread.");
            try {
                long nextWakeMs = 0;
                while (true) {
                    long now = time.milliseconds();
                    List<Fault> toStart = new ArrayList<>();
                    lock.lock();
                    try {
                        if (nextWakeMs > now) {
                            if (cond.await(nextWakeMs - now, TimeUnit.MILLISECONDS)) {
                                log.trace("CoordinatorRunnable woke up early.");
                            }
                        }
                        nextWakeMs = now + (60L * 60L * 1000L);
                        if (shutdown) {
                            log.info("CoordinatorRunnable shutting down.");
                            return;
                        }
                        Iterator<Fault> iter = pendingFaults.iterateByStart();
                        while (iter.hasNext()) {
                            Fault fault = iter.next();
                            if (now < fault.spec().startMs()) {
                                nextWakeMs = Math.min(nextWakeMs, fault.spec().startMs());
                                break;
                            }
                            toStart.add(fault);
                            iter.remove();
                            doneFaults.add(fault);
                        }
                    } finally {
                        lock.unlock();
                    }<commit_msg>KAFKA-5806; Fix transient unit test failure in trogdor coordinator shutdown<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.kafka.trogdor.coordinator;

import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.kafka.common.utils.Exit;
import org.apache.kafka.common.utils.KafkaThread;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.trogdor.common.Node;
import org.apache.kafka.trogdor.common.Platform;
import org.apache.kafka.trogdor.fault.Fault;
import org.apache.kafka.trogdor.fault.FaultSet;
import org.apache.kafka.trogdor.fault.FaultSpec;
import org.apache.kafka.trogdor.fault.FaultState;
import org.apache.kafka.trogdor.rest.CoordinatorFaultsResponse;
import org.apache.kafka.trogdor.rest.CreateCoordinatorFaultRequest;
import org.apache.kafka.trogdor.rest.JsonRestServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import static net.sourceforge.argparse4j.impl.Arguments.store;

/**
 * The Trogdor coordinator.
 *
 * The coordinator manages the agent processes in the cluster. 
 */
public final class Coordinator {
    private static final Logger log = LoggerFactory.getLogger(Coordinator.class);

    /**
     * The clock to use for this coordinator.
     */
    private final Time time;

    /**
     * The start time in milliseconds.
     */
    private final long startTimeMs;

    /**
     * The platform.
     */
    private final Platform platform;

    /**
     * NodeManager objects for each node in the cluster.
     */
    private final Map<String, NodeManager> nodeManagers;

    /**
     * The lock protecting shutdown and faultQueue.
     */
    private final ReentrantLock lock = new ReentrantLock();

    /**
     * The condition variable which the coordinator thread waits on.
     */
    private final Condition cond = lock.newCondition();

    /**
     * The coordinator runnable.
     */
    private final CoordinatorRunnable runnable;

    /**
     * The REST server.
     */
    private final JsonRestServer restServer;

    /**
     * The coordinator thread.
     */
    private final KafkaThread thread;

    /**
     * True if the server is shutting down.
     */
    private boolean shutdown = false;

    /**
     * The set of faults which have been scheduled.
     */
    private final FaultSet pendingFaults = new FaultSet();

    /**
     * The set of faults which have been sent to the agents.
     */
    private final FaultSet doneFaults = new FaultSet();

    class CoordinatorRunnable implements Runnable {
        @Override
        public void run() {
            log.info("Starting main service thread.");
            try {
                long nextWakeMs = 0;
                while (true) {
                    long now = time.milliseconds();
                    List<Fault> toStart = new ArrayList<>();
                    lock.lock();
                    try {
                        if (shutdown) {
                            break;
                        }
                        if (nextWakeMs > now) {
                            if (cond.await(nextWakeMs - now, TimeUnit.MILLISECONDS)) {
                                log.trace("CoordinatorRunnable woke up early.");
                            }
                            now = time.milliseconds();
                            if (shutdown) {
                                break;
                            }
                        }
                        nextWakeMs = now + (60L * 60L * 1000L);
                        Iterator<Fault> iter = pendingFaults.iterateByStart();
                        while (iter.hasNext()) {
                            Fault fault = iter.next();
                            if (now < fault.spec().startMs()) {
                                nextWakeMs = Math.min(nextWakeMs, fault.spec().startMs());
                                break;
                            }
                            toStart.add(fault);
                            iter.remove();
                            doneFaults.add(fault);
                        }
                    } finally {
                        lock.unlock();
                    }
{'fraction_non_alphanumeric': 0.08788245140890914, 'fraction_numerical': 0.004091881335441272, 'mean_word_length': 1.999721059972106, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4629146', 'n_tokens_mistral': 2961, 'n_tokens_neox': 2776, 'n_words': 805}