/** {@inheritDoc} */
  protected void getNewMonitors(Map<String, Monitor> map) throws MonitorException {
    assert Thread.holdsLock(this);

    int used = prologue.getUsed();
    long modificationTime = prologue.getModificationTimeStamp();

    if ((used > lastUsed) || (lastModificationTime > modificationTime)) {

      lastUsed = used;
      lastModificationTime = modificationTime;

      Monitor monitor = getNextMonitorEntry();
      while (monitor != null) {
        String name = monitor.getName();

        // guard against duplicate entries
        if (!map.containsKey(name)) {
          map.put(name, monitor);

          /*
           * insertedMonitors is null when called from pollFor()
           * via buildMonitorMap(). Since we update insertedMonitors
           * at the end of buildMonitorMap(), it's ok to skip the
           * add here.
           */
          if (insertedMonitors != null) {
            insertedMonitors.add(monitor);
          }
        }
        monitor = getNextMonitorEntry();
      }
    }
  }
示例#2
0
  public void destroy() {
    try {
      server_mon.enter();

      Iterator it = rendezvous_bindings.values().iterator();

      while (it.hasNext()) {

        Object[] entry = (Object[]) it.next();

        final DHTTransportUDPContact contact = (DHTTransportUDPContact) entry[0];

        new AEThread2("DHTNATPuncher:destroy", true) {
          public void run() {
            sendClose(contact);
          }
        }.start();
      }
    } catch (Throwable e) {

      log(e);

    } finally {

      server_mon.exit();
    }
  }
示例#3
0
    /** PENDING javadocs */
    public void run() {

      assert (monitors != null);
      boolean reloaded = false;
      for (Iterator<Monitor> i = monitors.iterator(); i.hasNext(); ) {
        Monitor m = i.next();
        try {
          if (m.hasBeenModified()) {
            if (!reloaded) {
              reloaded = true;
            }
          }
        } catch (IOException ioe) {
          if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.severe(
                "Unable to access url "
                    + m.uri.toString()
                    + ".  Monitoring for this resource will no longer occur.");
          }
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, ioe.toString(), ioe);
          }
          i.remove();
        }
      }
      if (reloaded) {
        reload(sc);
      }
    }
  /**
   * Read one node with the given ID from the database.
   *
   * @param nodeID ID of the node in the database
   * @param networkID ID of the network
   * @return Node
   */
  public Node read(long nodeID, long networkID) throws DatabaseException {
    Node node;
    String nodeIdStr = "node.{id=" + nodeID + ", network_id=" + networkID + "}";

    long timeBegin = System.nanoTime();

    try {
      dbr.transactionBegin();
      Monitor.debug("Node reader transaction beginning on " + nodeIdStr);

      node = readWithAssociates(nodeID, networkID);

      dbr.transactionCommit();
      Monitor.debug("Node reader transaction committing on " + nodeIdStr);
    } catch (DatabaseException dbExc) {
      Monitor.err(dbExc);
      throw dbExc;
    } finally {
      try {
        dbr.transactionRollback();
        Monitor.debug("Node reader transaction rollback on " + nodeIdStr);
      } catch (Exception Exc) {
        // Do nothing.
      }
    }

    long timeCommit = System.nanoTime();
    if (node != null) {
      Monitor.duration("Read " + nodeIdStr, timeCommit - timeBegin);
    }

    return node;
  }
示例#5
0
 public void updateMonitor(com.dragonflow.SiteView.J2EEMonitor j2eemonitor) {
   java.lang.String s = (java.lang.String) j2eemonitor.getUniqueID();
   Monitor monitor = (Monitor) activeMonitors.get(s);
   if (monitor == null) {
     return;
   }
   java.util.Set set = j2eemonitor.getCounters();
   int i = j2eemonitor.getInterval();
   boolean flag = false;
   synchronized (monitor) {
     if (!set.equals(monitor.getCounters())) {
       monitor.setCounters(set);
       calcCounterUnion();
       flag = true;
     }
     if (i != monitor.getInterval()) {
       monitor.setInterval(i);
       calcInterval();
       flag = true;
     }
   }
   if (flag) {
     getMetricData(true);
   }
 }
示例#6
0
 /**
  * @param monitorgroup
  * @param portalsiteview
  */
 void processGroup(MonitorGroup monitorgroup, PortalSiteView portalsiteview) {
   boolean flag = visitor.groupPre(monitorgroup, portalsiteview);
   if (flag) {
     if (addAlerts) {
       Array array = monitorgroup.getElementsOfClass("COM.dragonflow.SiteView.Rule", false, false);
       Rule rule;
       for (Enumeration enumeration1 = array.elements();
           enumeration1.hasMoreElements();
           processAlert(rule, null, monitorgroup, portalsiteview)) {
         rule = (Rule) enumeration1.nextElement();
       }
     }
     Enumeration enumeration = monitorgroup.getMonitors();
     while (enumeration.hasMoreElements()) {
       Monitor monitor = (Monitor) enumeration.nextElement();
       if (itemFilter.itemAllowed(monitor.getFullID()) && itemFilter.monitorAllowed(monitor)) {
         if (debug) {
           Monitor _tmp = monitor;
           TextUtils.debugPrint("process monitor: " + monitor.getProperty(Monitor.pName));
         }
         processMonitor(monitor, monitorgroup, portalsiteview);
       }
     }
   }
   visitor.groupPost(monitorgroup, portalsiteview);
 }
示例#7
0
 @Override
 public void onDestroy() {
   // Unregister observers
   for (Monitor monitor : monitors) {
     monitor.terminate();
   }
 }
示例#8
0
文件: TObject.java 项目: leobm/teavm
  @Sync
  static void monitorExit(final TObject o, int count) {
    if (o.isEmptyMonitor() || o.monitor.owner != TThread.currentThread()) {
      throw new TIllegalMonitorStateException();
    }
    o.monitor.count -= count;
    if (o.monitor.count > 0) {
      return;
    }

    o.monitor.owner = null;
    if (!o.monitor.enteringThreads.isEmpty()) {
      Platform.postpone(
          () -> {
            if (o.isEmptyMonitor() || o.monitor.owner != null) {
              return;
            }
            if (!o.monitor.enteringThreads.isEmpty()) {
              o.monitor.enteringThreads.remove().run();
            }
          });
    } else {
      o.isEmptyMonitor();
    }
  }
 @Override
 public void reset() {
   super.reset();
   m_phi.reset();
   m_mons = new LinkedList<ValuePair>();
   m_variableResolver = new HashMap<String, String>();
 }
示例#10
0
  protected void receiveTunnelInbound(DHTTransportUDPContact originator, Map data) {
    log("Received tunnel inbound message from " + originator.getString());

    try {
      punch_mon.enter();

      for (int i = 0; i < oustanding_punches.size(); i++) {

        Object[] wait_data = (Object[]) oustanding_punches.get(i);

        DHTTransportContact wait_contact = (DHTTransportContact) wait_data[0];

        if (originator.getAddress().getAddress().equals(wait_contact.getAddress().getAddress())) {

          wait_data[2] = new Integer(originator.getTransportAddress().getPort());

          ((AESemaphore) wait_data[1]).release();
        }
      }

    } finally {

      punch_mon.exit();
    }
  }
  /** Read all PeMS data in the given time range at the given VDS. */
  public PeMSProfile read(Interval interval, Long vdsId) throws DatabaseException {
    PeMSProfile profile;
    String pemsIdStr = "pems.{vds_id=" + vdsId + ", interval=" + interval + "}";

    long timeBegin = System.nanoTime();

    try {
      dbr.transactionBegin();
      Monitor.debug("PeMS reader transaction beginning on " + pemsIdStr);

      profile = readProfile(interval, vdsId);

      dbr.transactionCommit();
      Monitor.debug("PeMS reader transaction committing on " + pemsIdStr);
    } catch (DatabaseException dbExc) {
      Monitor.err(dbExc);
      throw dbExc;
    } finally {
      try {
        dbr.transactionRollback();
        Monitor.debug("PeMS reader transaction rollback on " + pemsIdStr);
      } catch (Exception Exc) {
        // Do nothing.
      }
    }

    long timeCommit = System.nanoTime();
    if (profile != null) {
      Monitor.duration("Read " + pemsIdStr, timeCommit - timeBegin);
    }

    return profile;
  }
示例#12
0
  /**
   * This method starts the arbitration of behaviours and runs an endless loop. <br>
   * Note: Arbitrator does not run in a separate thread. The start() method will never return unless
   * <br>
   * 1. no action() method is running and <br>
   * 2. no behaviour takeControl() returns <B> true </B> and <br>
   * 3. the <i>returnWhenInacative </i> flag is true,
   */
  public void start() {
    //	  int i =0;
    monitor.start();

    while (_highestPriority == NONE) {
      Thread.yield(); // wait for some behaviour to take contro
    }
    while (true) {
      synchronized (monitor) {
        if (_highestPriority != NONE) {
          _active = _highestPriority;

        } else if (_returnWhenInactive) { // no behaviour wants to run
          monitor.more = false; // 9 shut down monitor thread
          return;
        }
      }

      // monotor released before action is called
      if (_active != NONE) // _highestPrioirty could be NONE
      {
        visCall = 0;
        _behaviour[_active].action();
        _active = NONE; // no active behaviour at the moment
      }
      Thread.yield();
      // i++;
      // System.out.println("i " + i);
      // if (i==10) return;
    }
  }
示例#13
0
  /**
   * El metodo recibe un String que corresponde con la entrada del cliente. Se encarga de las
   * negociaciones con el cliente, en las que ovtiene tiempo y peso de la imagen a mostrar en la
   * ventana, devuelve la propuesta de la hora de muestra de su imagen
   *
   * @param inputLine
   * @return
   * @throws IOException
   */
  private String negociacionInicial(String inputLine, long t) throws IOException {
    // El cliente quiere iniciar la negociación con el servidor
    String salida = null;
    int peso = -1;
    int tiempo = -1;

    // Leemos los datos que nos envía
    try {
      Scanner lectura = new Scanner(inputLine);
      lectura.next(); // Peso
      lectura.next(); // de
      lectura.next(); // la
      lectura.next(); // imagen:
      peso = lectura.nextInt();
      lectura.next(); // Tiempo:
      tiempo = lectura.nextInt();
      lectura.close();
    } catch (Exception er) {
      salida = "ERROR: Mensaje ilegible.";
    }
    if (salida == null) { // Si no ha habido error
      nodo.setPesoImagen(peso);
      nodo.setTiempo(tiempo);

      // Tiempo de conexion y negociacion con el Socket
      long tfinal = System.currentTimeMillis() - t;
      tfinal = monitor.getT() + tfinal;

      monitor.setT(tfinal);
      // Nos ponemos en contacto con el gestor del servicio (monitor)
      salida = monitor.negociacion(nodo);
    }

    return salida;
  }
示例#14
0
 @Override
 public void remove(PnfsId id) {
   Monitor monitor = _entries.get(id);
   if (monitor != null) {
     monitor.remove();
   }
 }
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    JAtomicResourceSession atomicResourceSession =
        JAtomicResourceSessionHolder.getAtomicResourceSession();
    Monitor.get().in();
    Throwable throwable = null;
    Object object = null;
    try {
      object = method.invoke(target, args);
    } catch (Exception e) {
      logger.error(target.getClass().getName() + "(proxy) invoke encounter exception : ", e);
      throwable = e;
      throw e;
    } finally {
      if (throwable != null) {
        atomicResourceSession.rollback();
        Monitor.remove();
        JAtomicResourceSessionHolder.release();
      }

      if (Monitor.get().out()) {
        atomicResourceSession.commit();
        Monitor.remove();
        JAtomicResourceSessionHolder.release();
      }
    }
    return object;
  }
示例#16
0
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
   super.onStartCommand(intent, flags, startId);
   Monitor monitor = new Monitor();
   monitor.start();
   return START_STICKY;
 }
示例#17
0
    /** set a new channel whose limits we wish to monitor */
    public void setChannel(final Channel channel) {
      synchronized (this) {
        if (_lowerChannel != null) {
          _lowerChannel.removeConnectionListener(this);
          if (_lowerMonitor != null) {
            _lowerMonitor.clear();
            _lowerMonitor = null;
          }
        }

        final String lowerLimitPV = channel.channelName() + ".LOPR";
        _lowerChannel = ChannelFactory.defaultFactory().getChannel(lowerLimitPV);
        _lowerChannel.addConnectionListener(this);
        _lowerChannel.requestConnection();

        if (_upperChannel != null) {
          _upperChannel.removeConnectionListener(this);
          if (_upperMonitor != null) {
            _upperMonitor.clear();
            _upperMonitor = null;
          }
        }

        final String upperLimitPV = channel.channelName() + ".HOPR";
        _upperChannel = ChannelFactory.defaultFactory().getChannel(upperLimitPV);
        _upperChannel.addConnectionListener(this);
        _upperChannel.requestConnection();
      }
    }
示例#18
0
 ImmutableMap<Service, Long> startupTimes() {
   List<Entry<Service, Long>> loadTimes;
   monitor.enter();
   try {
     loadTimes = Lists.newArrayListWithCapacity(startupTimers.size());
     // N.B. There will only be an entry in the map if the service has started
     for (Entry<Service, Stopwatch> entry : startupTimers.entrySet()) {
       Service service = entry.getKey();
       Stopwatch stopWatch = entry.getValue();
       if (!stopWatch.isRunning() && !(service instanceof NoOpService)) {
         loadTimes.add(Maps.immutableEntry(service, stopWatch.elapsed(MILLISECONDS)));
       }
     }
   } finally {
     monitor.leave();
   }
   Collections.sort(
       loadTimes,
       Ordering.<Long>natural()
           .onResultOf(
               new Function<Entry<Service, Long>, Long>() {
                 @Override
                 public Long apply(Map.Entry<Service, Long> input) {
                   return input.getValue();
                 }
               }));
   ImmutableMap.Builder<Service, Long> builder = ImmutableMap.builder();
   for (Entry<Service, Long> entry : loadTimes) {
     builder.put(entry);
   }
   return builder.build();
 }
示例#19
0
 private synchronized void calcInterval() {
   int i = 0x7fffffff;
   int j = 0x80000000;
   synchronized (activeMonitors) {
     java.util.Iterator iterator = activeMonitors.values().iterator();
     while (iterator.hasNext()) {
       Monitor monitor = (Monitor) iterator.next();
       int k = monitor.getInterval();
       if (k < i) {
         i = k;
       }
       if (k > j) {
         j = k;
       }
     }
   }
   if (i != minInterval.intValue()) {
     synchronized (minInterval) {
       minInterval = new Integer(i);
       if (getMetricDataTimer != null) {
         getMetricDataTimer.cancel();
       }
       if (activeMonitors.size() != 0) {
         getMetricDataTimer = new Timer(true);
         getMetricDataTimer.scheduleAtFixedRate(
             new GetMetricDataTask(this), (i * 1000) / 4, (i * 1000) / 2);
       }
     }
   }
   if (j != maxInterval.intValue()) {
     synchronized (maxInterval) {
       maxInterval = new Integer(j);
     }
   }
 }
示例#20
0
 void awaitHealthy() {
   monitor.enterWhenUninterruptibly(awaitHealthGuard);
   try {
     checkHealthy();
   } finally {
     monitor.leave();
   }
 }
示例#21
0
 @Override
 public void close() {
   _isClosed = true;
   for (Monitor monitor : _entries.values()) {
     monitor.close();
   }
   _inner.close();
 }
  public void evaluateSequential(Frontier frontier, Seen seen) {
    Redirects r = null;
    try {
      r = _redirsClass.newInstance();
    } catch (InstantiationException e) {
      _log.info("IllegalAccessException. Using dummy.");
      r = new DummyRedirects();
    } catch (IllegalAccessException e) {
      _log.info("IllegalAccessException. Using dummy.");
      r = new DummyRedirects();
    }

    _queue = new BreadthFirstQueue(_tldm, r, seen, Integer.MAX_VALUE, Integer.MAX_VALUE, -1, false);
    _queue.schedule(frontier);

    _log.info(_queue.toString());

    int i = 0;

    while (_queue.size() > 0 && i <= CrawlerConstants.MAX_REDIRECTS) {
      List<Thread> ts = new ArrayList<Thread>();

      for (int j = 0; j < _threads; j++) {
        LookupThread lt =
            new LookupThread(
                _cm, _queue, _contentHandler, _output, _links, _robots, _eh, _ff, _blacklist, j);
        ts.add(lt); // new Thread(lt,"LookupThread-"+j));
      }

      _log.info("Starting threads round " + i++ + " with " + _queue.size() + " uris");

      for (Thread t : ts) {
        t.start();
      }

      Monitor m = new Monitor(ts, System.err, 1000 * 10);
      m.start();

      for (Thread t : ts) {
        try {
          t.join();
        } catch (InterruptedException e1) {
          _log.info(e1.getMessage());
          // e1.printStackTrace();
        }
      }

      m.shutdown();

      _queue.schedule(frontier);

      _log.info("ROUND " + i + " DONE with " + _queue.size() + " uris remaining in queue");

      _log.info("new queue: \n" + _queue.toString());
    }

    _log.info("DONE with " + _queue.size() + " uris remaining in queue");
  }
示例#23
0
 /**
  * Return an array with spaces for the values in header and values populated for monitor data -
  * last value, active and last access
  */
 public Object[] getData(Monitor mon) {
   Object[] retData =
       new Object
           [header.length]; // all but the 2 values will be null and will be replaced by caller.
   retData[lastValueIndex] = new Double(mon.getLastValue());
   retData[activeIndex] = new Double(mon.getActive());
   retData[dateIndex] = mon.getLastAccess();
   return retData;
 }
示例#24
0
 public java.lang.String getLastError(com.dragonflow.SiteView.J2EEMonitor j2eemonitor) {
   java.lang.String s = (java.lang.String) j2eemonitor.getUniqueID();
   Monitor monitor = (Monitor) activeMonitors.get(s);
   java.lang.String s1 = monitor.getLastError();
   if (s1 == null) {
     s1 = lastError;
   }
   return s1;
 }
示例#25
0
 protected void addToMonitorList(Monitor monitor, Array array, HashMap hashmap) {
   if (monitor == this) {
     return;
   }
   String s = monitor.getProperty(pGroupID) + " " + monitor.getProperty(pID);
   if (hashmap.get(s) == null) {
     hashmap.put(s, monitor);
     array.add(monitor);
   }
 }
示例#26
0
 /**
  * Test method for {@link Monitor#getServiceInfo()}.
  *
  * @throws ConnectionException
  */
 @Test
 public final void testGetServiceInfo1() throws ConnectionException {
   final Monitor conn = new Monitor(scalarisNode);
   try {
     final GetServiceInfoResult serviceInfo = conn.getServiceInfo();
     assertTrue(serviceInfo.nodes >= 0);
     assertTrue(serviceInfo.totalLoad >= 0);
   } finally {
     conn.closeConnection();
   }
 }
 /**
  * This method is used to write the zero length chunk. Writing the zero length chunk tells the
  * client that the response has been fully sent, and the next sequence of bytes from the HTTP
  * pipeline is the start of the next response. This will signal to the server kernel that the next
  * request is read to read.
  */
 private void finish() throws IOException {
   try {
     sender.send(zero);
     monitor.ready(sender);
   } catch (Exception cause) {
     if (sender != null) {
       monitor.close(sender);
     }
     throw new ProducerException("Error flushing response", cause);
   }
 }
示例#28
0
 /**
  * Attempts to start the timer immediately prior to the service being started via {@link
  * Service#startAsync()}.
  */
 void tryStartTiming(Service service) {
   monitor.enter();
   try {
     Stopwatch stopwatch = startupTimers.get(service);
     if (stopwatch == null) {
       startupTimers.put(service, Stopwatch.createStarted());
     }
   } finally {
     monitor.leave();
   }
 }
示例#29
0
    /**
     * Updates the state with the given service transition.
     *
     * <p>This method performs the main logic of ServiceManager in the following steps.
     *
     * <ol>
     *   <li>Update the {@link #servicesByState()}
     *   <li>Update the {@link #startupTimers}
     *   <li>Based on the new state queue listeners to run
     *   <li>Run the listeners (outside of the lock)
     * </ol>
     */
    void transitionService(final Service service, State from, State to) {
      checkNotNull(service);
      checkArgument(from != to);
      monitor.enter();
      try {
        transitioned = true;
        if (!ready) {
          return;
        }
        // Update state.
        checkState(
            servicesByState.remove(from, service),
            "Service %s not at the expected location in the state map %s",
            service,
            from);
        checkState(
            servicesByState.put(to, service),
            "Service %s in the state map unexpectedly at %s",
            service,
            to);
        // Update the timer
        Stopwatch stopwatch = startupTimers.get(service);
        if (stopwatch == null) {
          // This means the service was started by some means other than ServiceManager.startAsync
          stopwatch = Stopwatch.createStarted();
          startupTimers.put(service, stopwatch);
        }
        if (to.compareTo(RUNNING) >= 0 && stopwatch.isRunning()) {
          // N.B. if we miss the STARTING event then we may never record a startup time.
          stopwatch.stop();
          if (!(service instanceof NoOpService)) {
            logger.log(Level.FINE, "Started {0} in {1}.", new Object[] {service, stopwatch});
          }
        }
        // Queue our listeners

        // Did a service fail?
        if (to == FAILED) {
          fireFailedListeners(service);
        }

        if (states.count(RUNNING) == numberOfServices) {
          // This means that the manager is currently healthy. N.B. If other threads call isHealthy
          // they are not guaranteed to get 'true', because any service could fail right now.
          fireHealthyListeners();
        } else if (states.count(TERMINATED) + states.count(FAILED) == numberOfServices) {
          fireStoppedListeners();
        }
      } finally {
        monitor.leave();
        // Run our executors outside of the lock
        executeListeners();
      }
    }
示例#30
0
 @Override
 public void run() {
   while (true) {
     try {
       monitor.DEC();
       System.out.println(
           "resto y total:" + monitor.toString() + " soy " + Thread.currentThread().getName());
     } catch (InterruptedException ex) {
       Logger.getLogger(HiloRestador.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
 }