<commit_before>/*
Copyright 2013 <NAME>, <NAME>, <NAME>

Licensed 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 io.teknek.daemon;

import io.teknek.datalayer.WorkerDao;
import io.teknek.datalayer.WorkerDaoException;
import io.teknek.plan.Plan;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.recipes.lock.WriteLock;

import com.google.common.annotations.VisibleForTesting;

public class TeknekDaemon implements Watcher{

  public static final String ZK_SERVER_LIST = "teknek.zk.servers";
  public static final String MAX_WORKERS = "teknek.max.workers";
  final static Logger logger = Logger.getLogger(TeknekDaemon.class.getName());
  private int maxWorkers = 4;
  private UUID myId;
  private Properties properties;
  private ZooKeeper zk;
  private long rescanMillis = 5000;
  ConcurrentHashMap<Plan, List<Worker>> workerThreads;
  private boolean goOn = true;
  
  public TeknekDaemon(Properties properties){
    
    myId = UUID.randomUUID();
    this.properties = properties;
    workerThreads = new ConcurrentHashMap<Plan,List<Worker>>();
    if (properties.containsKey(MAX_WORKERS)){
      maxWorkers = Integer.parseInt(properties.getProperty(MAX_WORKERS));
    }
  }
  
  public void init() {
    logger.debug("my UUID" + myId);
    System.out.println("connecting to "+properties.getProperty(ZK_SERVER_LIST));
    try {
      zk = new ZooKeeper(properties.getProperty(ZK_SERVER_LIST), 100, this);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        /*
         * Session establishment is asynchronous. This constructor will initiate connection to the server and return immediately - potentially (usually) before the session is fully established. The watcher argument specifies the watcher that will be notified of any changes in state. This notification can come at any point before or after the constructor call has returned. 
         */
        e.printStackTrace();
      }
    } catch (IOException e1) {
      System.out.println("failed connected");
      throw new RuntimeException(e1);
    }
    System.out.println("connected");
    try {

      WorkerDao.createZookeeperBase(zk);
      WorkerDao.createEphemeralNodeForDaemon(zk, this);
    } catch (WorkerDaoException e) {
      throw new RuntimeException(e);
    }
      
    new Thread(){
      public void run(){
        while (goOn){
          try {
            if (workerThreads.size() < maxWorkers) {
              List<String> children = WorkerDao.finalAllPlanNames(zk);
              
              logger.debug("Children found in zk" + children);
              for (String child: children){
                considerStarting(child);
              }
            } else {
              logger.debug("Will not attemt to start worker. Already at max workers "+ workerThreads.size());
            }
           
          } catch (Exception ex){
            logger.error("Exception during scan "+ex);
            ex.printStackTrace();
          }
          try {
            Thread.sleep(rescanMillis);
          } catch (InterruptedException e) {<commit_msg>Sys.out get out<commit_after>/*
Copyright 2013 <NAME>, <NAME>, <NAME>

Licensed 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 io.teknek.daemon;

import io.teknek.datalayer.WorkerDao;
import io.teknek.datalayer.WorkerDaoException;
import io.teknek.plan.Plan;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.recipes.lock.WriteLock;

import com.google.common.annotations.VisibleForTesting;

public class TeknekDaemon implements Watcher{

  public static final String ZK_SERVER_LIST = "teknek.zk.servers";
  public static final String MAX_WORKERS = "teknek.max.workers";
  final static Logger logger = Logger.getLogger(TeknekDaemon.class.getName());
  private int maxWorkers = 4;
  private UUID myId;
  private Properties properties;
  private ZooKeeper zk;
  private long rescanMillis = 5000;
  ConcurrentHashMap<Plan, List<Worker>> workerThreads;
  private boolean goOn = true;
  
  public TeknekDaemon(Properties properties){
    
    myId = UUID.randomUUID();
    this.properties = properties;
    workerThreads = new ConcurrentHashMap<Plan,List<Worker>>();
    if (properties.containsKey(MAX_WORKERS)){
      maxWorkers = Integer.parseInt(properties.getProperty(MAX_WORKERS));
    }
  }
  
  public void init() {
    logger.debug("my UUID" + myId);
    System.out.println("connecting to "+properties.getProperty(ZK_SERVER_LIST));
    try {
      zk = new ZooKeeper(properties.getProperty(ZK_SERVER_LIST), 100, this);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        /*
         * Session establishment is asynchronous. This constructor will initiate connection to the server and return immediately - potentially (usually) before the session is fully established. The watcher argument specifies the watcher that will be notified of any changes in state. This notification can come at any point before or after the constructor call has returned. 
         */
        e.printStackTrace();
      }
    } catch (IOException e1) {
      throw new RuntimeException(e1);
    }
    try {
      WorkerDao.createZookeeperBase(zk);
      WorkerDao.createEphemeralNodeForDaemon(zk, this);
    } catch (WorkerDaoException e) {
      throw new RuntimeException(e);
    }
      
    new Thread(){
      public void run(){
        while (goOn){
          try {
            if (workerThreads.size() < maxWorkers) {
              List<String> children = WorkerDao.finalAllPlanNames(zk);
              logger.debug("Children found in zk" + children);
              for (String child: children){
                considerStarting(child);
              }
            } else {
              logger.debug("Will not attemt to start worker. Already at max workers "+ workerThreads.size());
            }
           
          } catch (Exception ex){
            logger.error("Exception during scan "+ex);
            ex.printStackTrace();
          }
          try {
            Thread.sleep(rescanMillis);
          } catch (InterruptedException e) {
{'fraction_non_alphanumeric': 0.08994708994708994, 'fraction_numerical': 0.005936249838688863, 'mean_word_length': 3.1914548404542997, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 19, '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': '1691784', 'n_tokens_mistral': 2183, 'n_tokens_neox': 2139, 'n_words': 643}