@Override
 public void run() {
   try {
     boolean running = true;
     while (running) {
       try {
         // block on event availability
         ThreadBoundEvent event = queue.take();
         // add to the batch, and see if we can add more
         batch.add(event);
         if (maxBatchSize > 0) {
           queue.drainTo(batch, maxBatchSize);
         }
         // check for the stop condition (and remove it)
         // treat batches of 1 (the most common case) specially
         if (batch.size() > 1) {
           ListIterator<ThreadBoundEvent> itr = batch.listIterator();
           while (itr.hasNext()) {
             ThreadBoundEvent next = itr.next();
             if (next.getClass().equals(ShutdownTask.class)) {
               running = false;
               ((ShutdownTask) next).latch.countDown();
               itr.remove();
             }
           }
           eventProcessor.process(batch);
         } else {
           // just the one event, no need to iterate
           if (event.getClass().equals(ShutdownTask.class)) {
             running = false;
             ((ShutdownTask) event).latch.countDown();
           } else {
             eventProcessor.process(batch);
           }
         }
       } catch (InterruptedException e) {
         LOG.warn(
             String.format(
                 "Consumer on queue %s interrupted.", Thread.currentThread().getName()));
         // ignore
       } catch (Throwable exception) {
         LOG.error(
             String.format(
                 "exception on queue %s while executing events",
                 Thread.currentThread().getName()),
             exception);
       } finally {
         // reset the batch
         batch.clear();
       }
     }
   } catch (Throwable unexpectedThrowable) {
     // we observed some cases where trying to log the inner exception threw an error
     // don't use the logger here as that seems to be causing the problem in the first place
     System.err.println("Caught and unexpected Throwable while logging");
     System.err.println(
         "This problem happens when jar files change at runtime, JVM might be UNSTABLE");
     unexpectedThrowable.printStackTrace(System.err);
   }
 }
Beispiel #2
0
  /** {@inheritDoc} */
  @Override
  public void run() {

    while (requests != null) {

      /* Not processing a request. */
      currentRequest = null;

      /* Take a new request from the queue, waiting for one if none is available yet. */
      try {
        currentRequest = requests.take();
      }

      /* Interrupted? Well, try again! */
      catch (InterruptedException ignored) {
        continue;
      }

      /* Process the request. */
      try {
        ui.process(currentRequest.getRequest());
      }

      /* Uncaught exception occurred during the request. */
      catch (Throwable e) {
        e.initCause(currentRequest.getCause());
        logger.err(e, "Unexpected error occurred.");
      }
    }
  }
 private void deferExpired() {
   for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
     JedisPool jedisPool = entry.getValue();
     try {
       Jedis jedis = jedisPool.getResource();
       try {
         for (Node node : new HashSet<Node>(getRegistered())) {
           String key = NodeRegistryUtils.getNodeTypePath(clusterName, node.getNodeType());
           if (jedis.hset(
                   key, node.toFullString(), String.valueOf(SystemClock.now() + expirePeriod))
               == 1) {
             jedis.publish(key, Constants.REGISTER);
           }
         }
         if (lock.acquire(jedis)) {
           clean(jedis);
         }
         if (!replicate) {
           break; //  如果服务器端已同步数据,只需写入单台机器
         }
       } finally {
         jedis.close();
       }
     } catch (Throwable t) {
       LOGGER.warn(
           "Failed to write provider heartbeat to redis registry. registry: "
               + entry.getKey()
               + ", cause: "
               + t.getMessage(),
           t);
     }
   }
 }
 public void shutdown() {
   try {
     running = false;
     jedis.disconnect();
   } catch (Throwable t) {
     LOGGER.warn(t.getMessage(), t);
   }
 }
  @Override
  protected void doSubscribe(Node node, NotifyListener listener) {

    List<NodeType> listenNodeTypes = node.getListenNodeTypes();
    if (CollectionUtils.isEmpty(listenNodeTypes)) {
      return;
    }
    for (NodeType listenNodeType : listenNodeTypes) {
      String listenNodePath = NodeRegistryUtils.getNodeTypePath(clusterName, listenNodeType);

      Notifier notifier = notifiers.get(listenNodePath);
      if (notifier == null) {
        Notifier newNotifier = new Notifier(listenNodePath);
        notifiers.putIfAbsent(listenNodePath, newNotifier);
        notifier = notifiers.get(listenNodePath);
        if (notifier == newNotifier) {
          notifier.start();
        }
      }

      boolean success = false;
      NodeRegistryException exception = null;
      for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
        JedisPool jedisPool = entry.getValue();
        try {
          Jedis jedis = jedisPool.getResource();
          try {
            doNotify(
                jedis,
                Collections.singletonList(listenNodePath),
                Collections.singletonList(listener));
            success = true;
            break; // 只需读一个服务器的数据

          } finally {
            jedis.close();
          }
        } catch (Throwable t) {
          exception =
              new NodeRegistryException(
                  "Failed to unregister node to redis registry. registry: "
                      + entry.getKey()
                      + ", node: "
                      + node
                      + ", cause: "
                      + t.getMessage(),
                  t);
        }
      }
      if (exception != null) {
        if (success) {
          LOGGER.warn(exception.getMessage(), exception);
        } else {
          throw exception;
        }
      }
    }
  }
Beispiel #6
0
 /**
  * https://github.com/ReactiveX/RxJava/issues/198
  *
  * <p>Rx Design Guidelines 5.2
  *
  * <p>"when calling the Subscribe method that only has an onNext argument, the OnError behavior
  * will be to rethrow the exception on the thread that the message comes out from the Observable.
  * The OnCompleted behavior in this case is to do nothing."
  */
 @Test
 @Ignore("Subscribers can't throw")
 public void testErrorThrownWithoutErrorHandlerSynchronous() {
   try {
     Observable.error(new RuntimeException("failure")).subscribe();
     fail("expected exception");
   } catch (Throwable e) {
     assertEquals("failure", e.getMessage());
   }
 }
Beispiel #7
0
 /**
  * oneway调用,只发送请求,不接收返回结果.
  *
  * @param callable
  */
 public void asyncCall(Runnable runable) {
   try {
     setAttachment(Constants.RETURN_KEY, Boolean.FALSE.toString());
     runable.run();
   } catch (Throwable e) {
     // FIXME 异常是否应该放在future中?
     throw new RpcException("oneway call error ." + e.getMessage(), e);
   } finally {
     removeAttachment(Constants.RETURN_KEY);
   }
 }
    public void run() {
      final Connection conn = packet.getConn();
      final ClientEndpoint endpoint = getEndpoint(conn);
      ClientRequest request = null;
      try {
        final Data data = packet.getData();
        request = (ClientRequest) serializationService.toObject(data);
        if (endpoint.isAuthenticated() || request instanceof AuthenticationRequest) {
          request.setEndpoint(endpoint);
          final String serviceName = request.getServiceName();
          if (serviceName != null) {
            final Object service = nodeEngine.getService(serviceName);
            if (service == null) {
              if (nodeEngine.isActive()) {
                throw new IllegalArgumentException(
                    "No service registered with name: " + serviceName);
              }
              throw new HazelcastInstanceNotActiveException();
            }
            request.setService(service);
          }
          request.setClientEngine(ClientEngineImpl.this);
          final SecurityContext securityContext = getSecurityContext();
          if (securityContext != null && request instanceof SecureRequest) {
            final Permission permission = ((SecureRequest) request).getRequiredPermission();
            if (permission != null) {
              securityContext.checkPermission(endpoint.getSubject(), permission);
            }
          }
          request.process();
        } else {
          Exception exception;
          if (nodeEngine.isActive()) {
            String message = "Client " + conn + " must authenticate before any operation.";
            logger.severe(message);
            exception = new AuthenticationException(message);
          } else {
            exception = new HazelcastInstanceNotActiveException();
          }
          sendResponse(endpoint, exception);

          removeEndpoint(conn);
        }
      } catch (Throwable e) {
        final Level level = nodeEngine.isActive() ? Level.SEVERE : Level.FINEST;
        String message =
            request != null
                ? "While executing request: " + request + " -> " + e.getMessage()
                : e.getMessage();
        logger.log(level, message, e);
        sendResponse(endpoint, e);
      }
    }
 private boolean canRetryDriverConnection(Exception e) {
   if (e instanceof DriverException && e.getMessage().contains("Connection thread interrupted"))
     return true;
   if (e instanceof NoHostAvailableException) {
     if (((NoHostAvailableException) e).getErrors().values().size() == 1) {
       Throwable cause = ((NoHostAvailableException) e).getErrors().values().iterator().next();
       if (cause != null
           && cause.getCause() instanceof java.nio.channels.ClosedByInterruptException) {
         return true;
       }
     }
   }
   return false;
 }
Beispiel #10
0
 public void start(String[] args) throws Exception {
   if (lineReader == null) {
     lineReader = new DefaultLineReader();
   }
   running = true;
   while (running) {
     print("hazelcast[" + namespace + "] > ");
     try {
       final String command = lineReader.readLine();
       handleCommand(command);
     } catch (Throwable e) {
       e.printStackTrace();
     }
   }
 }
Beispiel #11
0
 protected void doThrowable(final Throwable e) throws Exception {
   if (parent.launchLocation != null) {
     final ArrayList<StackTraceElement> stack =
         new ArrayList<StackTraceElement>(Arrays.asList(e.getStackTrace()));
     stack.addAll(Arrays.asList(parent.launchLocation));
     e.setStackTrace(stack.toArray(new StackTraceElement[stack.size()]));
   }
   postToUiThreadAndWait(
       new Callable<Object>() {
         public Object call() throws Exception {
           parent.onThrowable(e);
           return null;
         }
       });
 }
  /**
   * Processes cache query request.
   *
   * @param sndId Sender node id.
   * @param req Query request.
   */
  @SuppressWarnings("unchecked")
  @Override
  void processQueryRequest(UUID sndId, GridCacheQueryRequest req) {
    if (req.cancel()) {
      cancelIds.add(new CancelMessageId(req.id(), sndId));

      if (req.fields()) removeFieldsQueryResult(sndId, req.id());
      else removeQueryResult(sndId, req.id());
    } else {
      if (!cancelIds.contains(new CancelMessageId(req.id(), sndId))) {
        if (!F.eq(req.cacheName(), cctx.name())) {
          GridCacheQueryResponse res =
              new GridCacheQueryResponse(
                  cctx.cacheId(),
                  req.id(),
                  new IgniteCheckedException(
                      "Received request for incorrect cache [expected="
                          + cctx.name()
                          + ", actual="
                          + req.cacheName()));

          sendQueryResponse(sndId, res, 0);
        } else {
          threads.put(req.id(), Thread.currentThread());

          try {
            GridCacheQueryInfo info = distributedQueryInfo(sndId, req);

            if (info == null) return;

            if (req.fields()) runFieldsQuery(info);
            else runQuery(info);
          } catch (Throwable e) {
            U.error(log(), "Failed to run query.", e);

            sendQueryResponse(
                sndId, new GridCacheQueryResponse(cctx.cacheId(), req.id(), e.getCause()), 0);

            if (e instanceof Error) throw (Error) e;
          } finally {
            threads.remove(req.id());
          }
        }
      }
    }
  }
 @Override
 public void onMessage(String key, String msg) {
   if (LOGGER.isInfoEnabled()) {
     LOGGER.info("redis event: " + key + " = " + msg);
   }
   if (msg.equals(Constants.REGISTER) || msg.equals(Constants.UNREGISTER)) {
     try {
       Jedis jedis = jedisPool.getResource();
       try {
         doNotify(jedis, key);
       } finally {
         jedis.close();
       }
     } catch (Throwable t) {
       LOGGER.error(t.getMessage(), t);
     }
   }
 }
    public void run() {
      try {
        for (; ; ) {
          final Pair<Handler, Message> entry = eventQueue.take();
          final Handler handler = entry.left;
          final Message message = entry.right;
          try {
            // A message is either a command or an event.
            // A command returns a value that must be read by
            // the caller.
            if (message instanceof Command<?>) {
              Command<?> command = (Command<?>) message;
              try {
                Locus.push(command.getLocus());
                Object result = command.call();
                responseQueue.put(command, Pair.of(result, (Throwable) null));
              } catch (PleaseShutdownException e) {
                responseQueue.put(command, Pair.of(null, (Throwable) null));
                return; // exit event loop
              } catch (Throwable e) {
                responseQueue.put(command, Pair.of(null, e));
              } finally {
                Locus.pop(command.getLocus());
              }
            } else {
              Event event = (Event) message;
              event.acceptWithoutResponse(handler);

              // Broadcast the event to anyone who is interested.
              RolapUtil.MONITOR_LOGGER.debug(message);
            }
          } catch (Throwable e) {
            // REVIEW: Somewhere better to send it?
            e.printStackTrace();
          }
        }
      } catch (InterruptedException e) {
        // REVIEW: Somewhere better to send it?
        e.printStackTrace();
      } catch (Throwable e) {
        e.printStackTrace();
      }
    }
 @Override
 protected void handleInitComponentError(
     final Throwable ex, final boolean fatal, final String componentClassName) {
   if (PluginManager.isPluginClass(componentClassName)) {
     LOG.error(ex);
     PluginId pluginId = PluginManager.getPluginByClassName(componentClassName);
     @NonNls
     final String errorMessage =
         "Plugin "
             + pluginId.getIdString()
             + " failed to initialize and will be disabled:\n"
             + ex.getMessage()
             + "\nPlease restart "
             + ApplicationNamesInfo.getInstance().getFullProductName()
             + ".";
     PluginManager.disablePlugin(pluginId.getIdString());
     if (!myHeadlessMode) {
       JOptionPane.showMessageDialog(null, errorMessage);
     } else {
       //noinspection UseOfSystemOutOrSystemErr
       System.out.println(errorMessage);
       System.exit(1);
     }
     return; // do not call super
   }
   if (fatal) {
     LOG.error(ex);
     @NonNls
     final String errorMessage =
         "Fatal error initializing class "
             + componentClassName
             + ":\n"
             + ex.toString()
             + "\nComplete error stacktrace was written to idea.log";
     if (!myHeadlessMode) {
       JOptionPane.showMessageDialog(null, errorMessage);
     } else {
       //noinspection UseOfSystemOutOrSystemErr
       System.out.println(errorMessage);
     }
   }
   super.handleInitComponentError(ex, fatal, componentClassName);
 }
  @Test
  public void testThreadPoolLeakingThreadsWithTribeNode() {
    Settings settings =
        ImmutableSettings.builder()
            .put("node.name", "thread_pool_leaking_threads_tribe_node")
            .put("path.home", createTempDir())
            .put("tribe.t1.cluster.name", "non_existing_cluster")
            // trigger initialization failure of one of the tribes (doesn't require starting the
            // node)
            .put("tribe.t1.plugin.mandatory", "non_existing")
            .build();

    try {
      NodeBuilder.nodeBuilder().settings(settings).build();
      fail("The node startup is supposed to fail");
    } catch (Throwable t) {
      // all good
      assertThat(t.getMessage(), containsString("mandatory plugins [non_existing]"));
    }
  }
 @Override
 public void destroy() {
   super.destroy();
   try {
     expireFuture.cancel(true);
   } catch (Throwable t) {
     LOGGER.warn(t.getMessage(), t);
   }
   try {
     for (Notifier notifier : notifiers.values()) {
       notifier.shutdown();
     }
   } catch (Throwable t) {
     LOGGER.warn(t.getMessage(), t);
   }
   for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
     JedisPool jedisPool = entry.getValue();
     try {
       jedisPool.destroy();
     } catch (Throwable t) {
       LOGGER.warn(
           "Failed to destroy the redis registry client. registry: "
               + entry.getKey()
               + ", cause: "
               + t.getMessage(),
           t);
     }
   }
 }
 @Override
 protected void doRegister(Node node) {
   String key = NodeRegistryUtils.getNodeTypePath(clusterName, node.getNodeType());
   String expire = String.valueOf(SystemClock.now() + expirePeriod);
   boolean success = false;
   NodeRegistryException exception = null;
   for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
     JedisPool jedisPool = entry.getValue();
     try {
       Jedis jedis = jedisPool.getResource();
       try {
         jedis.hset(key, node.toFullString(), expire);
         jedis.publish(key, Constants.REGISTER);
         success = true;
         if (!replicate) {
           break; //  如果服务器端已同步数据,只需写入单台机器
         }
       } finally {
         jedis.close();
       }
     } catch (Throwable t) {
       exception =
           new NodeRegistryException(
               "Failed to register node to redis registry. registry: "
                   + entry.getKey()
                   + ", node: "
                   + node
                   + ", cause: "
                   + t.getMessage(),
               t);
     }
   }
   if (exception != null) {
     if (success) {
       LOGGER.warn(exception.getMessage(), exception);
     } else {
       throw exception;
     }
   }
 }
Beispiel #19
0
  /** Submit exec into pool and throw exceptions */
  public void execute() {
    String p = project.getProperty("number.of.threads");
    if (p != null) {
      ((ThreadPoolExecutor) threadPool).setCorePoolSize(Integer.parseInt(p));
      ((ThreadPoolExecutor) threadPool).setMaximumPoolSize(Integer.parseInt(p));
    }
    TaskRunnable tr = new TaskRunnable();
    threadPool.submit(tr);
    try {
      synchronized (semaphore) {
        while (!tr.isFinished()) semaphore.wait();
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    Throwable t = tr.getException();
    if (t != null) {
      if (t instanceof BuildException) throw (BuildException) t;
      else t.printStackTrace();
    }
  }
 public void _saveSettings() { // public for testing purposes
   if (mySaveSettingsIsInProgress.compareAndSet(false, true)) {
     try {
       doSave();
     } catch (final Throwable ex) {
       if (isUnitTestMode()) {
         System.out.println("Saving application settings failed");
         ex.printStackTrace();
       } else {
         LOG.info("Saving application settings failed", ex);
         invokeLater(
             new Runnable() {
               public void run() {
                 if (ex instanceof PluginException) {
                   final PluginException pluginException = (PluginException) ex;
                   PluginManager.disablePlugin(pluginException.getPluginId().getIdString());
                   Messages.showMessageDialog(
                       "The plugin "
                           + pluginException.getPluginId()
                           + " failed to save settings and has been disabled. Please restart "
                           + ApplicationNamesInfo.getInstance().getFullProductName(),
                       CommonBundle.getErrorTitle(),
                       Messages.getErrorIcon());
                 } else {
                   Messages.showMessageDialog(
                       ApplicationBundle.message(
                           "application.save.settings.error", ex.getLocalizedMessage()),
                       CommonBundle.getErrorTitle(),
                       Messages.getErrorIcon());
                 }
               }
             });
       }
     } finally {
       mySaveSettingsIsInProgress.set(false);
     }
   }
 }
 @Override
 public void run() {
   try {
     while (running) {
       int retryTimes = 0;
       for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
         try {
           JedisPool jedisPool = entry.getValue();
           jedis = jedisPool.getResource();
           if (listenNodePath.equals(monitorId) && !redisAvailable) {
             redisAvailable = true;
             appContext.getRegistryStatMonitor().setAvailable(redisAvailable);
           }
           try {
             retryTimes = 0;
             jedis.subscribe(new NotifySub(jedisPool), listenNodePath); // 阻塞
             break;
           } finally {
             jedis.close();
           }
         } catch (Throwable t) { // 重试另一台
           LOGGER.warn(
               "Failed to subscribe node from redis registry. registry: " + entry.getKey(), t);
           if (++retryTimes % jedisPools.size() == 0) {
             // 如果在所有redis都不可用,需要休息一会,避免空转占用过多cpu资源
             sleep(reconnectPeriod);
             if (listenNodePath.equals(monitorId) && redisAvailable) {
               redisAvailable = false;
               appContext.getRegistryStatMonitor().setAvailable(redisAvailable);
             }
           }
         }
       }
     }
   } catch (Throwable t) {
     LOGGER.error(t.getMessage(), t);
   }
 }
Beispiel #22
0
 @Override
 public void run() {
   // Устанавливаем системные параметры запуска
   startTask();
   // Выполняем задачу
   Map<String, Object> results = null;
   TaskResultStatus resultStatus;
   Throwable cause = null;
   try {
     results = performer.performTask(this, result.getParameters());
     resultStatus = (isCancelled()) ? TaskResultStatus.CANCELED : TaskResultStatus.FINISHED;
   } catch (Throwable th) {
     resultStatus = TaskResultStatus.ERROR;
     cause = th;
     LOG.error(
         String.format(
             "Task '%s[%s]' error: %s",
             descriptor.getId(), performer.retrieveName(), cause.getMessage()),
         cause);
   }
   // Устанавливаем системные параметры завершения
   endTask(results, resultStatus, cause);
 }
Beispiel #23
0
 /**
  * Устанавливает параметры завершения задачи
  *
  * @param results результат задачи
  * @param resultStatus статус завершения
  * @param exception исключения, которое произошло в процессе выполнения
  */
 private void endTask(
     Map<String, Object> results, TaskResultStatus resultStatus, Throwable exception) {
   writeLock.lock();
   try {
     result.setContent(results);
     result.setStatus(resultStatus);
     if (exception != null) {
       result.setErrorMessage(
           StringUtils.abbreviate(exception.getMessage(), TaskResult.ERROR_MESSAGE_MAX_SIZE - 3));
     }
     result.setEndDate(new Date());
     executionLock.countDown();
     changeState(null, TaskExecutionStatus.READY);
   } finally {
     writeLock.unlock();
   }
 }
    @Override
    public DataContainer call() throws Exception {

      for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
        try {
          listener.beforeExecute(dataFlowInstance, builderMeta, dataDelta, responseData);
        } catch (Throwable t) {
          logger.error("Error running pre-execution execution listener: ", t);
        }
      }
      try {
        Data response =
            builder.process(
                dataBuilderContext.immutableCopy(
                    dataSet.accessor().getAccesibleDataSetFor(builder)));
        // logger.debug("Ran " + builderMeta.getName());
        procesedBuilders.add(builderMeta);
        for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
          try {
            listener.afterExecute(dataFlowInstance, builderMeta, dataDelta, responseData, response);
          } catch (Throwable t) {
            logger.error("Error running post-execution listener: ", t);
          }
        }
        if (null != response) {
          Preconditions.checkArgument(
              response.getData().equalsIgnoreCase(builderMeta.getProduces()),
              String.format(
                  "Builder is supposed to produce %s but produces %s",
                  builderMeta.getProduces(), response.getData()));
          response.setGeneratedBy(builderMeta.getName());
        }
        return new DataContainer(builderMeta, response);
      } catch (DataBuilderException e) {
        logger.error("Error running builder: " + builderMeta.getName());
        for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
          try {
            listener.afterException(dataFlowInstance, builderMeta, dataDelta, responseData, e);

          } catch (Throwable error) {
            logger.error("Error running post-execution listener: ", error);
          }
        }
        return new DataContainer(
            builderMeta,
            new DataBuilderFrameworkException(
                DataBuilderFrameworkException.ErrorCode.BUILDER_EXECUTION_ERROR,
                "Error running builder: " + builderMeta.getName(),
                e.getDetails(),
                e));

      } catch (DataValidationException e) {
        logger.error("Validation error in data produced by builder" + builderMeta.getName());
        for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
          try {
            listener.afterException(dataFlowInstance, builderMeta, dataDelta, responseData, e);

          } catch (Throwable error) {
            logger.error("Error running post-execution listener: ", error);
          }
        }
        return new DataContainer(
            builderMeta,
            new DataValidationException(
                DataValidationException.ErrorCode.DATA_VALIDATION_EXCEPTION,
                "Error running builder: " + builderMeta.getName(),
                new DataExecutionResponse(responseData),
                e.getDetails(),
                e));

      } catch (Throwable t) {
        logger.error("Error running builder: " + builderMeta.getName());
        for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
          try {
            listener.afterException(dataFlowInstance, builderMeta, dataDelta, responseData, t);

          } catch (Throwable error) {
            logger.error("Error running post-execution listener: ", error);
          }
        }
        Map<String, Object> objectMap = new HashMap<String, Object>();
        objectMap.put("MESSAGE", t.getMessage());
        return new DataContainer(
            builderMeta,
            new DataBuilderFrameworkException(
                DataBuilderFrameworkException.ErrorCode.BUILDER_EXECUTION_ERROR,
                "Error running builder: " + builderMeta.getName() + t.getMessage(),
                objectMap,
                t));
      }
    }
Beispiel #25
0
 static void unexpected(Throwable t) {
   failed++;
   t.printStackTrace();
 }
Beispiel #26
0
  public synchronized RPC<V> call() {
    // Any Completer will not be carried over to remote; add it to the RPC call
    // so completion is signaled after the remote comes back.
    CountedCompleter cc = _dt.getCompleter();
    if (cc != null) handleCompleter(cc);

    // If running on self, just submit to queues & do locally
    if (_target == H2O.SELF) return handleLocal();

    // Keep a global record, for awhile
    if (_target != null) _target.taskPut(_tasknum, this);
    try {
      if (_nack) return this; // Racing Nack rechecked under lock; no need to send retry
      // We could be racing timeouts-vs-replies.  Blow off timeout if we have an answer.
      if (isDone()) {
        if (_target != null) _target.taskRemove(_tasknum);
        return this;
      }
      // Default strategy: (re)fire the packet and (re)start the timeout.  We
      // "count" exactly 1 failure: just whether or not we shipped via TCP ever
      // once.  After that we fearlessly (re)send UDP-sized packets until the
      // server replies.

      // Pack classloader/class & the instance data into the outgoing
      // AutoBuffer.  If it fits in a single UDP packet, ship it.  If not,
      // finish off the current AutoBuffer (which is now going TCP style), and
      // make a new UDP-sized packet.  On a re-send of a TCP-sized hunk, just
      // send the basic UDP control packet.
      if (!_sentTcp) {
        while (true) { // Retry loop for broken TCP sends
          AutoBuffer ab = new AutoBuffer(_target, _dt.priority());
          try {
            final boolean t;
            int offset = ab.position();
            ab.putTask(UDP.udp.exec, _tasknum).put1(CLIENT_UDP_SEND);
            ab.put(_dt);
            t = ab.hasTCP();
            assert sz_check(ab)
                : "Resend of "
                    + _dt.getClass()
                    + " changes size from "
                    + _size
                    + " to "
                    + ab.size()
                    + " for task#"
                    + _tasknum;
            ab.close(); // Then close; send final byte
            _sentTcp = t; // Set after close (and any other possible fail)
            break; // Break out of retry loop
          } catch (AutoBuffer.AutoBufferException e) {
            Log.info(
                "IOException during RPC call: "
                    + e._ioe.getMessage()
                    + ",  AB="
                    + ab
                    + ", for task#"
                    + _tasknum
                    + ", waiting and retrying...");
            ab.drainClose();
            try {
              Thread.sleep(500);
            } catch (InterruptedException ignore) {
            }
          }
        } // end of while(true)
      } else {
        // Else it was sent via TCP in a prior attempt, and we've timed out.
        // This means the caller's ACK/answer probably got dropped and we need
        // him to resend it (or else the caller is still processing our
        // request).  Send a UDP reminder - but with the CLIENT_TCP_SEND flag
        // instead of the UDP send, and no DTask (since it previously went via
        // TCP, no need to resend it).
        AutoBuffer ab = new AutoBuffer(_target, _dt.priority()).putTask(UDP.udp.exec, _tasknum);
        ab.put1(CLIENT_TCP_SEND).close();
      }
      // Double retry until we exceed existing age.  This is the time to delay
      // until we try again.  Note that we come here immediately on creation,
      // so the first doubling happens before anybody does any waiting.  Also
      // note the generous 5sec cap: ping at least every 5 sec.
      _retry += (_retry < MAX_TIMEOUT) ? _retry : MAX_TIMEOUT;
      // Put self on the "TBD" list of tasks awaiting Timeout.
      // So: dont really 'forget' but remember me in a little bit.
      //      UDPTimeOutThread.PENDING.put(_tasknum, this);
      return this;
    } catch (Throwable t) {
      t.printStackTrace();
      throw Log.throwErr(t);
    }
  }
  @SuppressWarnings({"unchecked"})
  public final void execute(final Callback callback)
      throws MojoExecutionException, MojoFailureException {
    if (!skip) {
      if (header == null) {
        warn("No header file specified to check for license");
        return;
      }
      if (!strictCheck) {
        warn(
            "Property 'strictCheck' is not enabled. Please consider adding <strictCheck>true</strictCheck> in your pom.xml file.");
        warn("See http://mycila.github.io/license-maven-plugin for more information.");
      }

      finder = new ResourceFinder(basedir);
      try {
        finder.setCompileClassPath(project.getCompileClasspathElements());
      } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
      }
      finder.setPluginClassPath(getClass().getClassLoader());

      final Header h = new Header(finder.findResource(this.header), encoding, headerSections);
      debug("Header %s:\n%s", h.getLocation(), h);

      if (this.validHeaders == null) {
        this.validHeaders = new String[0];
      }
      final List<Header> validHeaders = new ArrayList<Header>(this.validHeaders.length);
      for (String validHeader : this.validHeaders) {
        validHeaders.add(new Header(finder.findResource(validHeader), encoding, headerSections));
      }

      final List<PropertiesProvider> propertiesProviders = new LinkedList<PropertiesProvider>();
      for (PropertiesProvider provider :
          ServiceLoader.load(
              PropertiesProvider.class, Thread.currentThread().getContextClassLoader())) {
        propertiesProviders.add(provider);
      }
      final DocumentPropertiesLoader propertiesLoader =
          new DocumentPropertiesLoader() {
            @Override
            public Properties load(Document document) {
              Properties props = new Properties();

              for (Map.Entry<String, String> entry : mergeProperties(document).entrySet()) {
                if (entry.getValue() != null) {
                  props.setProperty(entry.getKey(), entry.getValue());
                } else {
                  props.remove(entry.getKey());
                }
              }
              for (PropertiesProvider provider : propertiesProviders) {
                try {
                  final Map<String, String> providerProperties =
                      provider.getAdditionalProperties(AbstractLicenseMojo.this, props, document);
                  if (getLog().isDebugEnabled()) {
                    getLog()
                        .debug(
                            "provider: "
                                + provider.getClass()
                                + " brought new properties\n"
                                + providerProperties);
                  }
                  for (Map.Entry<String, String> entry : providerProperties.entrySet()) {
                    if (entry.getValue() != null) {
                      props.setProperty(entry.getKey(), entry.getValue());
                    } else {
                      props.remove(entry.getKey());
                    }
                  }
                } catch (Exception e) {
                  getLog().warn("failure occured while calling " + provider.getClass(), e);
                }
              }
              return props;
            }
          };

      final DocumentFactory documentFactory =
          new DocumentFactory(
              basedir,
              buildMapping(),
              buildHeaderDefinitions(),
              encoding,
              keywords,
              propertiesLoader);

      int nThreads = (int) (Runtime.getRuntime().availableProcessors() * concurrencyFactor);
      ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
      CompletionService completionService = new ExecutorCompletionService(executorService);
      int count = 0;
      debug("Number of execution threads: %s", nThreads);

      try {
        for (final String file : listSelectedFiles()) {
          completionService.submit(
              new Runnable() {
                @Override
                public void run() {
                  Document document = documentFactory.createDocuments(file);
                  debug(
                      "Selected file: %s [header style: %s]",
                      document.getFilePath(), document.getHeaderDefinition());
                  if (document.isNotSupported()) {
                    callback.onUnknownFile(document, h);
                  } else if (document.is(h)) {
                    debug("Skipping header file: %s", document.getFilePath());
                  } else if (document.hasHeader(h, strictCheck)) {
                    callback.onExistingHeader(document, h);
                  } else {
                    boolean headerFound = false;
                    for (Header validHeader : validHeaders) {
                      if (headerFound = document.hasHeader(validHeader, strictCheck)) {
                        callback.onExistingHeader(document, h);
                        break;
                      }
                    }
                    if (!headerFound) {
                      callback.onHeaderNotFound(document, h);
                    }
                  }
                }
              },
              null);
          count++;
        }

        while (count-- > 0) {
          try {
            completionService.take().get();
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof Error) {
              throw (Error) cause;
            }
            if (cause instanceof MojoExecutionException) {
              throw (MojoExecutionException) cause;
            }
            if (cause instanceof MojoFailureException) {
              throw (MojoFailureException) cause;
            }
            if (cause instanceof RuntimeException) {
              throw (RuntimeException) cause;
            }
            throw new RuntimeException(cause.getMessage(), cause);
          }
        }

      } finally {
        executorService.shutdownNow();
      }
    }
  }