Пример #1
0
  private synchronized void saveHOMStates() {
    ch1 = new Channel[rfCavs.size()];
    ch2 = new Channel[rfCavs.size()];
    hom0States = new int[rfCavs.size()];
    hom1States = new int[rfCavs.size()];

    ChannelFactory cf = ChannelFactory.defaultFactory();

    Iterator<SCLCavity> it = rfCavs.iterator();
    int i = 0;

    while (it.hasNext()) {
      // get HOM monitor states
      String cavName = ((AcceleratorNode) it.next()).getId();
      String chName0 = cavName.replaceAll("RF:Cav", "LLRF:HPM").concat(":HBADC0_Ctl");
      String chName1 = cavName.replaceAll("RF:Cav", "LLRF:HPM").concat(":HBADC1_Ctl");
      ch1[i] = cf.getChannel(chName0);
      ch2[i] = cf.getChannel(chName1);

      try {
        hom0States[i] = Integer.parseInt(ch1[i].getValueRecord().stringValue());
        hom1States[i] = Integer.parseInt(ch2[i].getValueRecord().stringValue());
      } catch (ConnectionException ce) {
        System.out.println("Cannot connect to a channel!");
      } catch (GetException ge) {
        System.out.println("Cannot get a channel value!");
      }

      i++;
    }
    finished1 = true;
    this.notify();
  }
Пример #2
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();
      }
    }
Пример #3
0
  private void onMsgChannelOpen(SshMsgChannelOpen msg) throws IOException {
    synchronized (activeChannels) {
      log.info("Request for " + msg.getChannelType() + " channel recieved");

      // Try to get the channel implementation from the allowed channels
      ChannelFactory cf = (ChannelFactory) allowedChannels.get(msg.getChannelType());

      if (cf == null) {
        sendChannelOpenFailure(
            msg.getSenderChannelId(),
            SshMsgChannelOpenFailure.SSH_OPEN_CONNECT_FAILED,
            "The channel type is not supported",
            "");
        log.info("Request for channel type " + msg.getChannelType() + " refused");

        return;
      }

      try {
        log.info("Creating channel " + msg.getChannelType());

        Channel channel = cf.createChannel(msg.getChannelType(), msg.getChannelData());

        // Initialize the channel
        log.info("Initiating channel");

        Long channelId = getChannelId();
        channel.init(
            this,
            channelId.longValue(),
            msg.getSenderChannelId(),
            msg.getInitialWindowSize(),
            msg.getMaximumPacketSize());
        activeChannels.put(channelId, channel);
        log.info("Sending channel open confirmation");

        // Send the confirmation message
        sendChannelOpenConfirmation(channel);

        // Open the channel for real
        channel.open();
      } catch (InvalidChannelException ice) {
        sendChannelOpenFailure(
            msg.getSenderChannelId(),
            SshMsgChannelOpenFailure.SSH_OPEN_CONNECT_FAILED,
            ice.getMessage(),
            "");
      }
    }
  }
Пример #4
0
 private static final void unrefChannelFactory() {
   synchronized (channelFactoryRefs) {
     if (channelFactoryRefs.decrementAndGet() == 0) {
       channelFactory.releaseExternalResources();
       channelFactory = null;
     }
   }
 }
Пример #5
0
 public void stop() {
   try {
     myScheduler.shutdown();
     myBuildsExecutor.shutdown();
     final ChannelGroupFuture closeFuture = myAllOpenChannels.close();
     closeFuture.awaitUninterruptibly();
   } finally {
     myChannelFactory.releaseExternalResources();
   }
 }
Пример #6
0
  protected <C extends Channel> C createChannel(ChannelFactory<C> channelFactory, String clientId) {
    C channel = null;
    if (clientId != null) {
      channel = getChannel(channelFactory, clientId);
      if (channel != null) return channel;
    }

    String clientType = GraniteContext.getCurrentInstance().getClientType();
    channel = channelFactory.newChannel(UUIDUtil.randomUUID(), clientType);
    TimeChannel<C> timeChannel = new TimeChannel<C>(channel);
    for (int i = 0; channels.putIfAbsent(channel.getId(), timeChannel) != null; i++) {
      if (i >= 10)
        throw new RuntimeException("Could not find random new clientId after 10 iterations");
      channel.destroy(false);
      channel = channelFactory.newChannel(UUIDUtil.randomUUID(), clientType);
      timeChannel = new TimeChannel<C>(channel);
    }

    String channelId = channel.getId();

    // Save channel id in distributed data (clustering).
    try {
      DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
      if (gdd != null) {
        log.debug("Saving channel id in distributed data: %s", channelId);
        gdd.addChannelId(channelId, channelFactory.getClass().getName(), clientType);
      }
    } catch (Exception e) {
      log.error(e, "Could not add channel id in distributed data: %s", channelId);
    }

    // Initialize timer task.
    access(channelId);

    return channel;
  }
Пример #7
0
  @SuppressWarnings("unchecked")
  public <C extends Channel> C getChannel(ChannelFactory<C> channelFactory, String clientId) {
    if (clientId == null) return null;

    TimeChannel<C> timeChannel = (TimeChannel<C>) channels.get(clientId);
    if (timeChannel == null) {
      // Look for existing channel id/subscriptions in distributed data (clustering).
      log.debug("Lookup channel %s in distributed data", clientId);
      try {
        DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
        if (gdd != null && gdd.hasChannelId(clientId)) {
          log.debug("Found channel id in distributed data: %s", clientId);
          String channelFactoryClassName = gdd.getChannelFactoryClassName(clientId);
          String clientType = gdd.getChannelClientType(clientId);
          channelFactory =
              (ChannelFactory<C>)
                  TypeUtil.newInstance(
                      channelFactoryClassName, new Class<?>[] {Gravity.class}, new Object[] {this});
          C channel = channelFactory.newChannel(clientId, clientType);
          timeChannel = new TimeChannel<C>(channel);
          if (channels.putIfAbsent(clientId, timeChannel) == null) {
            for (CommandMessage subscription : gdd.getSubscriptions(clientId)) {
              log.debug("Resubscribing channel: %s - %s", clientId, subscription);
              handleSubscribeMessage(channelFactory, subscription, false);
            }
            access(clientId);
          }
        }
      } catch (Exception e) {
        log.error(
            e, "Could not recreate channel/subscriptions from distributed data: %s", clientId);
      }
    }

    return (timeChannel != null ? timeChannel.getChannel() : null);
  }
Пример #8
0
 @Override
 public void close() {
   allChannels.close().awaitUninterruptibly();
   channelFactory.releaseExternalResources();
 }
Пример #9
0
  /**
   * Start a HyperGateClient
   *
   * <p>for that case use
   *
   * @throws Exception
   */
  @Override
  public void start() throws Exception {

    if (this.running) {
      throw new InstantiationException("HyperGate client " + this.getName() + "is running");
    }

    // Configure the client.
    // TODO make it more robust & speedy implements Kryo serializer
    this.channelFactory =
        new NioClientSocketChannelFactory(
            // TODO implement other executors
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool());

    this.clientBootstrap = new ClientBootstrap(channelFactory);

    ChannelPipelineFactory channelPipelineFactory =
        new ChannelPipelineFactory() {
          public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(
                // TODO make Encoder & Decoder - like a Strategy Pattern, and changeable via
                // external settings
                //                        new KryoObjectEncoder(),
                //                        new
                // KryoObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader()))
                // TODO #6
                new ObjectEncoder(),
                new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())),
                new SimpleChannelUpstreamHandler() {

                  @Override
                  public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
                      throws Exception {
                    if (e instanceof ChannelStateEvent
                        && ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) {
                      LOG.info(e.toString());
                    }
                    super.handleUpstream(ctx, e);
                  }

                  @Override
                  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent event) {
                    channel = event.getChannel();
                    // Send the first message
                    // channel.write(firstMessage);
                  }

                  @Override
                  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
                    // Get
                    serverListener(e.getMessage());
                    ctx.sendUpstream(e);

                    // e.getChannel().write(e.getStatus());
                    // e.getChannel().close();
                  }

                  @Override
                  public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
                    LOG.warn("Unexpected exception from downstream.", e.getCause());
                    e.getChannel().close();
                  }
                });
          }
        };

    // Set up the pipeline factory.
    this.clientBootstrap.setPipelineFactory(channelPipelineFactory);

    // Start the connection attempt.
    // ChannelFuture channelFuture = this.clientBootstrap.connect(new InetSocketAddress(host,
    // setPort));
    LOG.debug("CLIENT GOING TO CONNECT - host:" + host + " post:" + port);
    this.channelFuture = this.clientBootstrap.connect(new InetSocketAddress(host, port));

    // INFO

    // correct shut down a client
    // see http://netty.io/3.6/guide/#start.12 - 9.  Shutting Down Your Application

    // http://stackoverflow.com/questions/10911988/shutting-down-netty-server-when-client-connections-are-open
    //    Netty Server Shutdown
    //
    //    Close server channel
    //    Shutdown boss and worker executor
    //    Release server bootstrap resource
    //    Example code
    //
    //    ChannelFuture cf = serverChannel.close();
    //    cf.awaitUninterruptibly();
    //    bossExecutor.shutdown();
    //    workerExecutor.shutdown();
    //    thriftServer.releaseExternalResources();

    // TODO Need to repair it

    boolean goAway = false;
    long countGoAway = 0;
    final long stepGoAway = 50; // ms

    LOG.warn("Warming up 0.6.0-SNAPSHOT ...");
    while (goAway == false | countGoAway < (SERVER_CONNECTION_TIMEOUT / stepGoAway)) {

      Thread.sleep(stepGoAway);
      if (!channelFuture.isSuccess()) {
        this.running = false;
        goAway = true;
      } else {
        this.running = true;
        goAway = true;
        countGoAway = (SERVER_CONNECTION_TIMEOUT / stepGoAway) + 10;
      }
      countGoAway++;
      LOG.warn(
          "Count down for connection tomeout:"
              + countGoAway * stepGoAway
              + ":ms future:"
              + channelFuture.isSuccess()
              + " running:"
              + this.running);
    }

    if (this.running == false) {
      LOG.warn("After ");
      channelFuture.getCause().printStackTrace();
      channelFactory.releaseExternalResources();
      channelFuture = null;
    }
  }
Пример #10
0
 private void shutDownChannelFuture(ChannelFuture channelFutureLocal) {
   channelFutureLocal.getCause().printStackTrace();
   channelFactory.releaseExternalResources();
   channelFutureLocal = null;
   running = false;
 }