Exemplo n.º 1
0
  /** Initialize SecondaryNameNode. */
  private void initialize(Configuration conf) throws IOException {
    // initiate Java VM metrics
    JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));

    // Create connection to the namenode.
    shouldRun = true;
    nameNodeAddr = NameNode.getAddress(conf);

    this.conf = conf;
    this.namenode =
        (NamenodeProtocol)
            RPC.waitForProxy(
                NamenodeProtocol.class, NamenodeProtocol.versionID, nameNodeAddr, conf);

    // initialize checkpoint directories
    fsName = getInfoServer();
    checkpointDirs = FSImage.getCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary");
    checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf, "/tmp/hadoop/dfs/namesecondary");
    checkpointImage = new CheckpointStorage(conf);
    checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);

    // Initialize other scheduling parameters from the configuration
    checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
    checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);

    // initialize the webserver for uploading files.
    String infoAddr =
        NetUtils.getServerAddress(
            conf,
            "dfs.secondary.info.bindAddress",
            "dfs.secondary.info.port",
            "dfs.secondary.http.address");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    infoBindAddress = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort, tmpInfoPort == 0, conf);
    infoServer.setAttribute("name.system.image", checkpointImage);
    this.infoServer.setAttribute("name.conf", conf);
    infoServer.addInternalServlet("getimage", "/getimage", GetImageServlet.class);
    infoServer.start();

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = infoServer.getPort();
    conf.set("dfs.secondary.http.address", infoBindAddress + ":" + infoPort);
    LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" + infoPort);
    LOG.warn(
        "Checkpoint Period   :"
            + checkpointPeriod
            + " secs "
            + "("
            + checkpointPeriod / 60
            + " min)");
    LOG.warn(
        "Log Size Trigger    :"
            + checkpointSize
            + " bytes "
            + "("
            + checkpointSize / 1024
            + " KB)");
  }
Exemplo n.º 2
0
  private void deleteLocation(LocationInfo info) {
    if (NavigineApp.Navigation == null) return;

    if (info != null) {
      try {
        (new File(info.archiveFile)).delete();
        info.localVersion = -1;
        info.localModified = false;

        String locationDir = LocationLoader.getLocationDir(mContext, info.title);
        File dir = new File(locationDir);
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; ++i) files[i].delete();
        dir.delete();

        String mapFile = NavigineApp.Settings.getString("map_file", "");
        if (mapFile.equals(info.archiveFile)) {
          NavigineApp.Navigation.loadArchive(null);
          SharedPreferences.Editor editor = NavigineApp.Settings.edit();
          editor.putString("map_file", "");
          editor.commit();
        }

        mAdapter.updateList();
      } catch (Throwable e) {
        Log.e(TAG, Log.getStackTraceString(e));
      }
    }
  }
Exemplo n.º 3
0
  /**
   * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by
   * the interface (and its superinterfaces) will be invocable.
   */
  public <T> InAppServer(
      String name,
      String portFilename,
      InetAddress inetAddress,
      Class<T> exportedInterface,
      T handler) {
    this.fullName = name + "Server";
    this.exportedInterface = exportedInterface;
    this.handler = handler;

    // In the absence of authentication, we shouldn't risk starting a server as root.
    if (System.getProperty("user.name").equals("root")) {
      Log.warn(
          "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!");
      return;
    }

    try {
      File portFile = FileUtilities.fileFromString(portFilename);
      secretFile = new File(portFile.getPath() + ".secret");
      Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName);
      // If there are no other threads left, the InApp server shouldn't keep us alive.
      serverThread.setDaemon(true);
      serverThread.start();
    } catch (Throwable th) {
      Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th);
    }
    writeNewSecret();
  }
Exemplo n.º 4
0
 public void run() {
   while (true) {
     LinkedList<PacketCallbackStruct> list = null;
     try {
       queuedPacketCallbacksLock.lock();
       try {
         queuedPacketCallbacksNotEmpty.await();
       } catch (Exception e) {
         Log.error(
             "RDPServer.PacketCallbackThread: queuedPacketCallbacksNotEmpty.await() caught exception "
                 + e.getMessage());
       }
       list = queuedPacketCallbacks;
       queuedPacketCallbacks = new LinkedList<PacketCallbackStruct>();
     } finally {
       queuedPacketCallbacksLock.unlock();
     }
     if (Log.loggingNet)
       Log.net("RDPServer.PacketCallbackThread: Got " + list.size() + " queued packets");
     for (PacketCallbackStruct pcs : list) {
       try {
         callbackProcessPacket(pcs.cb, pcs.con, pcs.packet);
       } catch (Exception e) {
         Log.exception("RDPServer.PacketCallbackThread: ", e);
       }
     }
   }
 }
Exemplo n.º 5
0
  /**
   * there is a socket listening on the port for this packet. process if it is a new connection rdp
   * packet
   */
  public void processNewConnection(RDPServerSocket serverSocket, RDPPacket packet) {
    if (Log.loggingNet)
      Log.net(
          "processNewConnection: RDPPACKET (localport=" + serverSocket.getPort() + "): " + packet);

    //        int localPort = serverSocket.getPort();
    InetAddress remoteAddr = packet.getInetAddress();
    int remotePort = packet.getPort();
    if (!packet.isSyn()) {
      // the client is not attemping to start a new connection
      // send a reset and forget about it
      Log.debug("socket got non-syn packet, replying with reset: packet=" + packet);
      RDPPacket rstPacket = RDPPacket.makeRstPacket();
      rstPacket.setPort(remotePort);
      rstPacket.setInetAddress(remoteAddr);
      RDPServer.sendPacket(serverSocket.getDatagramChannel(), rstPacket);
      return;
    }

    // it is a syn packet, lets make a new connection for it
    RDPConnection con = new RDPConnection();
    DatagramChannel dc = serverSocket.getDatagramChannel();
    con.initConnection(dc, packet);

    // add new connection to allConnectionMap
    registerConnection(con, dc);

    // ack it with a syn
    RDPPacket synPacket = RDPPacket.makeSynPacket(con);
    con.sendPacketImmediate(synPacket, false);
  }
Exemplo n.º 6
0
  /** Create a new checkpoint */
  void doCheckpoint() throws IOException {

    LOG.info("Checkpoint starting");

    // Do the required initialization of the merge work area.
    startCheckpoint();

    // Tell the namenode to start logging transactions in a new edit file
    // Returns a token that would be used to upload the merged image.
    CheckpointSignature sig = (CheckpointSignature) namenode.rollEditLog();

    // error simulation code for junit test
    if (ErrorSimulator.getErrorSimulation(0)) {
      throw new IOException("Simulating error0 " + "after creating edits.new");
    }

    boolean loadImage = downloadCheckpointFiles(sig); // Fetch fsimage and edits
    doMerge(sig, loadImage); // Do the merge

    //
    // Upload the new image into the NameNode. Then tell the Namenode
    // to make this new uploaded image as the most current image.
    //
    putFSImage(sig);

    // error simulation code for junit test
    if (ErrorSimulator.getErrorSimulation(1)) {
      throw new IOException("Simulating error1 " + "after uploading new image to NameNode");
    }

    namenode.rollFsImage(new CheckpointSignature(checkpointImage));
    checkpointImage.endCheckpoint();

    LOG.info("Checkpoint done. New Image Size: " + checkpointImage.getFsImageName().length());
  }
Exemplo n.º 7
0
  /**
   * Download <code>fsimage</code> and <code>edits</code> files from the name-node.
   *
   * @return true if a new image has been downloaded and needs to be loaded
   * @throws IOException
   */
  private boolean downloadCheckpointFiles(CheckpointSignature sig) throws IOException {

    checkpointImage.cTime = sig.cTime;
    checkpointImage.checkpointTime = sig.checkpointTime;

    boolean downloadImage = true;
    String fileid;
    File[] srcNames;
    if (sig.imageDigest.equals(checkpointImage.imageDigest)) {
      downloadImage = false;
      LOG.info("Image has not changed. Will not download image.");
    } else {
      // get fsimage
      srcNames = checkpointImage.getImageFiles();
      assert srcNames.length > 0 : "No checkpoint targets.";
      fileid = "getimage=1";
      TransferFsImage.getFileClient(fsName, fileid, srcNames, false);
      checkpointImage.imageDigest = sig.imageDigest;
      LOG.info(
          "Downloaded file " + srcNames[0].getName() + " size " + srcNames[0].length() + " bytes.");
    }
    // get edits file
    fileid = "getedit=1";
    srcNames = checkpointImage.getEditsFiles();
    assert srcNames.length > 0 : "No checkpoint targets.";
    TransferFsImage.getFileClient(fsName, fileid, srcNames, false);
    LOG.info(
        "Downloaded file " + srcNames[0].getName() + " size " + srcNames[0].length() + " bytes.");

    checkpointImage.checkpointUploadDone(null);

    return downloadImage;
  }
Exemplo n.º 8
0
    public int compareTo(Object arg0) {
      RDPConnectionData other = (RDPConnectionData) arg0;

      if (this.readyTime < other.readyTime) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: readyTime compare -1: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con
                  + ", thisready="
                  + this.readyTime
                  + ", otherReady="
                  + other.readyTime);
        return -1;
      } else if (this.readyTime > other.readyTime) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: readyTime compare 1: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con
                  + ", thisready="
                  + this.readyTime
                  + ", otherReady="
                  + other.readyTime);
        return 1;
      }

      if (this.con == other.con) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: conRef compare 0: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con);
        return 0;
      } else if (this.con.hashCode() < other.con.hashCode()) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: hashCode compare -1: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con);
        return -1;
      } else if (this.con.hashCode() > other.con.hashCode()) {
        if (Log.loggingNet)
          Log.net(
              "RDPServer.RDPConnectionData.compareTo: hashCode compare 1: thiscon="
                  + this.con
                  + ", othercon="
                  + other.con);
        return 1;
      } else {
        throw new RuntimeException("error");
      }
    }
Exemplo n.º 9
0
 /**
  * a DatagramChannel has data ready - process all the pending packets, whether its for a
  * rdpserversocket or rdpconnection.
  */
 void processActiveChannel(DatagramChannel dc) throws ClosedChannelException {
   RDPPacket packet;
   int count = 0;
   // read in the packet
   try {
     Set<RDPConnection> needsAckConnections = new HashSet<RDPConnection>();
     while ((packet = RDPServer.receivePacket(dc)) != null) {
       if (Log.loggingNet)
         Log.net(
             "RDPServer.processActiveChannel: Starting iteration with count of "
                 + count
                 + " packets");
       // see if there is a connection already for this packet
       InetAddress remoteAddr = packet.getInetAddress();
       int remotePort = packet.getPort();
       int localPort = dc.socket().getLocalPort();
       ConnectionInfo conInfo = new ConnectionInfo(remoteAddr, remotePort, localPort);
       RDPConnection con = RDPServer.getConnection(dc, conInfo);
       if (con != null) {
         if (Log.loggingNet)
           Log.net("RDPServer.processActiveChannel: found an existing connection: " + con);
         count++;
         if (processExistingConnection(con, packet)) needsAckConnections.add(con);
         // Prevent this from blocking getActiveChannels by
         // putting an upper bound on the number of packets
         // processed
         if (count >= 20) break;
         continue;
       } else {
         Log.net("RDPServer.processActiveChannel: did not find an existing connection");
       }
       // there is no connection,
       // see if there is a socket listening for new connection
       RDPServerSocket rdpSocket = RDPServer.getRDPSocket(dc);
       if (rdpSocket != null) {
         count++;
         processNewConnection(rdpSocket, packet);
         return;
       }
       return;
     }
     // Finally, send out the acks
     for (RDPConnection con : needsAckConnections) {
       RDPPacket replyPacket = new RDPPacket(con);
       con.sendPacketImmediate(replyPacket, false);
     }
   } catch (ClosedChannelException ex) {
     Log.error("RDPServer.processActiveChannel: ClosedChannel " + dc.socket());
     throw ex;
   } finally {
     if (Log.loggingNet)
       Log.net("RDPServer.processActiveChannel: Returning after processing " + count + " packets");
   }
 }
Exemplo n.º 10
0
 private void parseMapsXml() {
   try {
     String fileName = LocationLoader.getLocationDir(NavigineApp.AppContext, null) + "/maps.xml";
     List<LocationInfo> infoList = Parser.parseMapsXml(NavigineApp.AppContext, fileName);
     mInfoList = new ArrayList<LocationInfo>();
     if (infoList != null) mInfoList = infoList;
     mAdapter.updateList();
     new File(fileName).delete();
   } catch (Throwable e) {
     Log.e(TAG, Log.getStackTraceString(e));
   }
 }
Exemplo n.º 11
0
 public void run() {
   try {
     Log.debug("Trying to configure Clearspace.");
     doConfigClearspace();
     updateClearspaceClientSettings();
   } catch (UnauthorizedException e) {
     Log.warn(
         "Unauthorization problem trying to configure Clearspace, trying again in 1 minute", e);
     // TODO: Mark that there is an authorization problem
   } catch (Exception e) {
     Log.warn("Unknown problem trying to configure Clearspace, trying again in 1 minute", e);
   }
 }
Exemplo n.º 12
0
 /** Shut down this instance of the datanode. Returns only after shutdown is complete. */
 public void shutdown() {
   shouldRun = false;
   try {
     if (infoServer != null) infoServer.stop();
   } catch (Exception e) {
     LOG.warn("Exception shutting down SecondaryNameNode", e);
   }
   try {
     if (checkpointImage != null) checkpointImage.close();
   } catch (IOException e) {
     LOG.warn(StringUtils.stringifyException(e));
   }
 }
Exemplo n.º 13
0
  private synchronized void doConfigClearspace() throws UnauthorizedException {

    Log.debug("Starting Clearspace configuration.");

    List<String> bindInterfaces = getServerInterfaces();
    if (bindInterfaces.size() == 0) {
      // We aren't up and running enough to tell Clearspace what interfaces to bind to.
      Log.debug("No bind interfaces found to config Clearspace");
      throw new IllegalStateException("There are no binding interfaces.");
    }

    try {

      XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo();

      String path = IM_URL_PREFIX + "configureComponent/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("configureComponent");
      Element domainE = rootE.addElement("domain");
      domainE.setText(serverInfo.getXMPPDomain());
      for (String bindInterface : bindInterfaces) {
        Element hostsE = rootE.addElement("hosts");
        hostsE.setText(bindInterface);
      }
      Element portE = rootE.addElement("port");
      portE.setText(String.valueOf(ExternalComponentManager.getServicePort()));

      Log.debug(
          "Trying to configure Clearspace with: Domain: "
              + serverInfo.getXMPPDomain()
              + ", hosts: "
              + bindInterfaces.toString()
              + ", port: "
              + port);

      executeRequest(POST, path, rootE.asXML());

      // Done, Clearspace was configured correctly, clear the task
      Log.debug("Clearspace was configured, stopping the task.");
      TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask);
      configClearspaceTask = null;

    } catch (UnauthorizedException ue) {
      throw ue;
    } catch (Exception e) {
      // It is not supported exception, wrap it into an UnsupportedOperationException
      throw new UnsupportedOperationException("Unexpected error", e);
    }
  }
Exemplo n.º 14
0
  private synchronized void startClearspaceConfig() {
    // If the task is running, stop it
    if (configClearspaceTask != null) {
      configClearspaceTask.cancel();
      Log.debug("Stopping previous configuration Clearspace task.");
    }

    // Create and schedule a confi task every minute
    configClearspaceTask = new ConfigClearspaceTask();
    // Wait some time to start the task until Openfire has binding address
    TaskEngine.getInstance()
        .schedule(configClearspaceTask, JiveConstants.SECOND * 30, JiveConstants.MINUTE);
    Log.debug("Starting configuration Clearspace task in 10 seconds.");
  }
 public int[] readProgress() {
   int progress[] = new int[2];
   try {
     DataInputStream in =
         new DataInputStream(new BufferedInputStream(new FileInputStream(resume_file)));
     progress[0] = in.readInt();
     progress[1] = in.readInt();
     in.close();
   } catch (FileNotFoundException e) {
     Log.e(TAG, "readProgress file not found.");
   } catch (IOException e) {
     Log.e(TAG, e.getMessage());
   }
   return progress;
 }
Exemplo n.º 16
0
  /** Called when the activity is first created */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "LoaderActivity created");
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.content);

    // Instantiate custom adapter
    mAdapter = new LoaderAdapter();

    // Handle listview and assign adapter
    mListView = (ListView) findViewById(R.id.content_list_view);
    mListView.setAdapter(mAdapter);
    mListView.setVisibility(View.GONE);
    mListView.setOnItemLongClickListener(
        new AdapterView.OnItemLongClickListener() {
          public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
            selectItem(position);
            return true;
          }
        });

    mStatusLabel = (TextView) findViewById(R.id.content_status_label);
    mStatusLabel.setVisibility(View.VISIBLE);

    String userHash = NavigineApp.Settings.getString("user_hash", "");
    if (userHash.length() == 0) showUserHashDialog();
    else refreshMapList();
  }
Exemplo n.º 17
0
 private void closeClientSocket() {
   try {
     client.close();
   } catch (IOException ex) {
     Log.warn(Thread.currentThread().getName() + ": failed to close client socket.", ex);
   }
 }
Exemplo n.º 18
0
 private void writeHostAndPortToFile(File portFile) {
   String host = socket.getInetAddress().getHostName();
   int port = socket.getLocalPort();
   // The motivation for the Log.warn would be better satisfied by Bug 38.
   Log.warn("echo " + host + ":" + port + " > " + portFile);
   StringUtilities.writeFile(portFile, host + ":" + port + "\n");
 }
Exemplo n.º 19
0
  private void updateClearspaceSharedSecret(String newSecret) {

    try {
      String path = IM_URL_PREFIX + "updateSharedSecret/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("updateSharedSecret");
      rootE.addElement("newSecret").setText(newSecret);

      executeRequest(POST, path, groupDoc.asXML());
    } catch (UnauthorizedException ue) {
      Log.error("Error updating the password of Clearspace", ue);
    } catch (Exception e) {
      Log.error("Error updating the password of Clearspace", e);
    }
  }
Exemplo n.º 20
0
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
   Log.d(TAG, "Create menu options");
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.loader_menu, menu);
   menu.findItem(R.id.loader_menu_refresh_map_list).setVisible(mLoader < 0);
   return true;
 }
Exemplo n.º 21
0
  @Override
  public void onPause() {
    Log.d(TAG, "LoaderActivity paused");
    super.onPause();

    mTimerTask.cancel();
    mTimerTask = null;
  }
  public synchronized void writeProgress(int current_file, int total_files) {
    try {

      DataOutputStream out =
          new DataOutputStream(new BufferedOutputStream(new FileOutputStream(resume_file, false)));
      out.writeInt(current_file);
      out.writeInt(total_files);
      out.flush();
      out.close();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
      Log.e(TAG, "writeProgress resume.txt not found.");
    } catch (IOException ex) {
      Log.e(TAG, "Unable to create resume.txt.");
    }
  }
Exemplo n.º 23
0
  private void updateLoader() {
    if (NavigineApp.Navigation == null) return;

    // Log.d(TAG, String.format(Locale.ENGLISH, "Update loader: %d", mLoader));

    long timeNow = DateTimeUtils.currentTimeMillis();
    if (mLoader < 0) return;

    int status = LocationLoader.checkLocationLoader(mLoader);
    if (status < 100) {
      if ((Math.abs(timeNow - mLoaderTime) > LOADER_TIMEOUT / 3 && status == 0)
          || (Math.abs(timeNow - mLoaderTime) > LOADER_TIMEOUT)) {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText("Loading timeout!\nPlease, check your internet connection!");
        Log.d(TAG, String.format(Locale.ENGLISH, "Load stopped on timeout!"));
        LocationLoader.stopLocationLoader(mLoader);
        mLoader = -1;
      } else {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText(String.format(Locale.ENGLISH, "Loading content (%d%%)", status));
      }
    } else {
      Log.d(TAG, String.format(Locale.ENGLISH, "Load finished with result: %d", status));
      LocationLoader.stopLocationLoader(mLoader);
      mLoader = -1;

      if (status == 100) {
        parseMapsXml();
        if (mInfoList.isEmpty()) {
          mListView.setVisibility(View.GONE);
          mStatusLabel.setVisibility(View.VISIBLE);
          mStatusLabel.setText("No locations available");
        } else {
          mListView.setVisibility(View.VISIBLE);
          mStatusLabel.setVisibility(View.GONE);
        }
      } else {
        mListView.setVisibility(View.GONE);
        mStatusLabel.setVisibility(View.VISIBLE);
        mStatusLabel.setText("Error loading!\nPlease, check your ID!");
      }
    }
  }
Exemplo n.º 24
0
  /** make sure the packet as the remote address and remote port set */
  static void sendPacket(DatagramChannel dc, RDPPacket packet) {

    sendMeter.add();

    // allocate a buffer
    int bufSize = 100 + (packet.numEacks() * 4);
    if (packet.getData() != null) {
      bufSize += packet.getData().length;
      sendDataMeter.add();
    }
    MVByteBuffer buf = new MVByteBuffer(bufSize);
    packet.toByteBuffer(buf); // function flips the buffer

    int remotePort = packet.getPort();
    InetAddress remoteAddr = packet.getInetAddress();

    if ((remotePort < 0) || (remoteAddr == null)) {
      throw new MVRuntimeException("RDPServer.sendPacket: remotePort or addr is null");
    }

    try {
      int bytes = dc.send(buf.getNioBuf(), new InetSocketAddress(remoteAddr, remotePort));
      if (bytes == 0) {
        Log.error("RDPServer.sendPacket: could not send packet, size=" + bufSize);
      }

      if (Log.loggingNet)
        Log.net(
            "RDPServer.sendPacket: remoteAddr="
                + remoteAddr
                + ", remotePort="
                + remotePort
                + ", numbytes sent="
                + bytes);
    } catch (java.io.IOException e) {
      Log.exception(
          "RDPServer.sendPacket: remoteAddr="
              + remoteAddr
              + ", remotePort="
              + remotePort
              + ", got exception",
          e);
      throw new MVRuntimeException("RDPServer.sendPacket", e);
    }
  }
Exemplo n.º 25
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.mina.core.service.IoHandlerAdapter#sessionClosed(org.apache
   * .mina.core.session.IoSession)
   */
  public void sessionClosed(IoSession session) throws Exception {
    log.info("closed stub: " + session.getRemoteAddress());
    TConn d = (TConn) session.getAttribute("conn");
    if (d != null) {
      d.close();

      session.removeAttribute("conn");
    }
  }
Exemplo n.º 26
0
  /**
   * Instantiates a new MDC server.
   *
   * @param host the host
   * @param port the port
   */
  protected MDCServer(String host, int port) {
    _conf = Config.getConfig();

    address = (host == null) ? new InetSocketAddress(port) : new InetSocketAddress(host, port);

    /** initialize app command */
    Command.init();

    /** initialize the connection center */
    TConnCenter.init(_conf, port);

    synchronized (_conf) {
      /** load public key from database */
      TConn.pub_key = SystemConfig.s("pub_key", null);
      TConn.pri_key = SystemConfig.s("pri_key", null);

      /** initialize the RSA key, hardcode 2048 bits */
      if (TConn.pub_key == null
          || TConn.pri_key == null
          || "".equals(TConn.pub_key)
          || "".equals(TConn.pri_key)) {
        /** print out the old state */
        log.warn(
            "the pub_key or pri_key missed, the old state are pub_key:["
                + TConn.pub_key
                + "], pri_key:["
                + TConn.pri_key
                + "]");

        Key k = RSA.generate(2048);
        TConn.pri_key = k.pri_key;
        TConn.pub_key = k.pub_key;

        /** print out the new public key */
        log.warn("create new RSA key pair, pub_key:[" + TConn.pub_key + ']');

        /** set back in database */
        SystemConfig.setConfig("pri_key", TConn.pri_key);
        SystemConfig.setConfig("pub_key", TConn.pub_key);
      }

      MAX_SIZE = SystemConfig.i("mdc.max_size", MAX_SIZE);
    }
  }
Exemplo n.º 27
0
 private void acceptConnections() {
   for (; ; ) {
     try {
       String handlerName = fullName + "-Handler-" + Thread.activeCount();
       new Thread(new ClientHandler(socket.accept()), handlerName).start();
     } catch (Exception ex) {
       Log.warn(fullName + ": exception accepting connection.", ex);
     }
   }
 }
Exemplo n.º 28
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.mina.core.service.IoHandlerAdapter#sessionCreated(org.apache
   * .mina.core.session.IoSession)
   */
  public void sessionCreated(IoSession session) throws Exception {
    log.info("stub created:" + session.getRemoteAddress());

    Counter.add("mdc", "connection", 1);

    TConn d = new TConn(session);
    d.set("x-forwarded-for", session.getRemoteAddress().toString());

    session.setAttribute("conn", d);
  }
Exemplo n.º 29
0
  //
  // The main work loop
  //
  public void run() {

    //
    // Poll the Namenode (once every 5 minutes) to find the size of the
    // pending edit log.
    //
    long period = 5 * 60; // 5 minutes
    long lastCheckpointTime = 0;
    if (checkpointPeriod < period) {
      period = checkpointPeriod;
    }

    while (shouldRun) {
      try {
        Thread.sleep(1000 * period);
      } catch (InterruptedException ie) {
        // do nothing
      }
      if (!shouldRun) {
        break;
      }
      try {
        long now = System.currentTimeMillis();

        long size = namenode.getEditLogSize();
        if (size >= checkpointSize || now >= lastCheckpointTime + 1000 * checkpointPeriod) {
          doCheckpoint();
          lastCheckpointTime = now;
        }
      } catch (IOException e) {
        LOG.error("Exception in doCheckpoint: ");
        LOG.error(StringUtils.stringifyException(e));
        e.printStackTrace();
        checkpointImage.imageDigest = null;
      } catch (Throwable e) {
        LOG.error("Throwable Exception in doCheckpoint: ");
        LOG.error(StringUtils.stringifyException(e));
        e.printStackTrace();
        Runtime.getRuntime().exit(-1);
      }
    }
  }
Exemplo n.º 30
0
  private void updateClearspaceClientSettings() {
    String xmppBoshSslPort = "0";
    String xmppBoshPort = "0";
    String xmppPort =
        String.valueOf(XMPPServer.getInstance().getConnectionManager().getClientListenerPort());
    if (JiveGlobals.getBooleanProperty(
        HttpBindManager.HTTP_BIND_ENABLED, HttpBindManager.HTTP_BIND_ENABLED_DEFAULT)) {
      int boshSslPort = HttpBindManager.getInstance().getHttpBindSecurePort();
      int boshPort = HttpBindManager.getInstance().getHttpBindUnsecurePort();
      try {
        if (HttpBindManager.getInstance().isHttpsBindActive()
            && LocalClientSession.getTLSPolicy()
                != org.jivesoftware.openfire.Connection.TLSPolicy.disabled) {
          xmppBoshSslPort = String.valueOf(boshSslPort);
        }
      } catch (Exception e) {
        // Exception while working with certificate
        Log.debug(
            "Error while checking SSL certificate.  Instructing Clearspace not to use SSL port.");
      }
      if (HttpBindManager.getInstance().isHttpBindActive() && boshPort > 0) {
        xmppBoshPort = String.valueOf(boshPort);
      }
    }

    try {
      String path = CHAT_URL_PREFIX + "updateClientSettings/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("updateClientSettings");
      rootE.addElement("boshSslPort").setText(xmppBoshSslPort);
      rootE.addElement("boshPort").setText(xmppBoshPort);
      rootE.addElement("tcpPort").setText(xmppPort);

      executeRequest(POST, path, groupDoc.asXML());
    } catch (UnauthorizedException ue) {
      Log.error("Error updating the client settings of Clearspace", ue);
    } catch (Exception e) {
      Log.error("Error updating the client settings of Clearspace", e);
    }
  }