public synchronized void logUnavailableHost(URL url) {
    if (this.offlineMode) return;

    if (url == null) {
      String message = Logging.getMessage("nullValue.URLIsNull");
      Logging.error(message);
      throw new IllegalArgumentException(message);
    }

    String hostName = url.getHost();
    HostInfo hi = this.hostMap.get(hostName);
    if (hi != null) {
      if (!hi.isUnavailable()) {
        hi.logCount.incrementAndGet();
        if (hi.isUnavailable()) // host just became unavailable
        this.firePropertyChange(NetworkStatus.HOST_UNAVAILABLE, null, url);
      }
      hi.lastLogTime.set(System.currentTimeMillis());
    } else {
      hi = new HostInfo(this.attemptLimit.get(), this.tryAgainInterval.get());
      hi.logCount.set(1);
      if (hi.isUnavailable()) // the attempt limit may be as low as 1, so handle that case here
      this.firePropertyChange(NetworkStatus.HOST_UNAVAILABLE, null, url);
      this.hostMap.put(hostName, hi);
    }

    this.lastUnavailableLogTime.set(System.currentTimeMillis());
  }
 public void configHostName() throws IOException {
   expect.sendLine("echo '' > /etc/hosts");
   ready(ROOT_USER);
   for (HostInfo info : BuildEnv.ALL_HOST) {
     expect.sendLine("echo '" + info.getIp() + " " + info.getHostName() + "' >> /etc/hosts");
     ready(ROOT_USER);
   }
 }
 /**
  * Whether the host should ignore the domain resource
  *
  * @param domainResource the root domain resource
  * @param the address to check
  * @return {@code true} if we are to ignore the resource
  */
 @Override
 public boolean ignoreResource(Resource domainResource, PathAddress address) {
   if (address.size() != 1) {
     return false;
   }
   if (hostInfo.isIgnoreUnaffectedConfig()) {
     if (knownRootAddresses != null
         && address.size() >= 0
         && knownRootAddresses.contains(address.getElement(0))) {
       return false;
     }
     return util.ignoreResource(domainResource, hostInfo.getServerConfigInfos(), address);
   }
   return false;
 }
  private List<HostInfo> generateFakeDomain() {
    String[] hostNames = new String[] {"lightning", "eeak-a-mouse", "dirty-harry"};
    String[] groupNames =
        new String[] {
          "staging",
          "production",
          "messaging-back-server-test",
          "uat",
          "messaging",
          "backoffice",
          "starlight"
        };

    int numHosts = 13;
    final List<HostInfo> hostInfos = new ArrayList<HostInfo>();

    for (int i = 0; i < numHosts; i++) {
      // host info
      String name = hostNames[Random.nextInt(2)] + "-" + i;
      boolean isController = (i < 1);

      HostInfo host = new HostInfo(name, isController);
      host.setServerInstances(new ArrayList<ServerInstance>());

      // server instances
      for (int x = 0; x < (Random.nextInt(5) + 1); x++) {
        int groupIndex = Random.nextInt(groupNames.length - 1);
        ServerInstance serverInstance = beanFactory.serverInstance().as();
        serverInstance.setGroup(groupNames[groupIndex]);
        serverInstance.setRunning((groupIndex % 2 == 0));
        if (serverInstance.isRunning()) {
          if (Random.nextBoolean()) {
            serverInstance.setFlag(Random.nextBoolean() ? RESTART_REQUIRED : RELOAD_REQUIRED);
          } else {
            serverInstance.setFlag(null);
          }
        }
        serverInstance.setName(groupNames[groupIndex] + "-" + x);
        serverInstance.setSocketBindings(Collections.<String, String>emptyMap());
        serverInstance.setInterfaces(Collections.<String, String>emptyMap());

        host.getServerInstances().add(serverInstance);
      }
      hostInfos.add(host);
    }
    return hostInfos;
  }
 public void configSSH(String user) throws IOException {
   System.out.println("~~~~~~~~~~~~~configSSH  start~~~~~~~~~~~~~~");
   this.expect.sendLine("ssh-keygen -t rsa -P \"\" -f ~/.ssh/id_rsa");
   ready(user);
   this.expect.sendLine("cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys");
   ready(user);
   this.expect.sendLine("\\cp -f /vagrant/src/main/resources/ssh/config ~/.ssh");
   ready(user);
   for (HostInfo hi : otherHostInfo) {
     String copyId = "ssh-copy-id -i ~/.ssh/id_rsa.pub " + user + "@" + hi.getHostName();
     this.expect.sendLine(copyId);
     ready(user);
   }
   this.expect.sendLine("chmod 700 -R ~/.ssh");
   ready(user);
   System.out.println("~~~~~~~~~~~~~configSSH  成功~~~~~~~~~~~~~~");
 }
 /** Builds {@link ServerGroup} instances and populates the map {@link #serverGroups} */
 private SortedSet<ServerGroup> deriveGroups(List<HostInfo> hosts) {
   serverGroups.clear();
   for (HostInfo host : hosts) {
     List<ServerInstance> serverInstances = host.getServerInstances();
     for (ServerInstance server : serverInstances) {
       String group = server.getGroup();
       String profile = server.getProfile();
       ServerGroup serverGroup = serverGroups.get(group);
       if (serverGroup == null) {
         serverGroup = new ServerGroup(group, profile);
         serverGroup.fill(hosts);
         serverGroups.put(group, serverGroup);
       }
     }
   }
   return new TreeSet<ServerGroup>(serverGroups.values());
 }
 private void init() {
   otherHostInfo = getOtherHostInfo();
   JSch jSch = new JSch();
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   try {
     session = jSch.getSession(hostInfo.getUser(), hostInfo.getIp(), hostInfo.getPort());
     session.setConfig(config);
     session.setPassword(hostInfo.getPassword());
     session.connect(5000);
     System.out.println(hostInfo.getIp() + "已连接...");
     channel = session.openChannel("shell");
     channel.connect();
     expect =
         new ExpectBuilder()
             .withOutput(channel.getOutputStream())
             .withInputs(channel.getInputStream(), channel.getExtInputStream())
             .withEchoInput(System.out)
             .withEchoOutput(System.err)
             .withInputFilters(removeColors(), removeNonPrintable())
             .withExceptionOnFailure()
             .withTimeout(80000, TimeUnit.SECONDS)
             .withAutoFlushEcho(true)
             .withCombineInputs(true)
             .build();
     System.out.println(expect.getClass().getName());
   } catch (JSchException | IOException e) {
     e.printStackTrace();
     destroy();
     throw new RuntimeException("无法连接" + hostInfo.getIp() + ":" + hostInfo.getPort());
   }
 }
 public void copyConfig(boolean isFirst) throws IOException, TemplateException {
   genServerConfFile();
   expect.sendLine(
       "\\cp -f /vagrant/src/main/resources/template/server.cnf."
           + hostInfo.getHostName()
           + " /etc/my.cnf.d/server.cnf");
   ready(ROOT_USER);
   if (isFirst) {
     configMariaDBFirst();
   }
 }
  public boolean isHostUnavailable(URL url) {
    if (this.offlineMode) return true;

    if (url == null) {
      String message = Logging.getMessage("nullValue.URLIsNull");
      Logging.error(message);
      throw new IllegalArgumentException(message);
    }

    String hostName = url.getHost();
    HostInfo hi = this.hostMap.get(hostName);
    if (hi == null) return false;

    if (hi.isTimeToTryAgain()) {
      hi.logCount.set(0); // info removed from table in logAvailableHost
      return false;
    }

    return hi.isUnavailable();
  }
  public synchronized void connect(HostInfo host, long connectionVersion) throws Throwable {
    try {
      log.debug("Trying to connect");
      this.setConnectionVersion(connectionVersion);
      this.hostInfo = host;
      client = new Socket();

      client.setReceiveBufferSize(256 * 1024);
      client.setReceiveBufferSize(256 * 1024);
      client.setSoLinger(true, 2);

      client.connect(new InetSocketAddress(host.getHostname(), host.getPort()), 15 * 1000);
      rawOutput = new DataOutputStream(getSocket().getOutputStream());
      rawInput = new DataInputStream(getSocket().getInputStream());
      socketAddress = getSocket().getRemoteSocketAddress();
      socketAddressLiteral = socketAddress.toString();
      log.debug("Connection established: " + socketAddressLiteral);
      closed = false;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
  public void genServerConfFile() throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
    cfg.setClassForTemplateLoading(this.getClass(), "/");
    Template template = cfg.getTemplate("template/galera_server.ftl");

    // Build the data-model
    Map<String, Object> data = new HashMap<>();
    data.put("ownHostInfo", hostInfo);
    data.put("otherHostInfos", otherHostInfo);
    // Console output
    String path = getClass().getClassLoader().getResource("").getFile();
    FileWriter out = new FileWriter(path + "/template/server.cnf." + hostInfo.getHostName());
    template.process(data, out);
    out.flush();
    out.close();
  }
 private void ready(String user) throws IOException {
   expect.expect(contains(user + "@" + hostInfo.getHostName()));
   System.out.flush();
 }
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    PrintWriter out = resp.getWriter();

    String json = req.getParameter("json");
    String key = req.getParameter("key");

    String retval = new String();
    DBProc dbProc = new DBProc();

    ProfileProperties prop = dbProc.verifyProfileKey(key);

    if (prop == null) {
      out.print("Profile Key " + key + " was not Verified");
      out.flush();
      out.close();
      return;
    }

    if (!prop.ispEnabled()) {
      out.print("Profile Key " + key + " is not Enabled");
      out.flush();
      out.close();
      return;
    }

    if (!prop.isPgr_sp()) {
      out.print("ShortestPath Searches for this Profile is not enabled");
      out.flush();
      out.close();
      return;
    }

    if (!prop.ispPublic()) {
      if (!HostInfo.checkHostInfo(req.getRemoteHost(), prop.getHosts())) {
        if (!HostInfo.checkHostInfo(req.getRemoteAddr(), prop.getHosts())) {
          out.print("Not authorized to use this Service[ " + req.getRemoteAddr() + " ]");
          out.flush();
          out.close();
          return;
        }
      }
    }

    if (json == null) {
      out.print("No JSON Request Parameter");
      out.flush();
      out.close();
      return;
    }

    try {
      JSONObject jo = new JSONObject(json);
      String proj = jo.getString("projection");
      String source = jo.getJSONArray("points").getString(0);
      String target = jo.getJSONArray("points").getString(1);

      int epsg = Integer.parseInt(proj.split(":")[1]);

      if (epsg != RouteProperties.getSrid()) {
        source = dbProc.transformPoint(source, epsg);
        target = dbProc.transformPoint(target, epsg);
      }

      retval = dbProc.findShortestPath(prop.getId(), source, target, prop.isReverse_cost());
    } catch (Exception ex) {
      retval = "Error has occured";
      ex.printStackTrace();
    }

    resp.setContentType("application/json");

    out.print(retval);
    out.flush();
    out.close();
  }
 /**
  * Whether the slave host is set up to ignore unaffected config
  *
  * @return {@code true} if the slave is set up to ignore unaffected config
  */
 boolean isIgnoreUnaffactedConfig() {
   return hostInfo.isIgnoreUnaffectedConfig();
 }
 /**
  * Add/update a server config info
  *
  * @param serverInfo the server config info
  */
 void updateSlaveServerConfig(ServerConfigInfo serverInfo) {
   if (hostInfo.isIgnoreUnaffectedConfig()) {
     hostInfo.updateSlaveServerConfigInfo(serverInfo);
   }
 }