Search in sources :

Example 71 with CuratorFramework

use of org.apache.curator.framework.CuratorFramework in project metron by apache.

the class ModelSubmission method execute.

public void execute(FileSystem fs, String... argv) throws Exception {
    CommandLine cli = ModelSubmissionOptions.parse(new PosixParser(), argv);
    if (ModelSubmissionOptions.LOG4J_PROPERTIES.has(cli)) {
        Log4jPropertyHelper.updateLog4jConfiguration(ModelSubmission.class, ModelSubmissionOptions.LOG4J_PROPERTIES.get(cli));
    }
    ModelRequest request = null;
    CuratorFramework client = null;
    try {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.newClient(ModelSubmissionOptions.ZK_QUORUM.get(cli), retryPolicy);
        client.start();
        MaaSConfig config = ConfigUtil.INSTANCE.read(client, ModelSubmissionOptions.ZK_ROOT.get(cli, "/metron/maas/config"), new MaaSConfig(), MaaSConfig.class);
        String mode = ModelSubmissionOptions.MODE.get(cli);
        if (mode.equalsIgnoreCase("ADD")) {
            request = new ModelRequest() {

                {
                    setName(ModelSubmissionOptions.NAME.get(cli));
                    setAction(Action.ADD);
                    setVersion(ModelSubmissionOptions.VERSION.get(cli));
                    setNumInstances(Integer.parseInt(ModelSubmissionOptions.NUM_INSTANCES.get(cli)));
                    setMemory(Integer.parseInt(ModelSubmissionOptions.MEMORY.get(cli)));
                    setPath(ModelSubmissionOptions.HDFS_MODEL_PATH.get(cli));
                }
            };
        } else if (mode.equalsIgnoreCase("REMOVE")) {
            request = new ModelRequest() {

                {
                    setName(ModelSubmissionOptions.NAME.get(cli));
                    setAction(Action.REMOVE);
                    setNumInstances(Integer.parseInt(ModelSubmissionOptions.NUM_INSTANCES.get(cli)));
                    setVersion(ModelSubmissionOptions.VERSION.get(cli));
                }
            };
        } else if (mode.equalsIgnoreCase("LIST")) {
            String name = ModelSubmissionOptions.NAME.get(cli, null);
            String version = ModelSubmissionOptions.VERSION.get(cli, null);
            ServiceDiscoverer serviceDiscoverer = new ServiceDiscoverer(client, config.getServiceRoot());
            Model model = new Model(name, version);
            Map<Model, List<ModelEndpoint>> endpoints = serviceDiscoverer.listEndpoints(model);
            for (Map.Entry<Model, List<ModelEndpoint>> kv : endpoints.entrySet()) {
                String modelTitle = "Model " + kv.getKey().getName() + " @ " + kv.getKey().getVersion();
                System.out.println(modelTitle);
                for (ModelEndpoint endpoint : kv.getValue()) {
                    System.out.println(endpoint);
                }
            }
        }
        if (ModelSubmissionOptions.LOCAL_MODEL_PATH.has(cli)) {
            File localDir = new File(ModelSubmissionOptions.LOCAL_MODEL_PATH.get(cli));
            Path hdfsPath = new Path(ModelSubmissionOptions.HDFS_MODEL_PATH.get(cli));
            updateHDFS(fs, localDir, hdfsPath);
        }
        Queue<ModelRequest> queue = config.createQueue(ImmutableMap.of(ZKQueue.ZK_CLIENT, client));
        queue.enqueue(request);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}
Also used : Path(org.apache.hadoop.fs.Path) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) CuratorFramework(org.apache.curator.framework.CuratorFramework) List(java.util.List) RetryPolicy(org.apache.curator.RetryPolicy) ServiceDiscoverer(org.apache.metron.maas.discovery.ServiceDiscoverer) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) AbstractMap(java.util.AbstractMap) File(java.io.File)

Example 72 with CuratorFramework

use of org.apache.curator.framework.CuratorFramework in project metron by apache.

the class ParserTopologyBuilder method getSensorParserConfig.

/**
 * Fetch the parser configuration from Zookeeper.
 *
 * @param zookeeperUrl Zookeeper URL
 * @param sensorType   Type of sensor
 * @param configs
 * @return
 * @throws Exception
 */
private static SensorParserConfig getSensorParserConfig(String zookeeperUrl, String sensorType, ParserConfigurations configs) throws Exception {
    try (CuratorFramework client = ConfigurationsUtils.getClient(zookeeperUrl)) {
        client.start();
        ConfigurationsUtils.updateParserConfigsFromZookeeper(configs, client);
        SensorParserConfig parserConfig = configs.getSensorParserConfig(sensorType);
        if (parserConfig == null) {
            throw new IllegalStateException("Cannot find the parser configuration in zookeeper for " + sensorType + "." + "  Please check that it exists in zookeeper by using the 'zk_load_configs.sh -m DUMP' command.");
        }
        return parserConfig;
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) SensorParserConfig(org.apache.metron.common.configuration.SensorParserConfig)

Example 73 with CuratorFramework

use of org.apache.curator.framework.CuratorFramework in project metron by apache.

the class DefaultStellarShellExecutor method createZookeeperClient.

/**
 * Creates a Zookeeper client.
 * @param zookeeperUrl The Zookeeper URL.
 */
private Optional<CuratorFramework> createZookeeperClient(Optional<String> zookeeperUrl) {
    Optional<CuratorFramework> client = Optional.empty();
    // can only create client, if have valid zookeeper URL
    if (zookeeperUrl.isPresent()) {
        String url = zookeeperUrl.get();
        if (StringUtils.isNotBlank(url)) {
            LOG.debug(String.format("Connecting to Zookeeper; url=%s", url));
            CuratorFramework c = ConfigurationsUtils.getClient(url);
            c.start();
            client = Optional.of(c);
        }
    }
    return client;
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework)

Example 74 with CuratorFramework

use of org.apache.curator.framework.CuratorFramework in project rocketmq-externals by apache.

the class RocketMQRedisReplicator method open.

@Override
public void open() throws IOException {
    if (this.replicator instanceof RedisSocketReplicator) {
        boolean single = configure.getString(DEPLOY_MODEL).equals(DEPLOY_MODEL_SINGLE);
        if (single) {
            this.replicator.open();
        } else {
            String address = configure.getString(CONFIG_PROP_ZK_ADDRESS);
            final CuratorFramework client = newClient(address, new ExponentialBackoffRetry(1000, 3));
            client.start();
            String path = ROOT_DIR + "/" + uri.getHost() + "-" + uri.getPort();
            final LeaderSelector selector = new LeaderSelector(client, path, new LeaderSelectorListenerAdapter() {

                @Override
                public void takeLeadership(final CuratorFramework client) throws Exception {
                    RocketMQRedisReplicator.this.addCloseListener(new CloseListener() {

                        @Override
                        public void handle(Replicator replicator) {
                            client.close();
                        }
                    });
                    replicator.open();
                }
            });
            selector.start();
        }
    } else {
        this.replicator.open();
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) LeaderSelector(org.apache.curator.framework.recipes.leader.LeaderSelector) LeaderSelectorListenerAdapter(org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 75 with CuratorFramework

use of org.apache.curator.framework.CuratorFramework in project hive by apache.

the class HiveServer2 method deleteServerInstancesFromZooKeeper.

/**
 * Remove all znodes corresponding to the given version number from ZooKeeper
 *
 * @param versionNumber
 * @throws Exception
 */
static void deleteServerInstancesFromZooKeeper(String versionNumber) throws Exception {
    HiveConf hiveConf = new HiveConf();
    String zooKeeperEnsemble = ZooKeeperHiveHelper.getQuorumServers(hiveConf);
    String rootNamespace = hiveConf.getVar(HiveConf.ConfVars.HIVE_SERVER2_ZOOKEEPER_NAMESPACE);
    int baseSleepTime = (int) hiveConf.getTimeVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_CONNECTION_BASESLEEPTIME, TimeUnit.MILLISECONDS);
    int maxRetries = hiveConf.getIntVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_CONNECTION_MAX_RETRIES);
    CuratorFramework zooKeeperClient = CuratorFrameworkFactory.builder().connectString(zooKeeperEnsemble).retryPolicy(new ExponentialBackoffRetry(baseSleepTime, maxRetries)).build();
    zooKeeperClient.start();
    List<String> znodePaths = zooKeeperClient.getChildren().forPath(ZooKeeperHiveHelper.ZOOKEEPER_PATH_SEPARATOR + rootNamespace);
    List<String> znodePathsUpdated;
    // Now for each path that is for the given versionNumber, delete the znode from ZooKeeper
    for (int i = 0; i < znodePaths.size(); i++) {
        String znodePath = znodePaths.get(i);
        deleteSignal = new CountDownLatch(1);
        if (znodePath.contains("version=" + versionNumber + ";")) {
            String fullZnodePath = ZooKeeperHiveHelper.ZOOKEEPER_PATH_SEPARATOR + rootNamespace + ZooKeeperHiveHelper.ZOOKEEPER_PATH_SEPARATOR + znodePath;
            LOG.warn("Will attempt to remove the znode: " + fullZnodePath + " from ZooKeeper");
            System.out.println("Will attempt to remove the znode: " + fullZnodePath + " from ZooKeeper");
            zooKeeperClient.delete().guaranteed().inBackground(new DeleteCallBack()).forPath(fullZnodePath);
            // Wait for the delete to complete
            deleteSignal.await();
            // Get the updated path list
            znodePathsUpdated = zooKeeperClient.getChildren().forPath(ZooKeeperHiveHelper.ZOOKEEPER_PATH_SEPARATOR + rootNamespace);
            // Gives a list of any new paths that may have been created to maintain the persistent ephemeral node
            znodePathsUpdated.removeAll(znodePaths);
            // Add the new paths to the znodes list. We'll try for their removal as well.
            znodePaths.addAll(znodePathsUpdated);
        }
    }
    zooKeeperClient.close();
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) HiveConf(org.apache.hadoop.hive.conf.HiveConf) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

CuratorFramework (org.apache.curator.framework.CuratorFramework)824 Test (org.testng.annotations.Test)290 RetryOneTime (org.apache.curator.retry.RetryOneTime)267 Test (org.junit.Test)168 Timing (org.apache.curator.test.Timing)147 CountDownLatch (java.util.concurrent.CountDownLatch)120 ExponentialBackoffRetry (org.apache.curator.retry.ExponentialBackoffRetry)98 KeeperException (org.apache.zookeeper.KeeperException)84 IOException (java.io.IOException)75 ConnectionState (org.apache.curator.framework.state.ConnectionState)70 CuratorEvent (org.apache.curator.framework.api.CuratorEvent)52 ConnectionStateListener (org.apache.curator.framework.state.ConnectionStateListener)50 RetryNTimes (org.apache.curator.retry.RetryNTimes)48 ExecutorService (java.util.concurrent.ExecutorService)47 ArrayList (java.util.ArrayList)44 RetryPolicy (org.apache.curator.RetryPolicy)36 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)35 Stat (org.apache.zookeeper.data.Stat)35 BackgroundCallback (org.apache.curator.framework.api.BackgroundCallback)33 CuratorFrameworkFactory (org.apache.curator.framework.CuratorFrameworkFactory)32